content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
How to Merge Two Views/ Teams?
Thank you both @Katie_Reynolds and @Julien_RENAUD for helping @annam!
I would definitely recommend adding your vote to Viewing all assigned tasks across multiple workspaces, but I also wanted to mention that some third party tool allows you to see your My Tasks for different Organization/Workspace in one place:
Hope this helps! Please let us know if you have any follow-up questions!
2 Likes
|
__label__pos
| 0.944265 |
Modulo
Find x in modulo equation:
47x = 4 (mod 9)
Hint - read as: what number 47x divided by 9 (modulo 9) give remainder 4 .
Correct result:
x = 2
Solution:
Our examples were largely sent or created by pupils and students themselves. Therefore, we would be pleased if you could send us any errors you found, spelling mistakes, or rephasing the example. Thank you!
Please write to us with your comment on the math problem or ask something. Thank you for helping each other - students, teachers, parents, and problem authors.
Showing 0 comments:
avatar
Tips to related online calculators
Do you solve Diofant problems and looking for a calculator of Diofant integer equations?
Do you have a linear equation or system of equations and looking for its solution? Or do you have quadratic equation?
You need to know the following knowledge to solve this word math problem:
Next similar math problems:
• Integer
abs1 Find the integer whose distance on the numerical axis from number 1 is two times smaller as the distance from number 6.
• Unknown x
UnknownX If we add to unknown number 21, then divide by 6 and then subtract 51, we get back an unknown number. What is this unknown number?
• 15 number
numbers_15 What number is smaller (greater) by 15 than its half?
• Mistake
minus Nicol mistake when calculate in school. Instead of add number 20 subtract it. What is the difference between the result and the right result?
• Balance of account
usd_6 Theo had a balance of -$4 in his savings account. After making a deposit, he has $25 in his account. What is the overall change to his account?
• Mysterious number
fun3_9 The magician thinks the number: "The mysterious number is first divided by minus five, dividing the result by three, multiplying the number by ten, and dividing the resulting number by minus four. This gives result 5. Can you reveal the mysterious number?
• Candy and boxes
cukriky_13 We have some number of candy and empty boxes. When we put candies in boxes of ten, there will be 2 candies and 8 empty boxes left, when of eight, there will be 6 candies and 3 boxes left. How many candy and empty boxes left when we put candies in boxes of
• Job applicants
workers Job applicants: three-fourths of applicants had experience for a position. The number that did not have prior experience was 36. How many people applied for the job?
• Positive integers
number_line Several positive integers are written on the paper. Michaella only remembered that each number was half the sum of all the other numbers. How many numbers could be written on paper?
• Two numbers 6
numbers_49 Fill two natural numbers a, b: 7 + blank- blank = 5
• Line
negative_slope Straight line passing through points A [-3; 22] and B [33; -2]. Determine the total number of points of the line which both coordinates are positive integers.
• Sequence
arithmetic_seq In the arithmetic sequence is a1=-1, d=4. Which member is equal to the number 203?
• Four integers
tiles2 Fnd four consecutive integers so that the product of the first two is 70 times smaller than the product of the next two.
• CZK coins
CZK-coins Thaddeus and Jolana together have 15 CZK. Jolana has half of Thaddeus money. Nevertheless Jolana has 3 coins and Thaddeus 2 coins. Which coin has Thaddeus and Jolana (Help: CZK coins has values 1,2,5,10,20,50 CZK)?
• Simplify
expr_3 Simplify expression - which expression is equivalent to: 3(m + 2) − 4(2m − 9)
• Equatiom
negativ_1 Solve equation with negatives: X/(-5) + 2 = -9
• Repairman
makak Repairman has vowed to do repair work at the plant for 25 days. However work had to be shortened, and therefore he took helper worker. Together they made all the corrections for the whole days. How long it would take work to helper worker?
|
__label__pos
| 0.987739 |
Archives for : 七月2024
第1293天:开发环境和生产环境复杂接口场景
由于历史原因,接口有点混乱,有的是开发环境和生产环境共用,有的有区分,被逼出了这么个解决方案,看上去不会出错了。
// 环境判断
const isProdEnv = xxxxxxx
// 域名列表
const server = ‘https://server.xxx.chat/’
const test = ‘https://test.xxx.chat/’
const www = ‘https://www.xxx.chat/’
const wx = ‘https://wx.xxx.chat/’
const api = ‘https://api.xxx.chat/’
export const baseUrls = {
basic: isProdEnv ? server : test,
login: isProdEnv ? www : www,
scene: isProdEnv ? www : wx,
message: isProdEnv ? server : server,
redirect: isProdEnv ? www : test,
pay: isProdEnv ? api : api,
socket: isProdEnv ? www : www,
}
|
__label__pos
| 0.999203 |
17/17 «Сколько гулять?» 100% Проверьте пожалуйста код
var temperature = 36;
var isRaining = true;
var minutes = 0;
if (!isRaining) {
if (temperature < 10) {
minutes = 0;
console.log(‘Очень холодно’);
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
if (temperature >= 10 && temperature < 15) {
minutes = 30;
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
if (temperature >= 15 && temperature < 25) {
minutes = 40;
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
if (temperature >= 25 && temperature <= 35) {
minutes = 20;
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
if (temperature > 35) {
console.log(‘Очень жарко’);
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
} else {
console.log(‘Идет дождь’);
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
Я вот так это реализовал.
var temperature=20;
var isRaining = true;
var minutes;
if (isRaining)
{
minutes = 0;
console.log=(‘Сижу дома, идет дождь’);
}
else (temperature>35 || temperature<10)
{
minutes = 0;
console.log=(‘Сижу дома, на улице не подходящая температура’);
}
if (!isRaining && temperature>=10 && temperature<15)
{
minutes=30;
console.log =(‘Гуляем -’+minutes+’ минут’);
}
if (!isRaining && temperature>=15 && temperature<25)
{
minutes=40;
console.log =(‘Гуляем -’+minutes+’ минут’);
}
if (!isRaining && temperature>=25 && temperature<=35)
{
minutes=20;
console.log =(‘Гуляем -’+minutes+’ минут’);
}
1 симпатия
вызов методов имеет такой синтаксис:
объект.метод(значение-аргумент);
поправьте вывод в консоль.
первое условие можно объединить с else, т.к. имеют одинаковое значение переменной.
!isRaining можно вывести общим условием, т.к. вы повторяете это в каждом последующем условии.
проще конечно сразу присвоить var minutes = 0; еще на этапе объявления переменной, чтобы не придумывать условия, когда Кекс не может выйти погулять
также, вывод в консоль в этой задаче не играет роли - для упрощения его можно опустить в коде и увести в комментарии (если этот вывод все еще имеет смысл)
Благодарю
Вот мой сжатый код, сразу таким написал.
var temperature = 20;
var isRaining = true;
var minutes = 0;
if (!isRaining){
if(temperature >= 10 && temperature < 15) {minutes = 30};
if(temperature >= 15 && temperature < 25) {minutes = 40};
if(temperature >= 25 && temperature <= 35) {minutes = 20};
};
var temperature = 13;
var isRaining = false;
var minutes = 0;
if (!isRaining) {
if (temperature >= 10 && temperature < 15) {
minutes = 30;
console.log(‘Гуляем ’ + minutes + ’ минут’);
}
if (temperature >= 15 && temperature < 25) {
minutes = 40;
console.log(‘Гуляем ’ + minutes + ’ минут’);
}
if (temperature >= 25 && temperature <= 35) {
minutes = 20;
console.log(‘Гуляем ’ + minutes + ’ минут’);
} else {
if (temperature < 10) {
console.log(‘Слишком холодно! Не гуляем!’);
}
if (temperature > 35) {
console.log(‘Слишком жарко! Не гуляем!’);
}
}
} else {
minutes = 0;
console.log(‘Идёт дождь! Не гуляем!’);
}
Я смог реализовать таким способом. Может кому поможет.
let temperature = 20;
let isRaining = true;
let minutes = 0;
if (!isRaining && temperature >= 10 && temperature <=35){
if (temperature < 15){
minutes = 30;
} else if (temperature >= 15 && temperature < 25){
minutes = 40;
} else {
minutes = 20;
}
} else {
minutes = 0;
}
Вот мой вариант, не уверен читабельность кода, но Кекс принял задачу.
let temperature = 20;
let isRaining = true;
let minutes = 0;
if (isRaining && temperature < 10) {
minutes = 0;
console.log(‘Очень холодно’);
}
else if (!isRaining && temperature >= 10 && temperature < 15) {
minutes = 30;
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
else if (!isRaining && temperature >= 15 && temperature < 25) {
minutes = 40;
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
else if (!isRaining && temperature >= 25 && temperature <= 35) {
minutes = 20;
console.log(‘Я гуляю ’ + minutes + ’ минут’);
}
else if (!isRaining && temperature > 35) {
console.log(‘Очень жарко’);
} else {
console.log(‘Идет дождь’);
console.log(‘Я гуляю ’ + minutes + ’ минут’);
};
Я так решила сделать
let temperature = 10;
let isRaining = false;
let minutes = 0;
if (!isRaining && temperature >= 10 && temperature <=35){
if (temperature < 15){
minutes = 30;
} else if (temperature >= 15 && temperature < 25){
minutes = 40;
} else {
minutes = 20;
}
console.log('Кекс идет гулять на ‘+ minutes + ’ минут’)
} else {
minutes = 0;
console.log(‘Кекс сидит дома’)
}
|
__label__pos
| 0.999998 |
Fungrim home page
Fungrim entry: 1f026d
tan (atan(z))=z\tan\!\left(\operatorname{atan}(z)\right) = z
Assumptions:zCz \in \mathbb{C}
TeX:
\tan\!\left(\operatorname{atan}(z)\right) = z
z \in \mathbb{C}
Definitions:
Fungrim symbol Notation Short description
Atanatan(z)\operatorname{atan}(z) Inverse tangent
CCC\mathbb{C} Complex numbers
Source code for this entry:
Entry(ID("1f026d"),
Formula(Equal(Tan(Atan(z)), z)),
Variables(z),
Assumptions(Element(z, CC)))
Topics using this entry
Copyright (C) Fredrik Johansson and contributors. Fungrim is provided under the MIT license. The source code is on GitHub.
2020-01-31 18:09:28.494564 UTC
|
__label__pos
| 0.994004 |
Skip Ribbon Commands
Skip to main content
Sign In
Repeating Rows Configuration
With the Repeating Rows column you can implement the following 2 common use-cases:
1. Multi-row form - this is done by connecting 2 lists, one is the "master", 2nd one hold the "details" items.
2. "Connected documents" - this is done by connecting a document library to a "master" list, this way users can upload and connect multiple documents to each list item.
Let's see how to configure the Repeating Rows column to support these 2 use-cases.
Configuring a multi-row form
To implement a multi-row form, follow the steps hereunder:
STEP 1: PREPARE YOUR LISTS
Before you create a Repeating Rows column, you need to have your connected lists – a “Master” list and a “Details” list.
In our example, we have the following 2 lists:
· Expense reports list – This is the “Master” list. Each item in this list is an expense report item, made by some employee.
The list includes the following columns:
o Employee
o Month
· Expense details list – This is the “Details” list. For each expense item in the Expense reports list, we have here multiple expense details items.
The list includes the following columns:
o Date
o Cost($)
o Expense type
o Expense details
Once you have your data model ready, it’s time to create your Repeating Rows column.
STEP 2: CREATE THE REPEATING ROWS COLUMN
In the “Master” list (Expense reports), create a Repeating Rows column that will display multiple rows from the “Details” list.
To do that, click the “Manage Repeating Rows” button to open the list’s Repeating Rows settings page:
IMPORTANT:
The Repeating Rows app relies on services provided by the KWizCom Apps Foundation app. When you browse the Repeating Rows settings page and KWizCom Apps Foundation is not installed, you will be prompted to install it.
For more details, please review the installation procedure section in this user guide.
Once you click the ribbon button, you’ll see the following settings page:
STEP 3: CONFIGURE THE REPEATING ROWS COLUMN
Configuring a Repeating Rows column is done by following the steps:
1. Select a repeating rows column
You can create new Repeating Rows column, or edit existing ones (if created before).
If you create a new column, type its name in the “New column title” textbox.
2. Decide how many rows should be displayed by this column by default
When you create a new item, the Repeating Rows column will display 3 empty rows by default, you can change that to any other number.
3. Decide if you want to allow end-users to add rows
You can allow users to add rows to the Repeating Rows column when they add/edit items. If you choose to allow users to add rows, you can also rename/translate the caption of the “add row” link that will appear below the Repeating Rows column in new/edit item forms.
4. Connect the Repeating Rows column to a target list
Select a list to which you want to connect your Repeating Rows column. In our example that would be the “Expense details” list.
IMPORTANT
The target list should be an empty list, used only to store the Repeating Rows items. If you connect the Repeating Rows field to a list that includes data in it, all the existing data items will be deleted.
5. Select which columns should be displayed in the Repeating Rows column
Click the box to add columns from the target list (“Expense details” list in our example) to the Repeating rows column. These columns will be displayed according to the order that they were added.
6. Configure columns’ layout and preview
Now you can see how the Repeating Rows column will look like (column order) by looking at the preview section at the bottom of the settings page.
You can also configure a column’s width*and add total function to selected columns.
To configure column width and/or a total function for it, simply click the icon – this will open the following popup:
SNAGHTML38618a73
Each total field will be also available as a Number column that can be displayed in the list views.
• Resizing field’s width is not available for Date, Boolean, Choice and Lookup columns since these columns have their width pre-defined and optimized
7. Save your settings
That’s it! Now you need to click “Update” to save your settings.
STEP 4: CHECK YOUR REPEATING ROWS COLUMN IN RUN-TIME
After you’ve created the Repeating Rows column it is time to check your configuration by simply creating a new item in your “Master” list.
In our example, we’ll create a new “Expense report” item:
So, now you can create/edit an expense report along with connected expense details rows.
Once you click the “Save” button the Expense report item will be saved, along with the expense details rows that will be saved in the “Expense details” list in our example.
COMMENT1
Upon clicking Save, empty rows will automatically be removed before the form data is saved.
COMMENT2
You should NOT edit items directly in the “Details” list to which the Repeating Rows field is connected, but only by using the Repeating Rows column in the “Master” list. If you edit these items directly in the “Details” list, the summary fields will not be display correctly. Also, if you add any items directly to the “Details” list – those items will be deleted by the Repeating Rows app cleanup job.
COMMENT3
Lookup fields that are included in the Repeating Rows column will display up to 2000 items. This limitation was set to prevent performance issues (because the Repeating Rows column might display many rows, each loading thousands of lookup items).
One more thing for you to check, is the existence of the summary fields as new columns available for list views:
So, you can display these summary fields in your list views just like any other column in your list.
Configuring connected documents
In the previous section we saw how to create a Repeating Rows column that connects to a “Details” list. In this section we’ll show a different scenario where you connect the Repeating Rows column to a “Details” document library. This enables you to connect multiple documents to an item and update them while you update your item:
SNAGHTML4e83461f
In the screenshot above you can see multiple documents can be connected to a single Issue item.
How is this different than SharePoint file attachments?
1. Since the actual documents are stored in a separate document library you can configure different permissions to selected documents, according to your requirements.
2. You can configure the Repeating Rows column to show selected properties of the connected documents (in attachments you don’t have any properties)
Setting up connected documents is very similar to what you saw in the previous section when we connected a master list to “Details” list, however when you select a document library in the “Select a target list” property you will see the following additional properties:
· Enter sub folder name:
you can have all connected documents grouped for better organization (rather then have them all as one huge pile of documents).
You can type a folder name or you can select a value from the “insert a column” drop down, which enables you to create a sub folder with a dynamic name, according to selected item column.
Example: if you want each item’s connected document to be saved under a sub-folder which its name equals the item’s ID, you should select the ID column:
· Show the file name in the repeating rows?
By default, repeating rows will simply show the file type icon, but you can show the file name if you like.
Repeating Rows column - A look behind the scenes
REPEATING ROWS COLUMN = LOOKUP COLUMN
When you create a Repeating Rows column in your list, the result is a lookup column that connects your “Master” list to a “Details” list.
Looking at our “Expense Reports” list columns, you can see that the “Expense Details” column that displays multiple rows in the list forms, is actually a regular Lookup columns:
This enables us to link between an item in the “Master” list and its connected multiple items in the “Details” list.
But that’s not all:
If you open one of the “Details” item, in our example an item in the “Expense details” list you will see a “Master Item” Lookup column:
This reverse Lookup column is automatically created in the “Details” list when you create the Repeating Rows column. We create it to enable you to navigate from a “Details” item to its “Master” item, or in our example: you can navigate from any expense details item to its expense report item.
SUMMARY FIELD = NUMBER-TYPE COLUMN
When you configure a Repeating Rows column you can create summary fields for selected .
In the screenshot below you can see that we have configured a summary field below the “Cost($)” column:
The result of this configuration, besides the fact that users will see this summary field while they create/edit and item, is that a Number-type column is created in the list for each summary field, so you can add these summary columns to your list views.
COMMENT
Summary fields are updated when you use the Repeating Rows column.
If you bypass it by updating the “Details” items directly from the “Details” list, the summary fields in the “Master” item will not get updated.
WHAT HAPPENS WHEN YOU DELETE AN ITEM?
There are several cases to consider:
1. What happens when you delete a “Master” item?
2. What happens when you delete a “Details” item in the Repeating Rows column?
· When you delete a “Master” item, you will be prompted with the following message:
Meaning: we do cascaded delete, so if you delete a “Master” item, we will delete all its connected items in the “Details” list (no point in leaving orphan items, right?)
· When you delete a “Details” item in the Repeating Rows column, it does not get deleted right away in the “Details” list. What happens instead is that its reverse Lookup that connects its “Master” item gets deleted, so it becomes orphan.
Why do we do it?
Because we cannot know for sure we really need to delete it until the user commits his action by saving the “Master” item form. If instead, he clicks “Cancel” after deleting a “Details” item, then we need to revert that deletion.
So, what we do is use aremote event receiver. That event handler will run the next time someone updates an item in the list, and will check for all orphan items in the “Details” list that need to be deleted, or need to be reconnected with their “Master items”.
So why are we telling this to you?
So you won’t be surprised to see that “Details” items that you deleted, are still there. Don’t worry, they will be deleted after several minutes, and will not appear in your forms anyway.
Details
Last modified at: 11/16/2020 7:10 AM
Last modified by: Nimrod Geva
Type: User-guide
Rating:
Article has been viewed 1223 times.
Also in this category
Powered by KWizCom WikiPlus
|
__label__pos
| 0.582558 |
多线程程序常见Bug剖析(下)
上一篇文章我们专门针对违反原子性(Atomicity Violation)的多线程程序Bug做了剖析,现在我们再来看看另一种常见的多线程程序Bug:违反执行顺序(Ordering Violation)。
简单来说,多线程程序各个线程之间交错执行的顺序的不确定性(Non-deterministic)是造成违反执行顺序Bug的根源[注1]。正是因为这个原因,程序员在编写多线程程序时就不能假设程序会按照你设想的某个顺序去执行,而是应该充分考虑到各种可能的顺序组合,从而采取正确的同步措施。
阅读全文>>
上一篇文章我们专门针对违反原子性(Atomicity Violation)的多线程程序Bug做了剖析,现在我们再来看看另一种常见的多线程程序Bug:违反执行顺序(Ordering Violation)。
简单来说,多线程程序各个线程之间交错执行的顺序的不确定性(Non-deterministic)是造成违反执行顺序Bug的根源[注1]。正是因为这个原因,程序员在编写多线程程序时就不能假设程序会按照你设想的某个顺序去执行,而是应该充分考虑到各种可能的顺序组合,从而采取正确的同步措施。
1. 违反执行顺序(Ordering Violation)
举例来说,下面这个来自Mozilla的多线程Bug产生的原因就是程序员错误地假设S1一定会在S2之前执行完毕,即在S2访问mThread之前S1一定已经完成了对mThread的初始化(因为线程2是由线程1创建的)。事实上线程2完全有可能执行的很快,而且S1这个初始化操作又不是原子的(因为需要几个时钟周期才能结束),从而在线程1完成初始化(即S1)之前就已经运行到S2从而导致Bug。
例1:
Thread 1 Thread 2
void init(...) void mMain(...)
{ ... { ...
S1: mThread= ...
PR_CreateThread(mMain, ...); S2: mState = mThread->State;
... ...
} }
上面这个例子是一个线程读一个线程写的情况,除此之外还有违反写-写顺序以及违反一组读写顺序的情况。例如下面这个程序,程序员错误的以为S2(写操作)一定会在S4(也是写操作)之前执行。但是实际上这个程序完全有可能先执行S4后执行S2,从而导致线程1一直hang在S3处:
例2:
Thread 1 Thread 2
int ReadWriteProc(...) void DoneWaiting(...)
{ {
... /*callback func of PBReadAsync*/
S1: PBReadAsync(&p);
S2: io_pending = TRUE; ...
... S4: io_pending = FALSE;
S3: while (io_pending) {...} ...
... }
}
下面这个是违反一组读写操作顺序的例子:程序员假设S2一定会在S1之前执行,但是事实上可能S1在S2之前执行,从而导致程序crash。
例3:
Thread 1 Thread 2
void js_DestroyContext(...){ void js_DestroyContext(...){
/* last one entering this func */ /* non-last one entering this func */
S1: js_UnpinPinnedAtom(&atoms); S2: js_MarkAtom(&atoms,...);
} }
调试违反执行顺序这种类型的Bug最困难的地方就在只有某几种执行顺序才会引发Bug,这大大降低了Bug重现的几率。最简单的调试手段自然是使用printf了,但是类似printf这样的函数会干扰程序的执行顺序,所以有可能违反执行顺序的Bug更难产生了。我所知道的目前最领先的商业多线程Debugger是Corensic的Jinx,他们的技术核心是用Hypervisor来控制线程的执行顺序以找出可能产生Bug的那些特定的执行顺序(学生、开源项目可以申请免费使用,Windows/Linux版均有)。八卦一下,这个公司是从U of Washington发展出来的,他们现在做的Deterministic Parallelism是最热门的方向之一。
2. Ordering Violation的解决方案
常见的解决方案主要有四种:
(1)加锁进行同步
加锁的目的就在于保证被锁住的操作的原子性,从而这些被锁住的操作就不会被别的线程的操作打断,在一定程度上保证了所需要的执行顺序。例如上面第二个例子可以给{S1,S2}一起加上锁,这样就不会出现S4打断S1,S2的情况了(即S1->S4->S2),因为S4是由S1引发的异步调用,S4肯定会在{S1,S2}这个原子操作执行完之后才能被运行。
(2)进行条件检查
进行条件检查是另一种常见的解决方案,关键就在于通过额外的条件语句来迫使该程序会按照你所想的方式执行。例如下面这个例子就会对n的值进行检查:
例4:
retry:
n = block->n;
...
...
if (n!=block->n)
{
goto retry;
}
...
(3)调整代码执行顺序
这个也是很可行的方案,例如上面的例2不需要给{S1,S2}加锁,而是直接调换S2与S1的顺序,这样S2就一定会在S4之前执行了!
(4)重新设计算法/数据结构
还有一些执行顺序的问题可以通过重新设计算法/数据结构来解决。这个就得具体情况具体分析了。例如MySQL的bug #7209中,一个共享变量HASH::current_record的访问有顺序上的冲突,但是实际上这个变量不需要共享,所以最后的解决办法就是线程私有化这个变量。
3. 总结
多线程Bug确实是个非常让人头痛的问题。写多线程程序不难,难的在于写正确的多线程程序。多线程的debug现在仍然可以作为CS Top10学校的博士论文题目。在看过这两篇分析多线程常见Bug的文章之后,不知道各位同学有没有什么关于多线程Bug的经历与大家分享呢?欢迎大家留言:)
需要注意的是,违反执行顺序和违反原子性这两种Bug虽然是相互独立的,但是两者又有着潜在的联系。例如,上一篇文章中我所讲到的第一个违反原子性的例子其实是因为执行顺序的不确定性造成的,而本文的第二个例子就可以通过把{S1,S2}加锁保证原子性来保证想要的执行顺序。
参考
[1] Learning from Mistakes – A Comprehensive Study on Real World Concurrency Bug Characteristics
[2] Understanding, Detecting and Exposing Concurrency Bugs
[3] Practical Parallel and Concurrent Programming
[4] Java concurrency bug patterns for multicore systems
注1:严格来讲,多线程交错执行顺序的不确定性只是违反执行顺序Bug的原因之一。另一个可能造成违反执行顺序Bug的原因是编译器/CPU对代码做出的违反多线程程序语义的乱序优化,这种“错误的优化”直接引出了编程语言的内存模型(memory model)这个关键概念。后面我会专门分析下C++与Java的内存模型,敬请期待。
多线程程序常见Bug剖析(上)
编写多线程程序的第一准则是先保证正确性,再考虑优化性能。本文重点分析多线程编程中除死锁之外的两种常见Bug:违反原子性(Atomicity Violation)和违反执行顺序(Ordering Violation)。现在已经有很多检测多线程Bug的工具,但是这两种Bug还没有工具能完美地帮你检测出来,所以到目前为止最好的办法还是程序员自己有意识的避免这两种Bug。本文的目的就是帮助程序员了解这两种Bug的常见形式和常见解决办法。
阅读全文>>
编写多线程程序的第一准则是先保证正确性,再考虑优化性能。本文重点分析多线程编程中除死锁之外的另两种常见Bug:违反原子性(Atomicity Violation)和违反执行顺序(Ordering Violation)。现在已经有很多检测多线程Bug的工具,但是这两种Bug还没有工具能完美地帮你检测出来,所以到目前为止最好的办法还是程序员自己有意识的避免这两种Bug。本文的目的就是帮助程序员了解这两种Bug的常见形式和常见解决办法。
1. 多线程程序执行模型
在剖析Bug之前,我们先来简单回顾一下多线程程序是怎么执行的。从程序员的角度来看,一个多线程程序的执行可以看成是每个子线程的指令交错在一起共同执行的,即Sequential Consistency模型。它有两个属性:每个线程内部的指令是按照代码指定的顺序执行的(Program Order),但是线程之间的交错顺序是任意的、不确定的(Non deterministic)。
我原来举过一个形象的例子。伸出你的双手,掌心面向你,两个手分别代表两个线程,从食指到小拇指的四根手指头分别代表每个线程要依次执行的四条指令。
(1)对每个手来说,它的四条指令的执行顺序必须是从食指执行到小拇指
(2)你两个手的八条指令(八个手指头)可以在满足(1)的条件下任意交错执行(例如可以是左1,左2,右1,右2,右3,左3,左4,右4,也可以是左1,左2,左3,左4,右1,右2,右3,右4,也可以是右1,右2,右3,左1,左2,右4,左3,左4等等等等)
好了,现在让我们来看看程序员在写多线程程序时是怎么犯错的。
2. 违反原子性(Atomicity Violation)
何谓原子性?简单的说就是不可被其他线程分割的操作。大部分程序员在编写多线程程序员时仍然是按照串行思维来思考,他们习惯性的认为一些简单的代码肯定是原子的。
例如:
Thread 1 Thread 2
S1: if (thd->proc_info) ...
{ S3: thd->proc_info=NULL;
S2: fputs(thd->proc_info,...)
}
这个来自MySQL的Bug的根源就在于程序员误认为,线程1在执行S1时如果从thd->proc_info读到的是一个非空的值的话,在执行S2时thd->proc_info的值肯定也还是非空的,所以可以调用fputs()进行操作。事实上,{S1,S2}组合到一起之后并不是原子操作,所以它们可能被线程2的S3打断,即按S1->S3->S2的顺序执行,从而导致线程1运行到S2时出错(注意,虽然这个Bug是因为多线程程序执行顺序的不确定性造成的,可是它违反的是程序员对这段代码是原子的期望,所以这个Bug不属于违反顺序性的Bug)。
这个例子的对象是两条语句,所以很容易看出来它们的组合不是原子的。事实上,有些看起来像是原子操作的代码其实也不是原子的。最著名的莫过于多个线程执行类似“x++”这样的操作了。这条语句本身不是原子的,因为它在大部分硬件平台上其实是由三条语句实现的:
mov eax,dword ptr [x]
add eax,1
mov dword ptr [x],eax
同样,下面这个“r.Location = p”也不是原子的,因为事实上它是两个操作:“r.Location.X = p.X”和“r.Location.Y = p.Y”组成的。
struct RoomPoint {
public int X;
public int Y;
}
RoomPoint p = new RoomPoint(2,3);
r.Location = p;
从根源上来讲,如果你想让这段代码真正按照你的心意来执行,你就得在脑子里仔细考虑是否会出现违反你本意的执行顺序,特别是涉及的变量(例如thd->proc_info)在其他线程中有可能被修改的情况,也就是数据竞争(Data Race)[注1]。如果有两个线程同时对同一个内存地址进行操作,而且它们之中至少有一个是写操作,数据竞争就发生了。
有时候数据竞争可是隐藏的很深的,例如下面的Parallel.For看似很正常:
Parallel.For(0, 10000,
i => {a[i] = new Foo();})
实际上,如果我们去看看Foo的实现:
class Foo {
private static int counter;
private int unique_id;
public Foo()
{
unique_id = counter++;
}
}
同志们,看出来哪里有数据竞争了么?是的,counter是静态变量,Foo()这个构造函数里面的counter++产生数据竞争了!想避免Atomicity Violation,其实根本上就是要保证没有数据竞争(Data Race Free)。
3. Atomicity Violation的解决方案
解决方案大致有三(可结合使用):
(1)把变量隔离起来:只有一个线程可以访问它(isolation)
(2)把变量的属性定义为immutable的:这样它就是只读的了(immutability)
(3)同步对这个变量的读写:比如用锁把它锁起来(synchronization)
例如下面这个例子里面x是immutable的;而a[]则通过index i隔离起来了,即不同线程处理a[]中不同的元素;
Parallel.For(1,1000,
i => {
a[i] = x;
});
例如下面这个例子在构造函数中给x和y赋值(此时别的线程不能访问它们),保证了isolation;一旦构造完毕x和y就是只读的了,保证了immutability。
public class Coordinate
{
private double x, y;
public Coordinate(double a,
double b)
{
x = a;
y = b;
}
public void GetX() {
return x;
}
public void GetY() {
return y;
}
}
而我最开始提到的关于thd->proc_info的Bug可以通过把S1和S2两条语句用锁包起来解决(同志们,千万别忘了给S3加同一把锁,要不然还是有Bug!)。被锁保护起来的临界区在别的线程看来就是“原子”的,不可以被打断的。
Thread 1 Thread 2
LOCK(&lock)
S1: if (thd->proc_info) LOCK(&lock);
{ S3: thd->proc_info=NULL;
S2: fputs(thd->proc_info,...) UNLOCK(&lock);
}
UNLOCK(&lock)
还有另一个用锁来同步的例子,即通过使用锁(Java中的synchronized关键字)来保证没有数据竞争:
“Java 5 中提供了 ConcurrentLinkedQueue 来简化并发操作。但是有一个问题:使用了这个类之后是否意味着我们不需要自己进行任何同步或加锁操作了呢?
也就是说,如果直接使用它提供的函数,比如:queue.add(obj); 或者 queue.poll(obj);,这样我们自己不需要做任何同步。”但是,两个原子操作合起来可就不一定是原子操作了(Atomic + Atomic != Atomic),例如:
if(!queue.isEmpty()) {
queue.poll(obj);
}
事实情况就是在调用isEmpty()之后,poll()之前,这个queue没有被其他线程修改是不确定的,所以对于这种情况,我们还是需要自己同步,用加锁的方式来保证原子性(虽然这样很损害性能):
synchronized(queue) {
if(!queue.isEmpty()) {
queue.poll(obj);
}
}
但是注意了,使用锁也会造成一堆Bug,死锁就先不说了,先看看初学者容易犯的一个错误(是的,我曾经也犯过这个错误),x在两个不同的临界区中被修改,加了锁跟没加一样,因为还是有数据竞争:
int x = 0;
pthread_mutex_t lock1;
pthread_mutex_t lock2;
pthread_mutex_lock(&lock1);
x++;
pthread_mutex_unlock(&lock1);
...
...
pthread_mutex_lock(&lock2);
x++;
pthread_mutex_unlock(&lock2);
事实上,类似x++这样的操作最好的解决办法就是使用类似java.util.concurrent.atomic,Intel TBB中的atomic operation之类的方法完成,具体的例子可以参考这篇文章
总结一下,不管是多条语句之间的原子性也好,单个语句(例如x++)的原子性也好都需要大家格外小心,有这种意识之后很多跟Atomicity Violation相关的Bug就可以被避免了。其实归根结底,我们最终是想让多线程程序按照你的意愿正确的执行,所以在清楚什么样的情形可能让你的多线程程序不能按你所想的那样执行之后我们就能有意识的避免它们了(或者更加容易的修复它们)。下一篇文章我们再来仔细分析下Ordering Violation。
[注1] 严格意义上来讲,Data Race只是Atomicity Violation的一个特例,Data Race Free不能保证一定不会出现Atomicity Violation。例如文中Java实现的那个Concurrent Queue的例子,严格意义上来讲它并没有data race,因为isEmpty()和poll()都是线程安全的调用,只不过它们组合起来之后会出现违反程序员本意的Atomicity Violation,所以要用锁保护起来。
P.S. 参考文献中的前两篇是YuanYuan Zhou教授的得意门生Dr. Shan Lu的论文,后者现在已经是Wisconsin–Madison的教授了。
|
__label__pos
| 0.757784 |
利用Python对mysql进行读写操作,创建数据库,插入数据,更新数据,删除数据等操作。
连接数据库
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import MySQLdb
#打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
#使用cursor()方法获取操作游标
cursor = db.cursor()
#使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
#使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print "Database version : %s " % data
#关闭数据库连接
db.close()
创建数据库表
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import MySQLdb
#打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
#使用cursor()方法获取操作游标
cursor = db.cursor()
#如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
#创建数据表SQL语句
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
#关闭数据库连接
db.close()
数据库插入操作
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import MySQLdb
#打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
#使用cursor()方法获取操作游标
cursor = db.cursor()
#SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
#执行sql语句
cursor.execute(sql)
#提交到数据库执行
db.commit()
except:
#Rollback in case there is any error
db.rollback()
#关闭数据库连接
db.close()
数据库查询操作
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import MySQLdb
#打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
#使用cursor()方法获取操作游标
cursor = db.cursor()
#SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %s" % (1000)
try:
#执行SQL语句
cursor.execute(sql)
#获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
#打印结果
print "fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
#关闭数据库连接
db.close()
数据库更新操作
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import MySQLdb
#打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
#使用cursor()方法获取操作游标
cursor = db.cursor()
#SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
#执行SQL语句
cursor.execute(sql)
#提交到数据库执行
db.commit()
except:
#发生错误时回滚
db.rollback()
#关闭数据库连接
db.close()
删除操作
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import MySQLdb
#打开数据库连接
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
#使用cursor()方法获取操作游标
cursor = db.cursor()
#SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try:
#执行SQL语句
cursor.execute(sql)
#提交修改
db.commit()
except:
#发生错误时回滚
db.rollback()
#关闭连接
db.close()
Last modification:February 29th, 2020 at 12:47 pm
正在沿街乞讨中……
|
__label__pos
| 0.991027 |
5
$\begingroup$
Let $\alpha \in \mathbb{R}^n$, $n \geq 2$, be a non-zero vector. Define a reflection in the hyperplane perpendicular to $\alpha$ by: $$\sigma_{\alpha}(v) = v - \dfrac{2(v, \alpha)}{(\alpha, \alpha)} \cdot \alpha$$ ($(x, y)$ is the usual inner product on $\mathbb{R}^n$).
1) Show $\sigma_{\alpha}$ is a linear map that fixes the hyperplane orthogonal to $\alpha$ and sends $\alpha$ to $-\alpha$.
2) Given $\alpha, \beta$ non-zero vectors, determine when the subgroup $\langle \sigma_{\alpha}, \sigma_{\beta} \rangle$ is infinite. Find its order when it is finite.
For 2) I don't understand what the group is. If $\sigma_{\alpha}$ and $\sigma_{\beta}$ are elements of a group, what other elements do they generate? Like for example, $\sigma_{\alpha}(\sigma_{\beta}(v)) = \left(v - \dfrac{2(v, \beta)}{(\beta, \beta)} \cdot \beta \right) - \dfrac{2\left(v - \dfrac{2(v, \beta)}{(\beta, \beta)} \cdot \beta, \beta \right)}{(\beta, \beta)} \cdot \beta$ which I guess makes sense (in the sense that dot products work in this function since the dot product is between vectors). But how do I know when there will be an infinite many number of these, and when there will be finitely many?
I can't even find an identity function $\sigma$, because a composition of $\sigma_{\alpha}$ and $\sigma_{\beta}$ is $\sigma_{\beta}$ only when $\sigma_{\alpha} = v$, but this is a constant function and does not reflect $\alpha$ about the hyperplane to $-\alpha$, so this constant function cannot be in the group.
$\endgroup$
• $\begingroup$ I don't want to keep pinging Lee by using his nice answer. Essentially, the span of $\alpha$ and $\beta$ should tell you everything you need to know. Just think about two vectors in $\Bbb R^2$, and think about reflecting across their normals. Keep dihedral groups in mind. If I can do it well, I may elaborate in an answer (probably not soon). $\endgroup$ – pjs36 Sep 23 '15 at 22:06
• $\begingroup$ @pjs36 If the two vectors are not normal to each other, then if you reflect a vector $\alpha$ across its normal, this reflected vector is not normal to the other vector $\beta$ so you can't reflect across the normal of $\beta$, right? $\endgroup$ – mr eyeglasses Sep 23 '15 at 22:30
1
$\begingroup$
Get some intuition from three dimensions first. Say the intersection of the two planes is the axis spanned by $\gamma$. Then $\{\alpha,\beta,\gamma\}$ is a basis, and the reflections only act on the $\alpha$ and $\beta$ components of any vector. This generalizes: prove that ${\rm span}\{\alpha,\beta\}$ is the orthogonal complement of the planes' intersection.
(More generally, $A^\perp\cap B^\perp=(A+B)^\perp$ for any subspaces $A,B$ of an inner product space.)
So really, you only need to worry about what the reflections do to the plane $\alpha$ and $\beta$ generate. That's only two dimensions to worry about. Without loss of generality, say one reflection is across the $x$-axis and the other is across the line $y=\tan(\theta)x$ (which makes an angle of $\theta$ with the $x$-axis). What exactly is the composition of the two reflections then?
If it helps, draw these two lines on a piece of paper, and put a point $P$ just under the $x$-axis in the fourth quadrant. Reflect across the $x$-axis to get a point $Q$, then reflect across the other line to get point $R$. If you label all of the angles made (between the lines and the imaginary line segments joining the origin to the three points) you should be able to make some deductions about the angles, and then get an idea for what the composition of the two reflections is.
(Spoiler: you'll be thinking about $n$-gons and dihedral groups soon after that.)
$\endgroup$
• $\begingroup$ Say one hyperplane is on the $x-axis$ and another hyperplane is $\tan(\theta)x$. Then if a vector is on the $y-axis$, then it gets reflected to the other side of the $y-axis$ by the hyperplane on the $x-axis$ because it is orthogonal to it. Then this vector doesn't get reflected across the $\tan(\theta)x$ hyperplane because it isn't orthogonal to it. So the composition of the two reflections is just one of the reflections since the other reflection doesn't do anything to it. But then I get a contradiction in that every element of the group is the identity. $\endgroup$ – mr eyeglasses Sep 25 '15 at 11:28
• $\begingroup$ For example, look at my picture: i.imgur.com/j3Ns9kL.png The red and blue lines are the hyperplane, and the orange is a vector. The orange vector gets reflected across the red hyperplane because it is orthogonal to the red hyperplane, but it does not get reflected across the blue hyperplane because it is not orthogonal to it. So the composition doesn't do anything $\endgroup$ – mr eyeglasses Sep 25 '15 at 11:50
• 1
$\begingroup$ @morphic We have a big problem: you don't know what a reflection is. When applying a reflection across a plane, the only points in all of space that don't get moved are the points on that plane. Reflections flip all other points to their mirror images across the plane - the nature of this operation should be geometrically obvious. Based on my reading of the comments under Lee's answer, you're not simply confused about where to go next, you're also saying a lot of things that don't make any sense or are just plain wrong - I suggest reviewing all the basic concepts that are in play here. $\endgroup$ – whacka Sep 25 '15 at 13:30
• $\begingroup$ I understand a general reflection across a plane, but in the problem it states that "...reflection in the hyperplane $\textbf{perpendicular to}$..." so I thought that meant it reflects vectors across the hyperplane only when the vector is perpendicular to the hyperplane. I guess I am misunderstanding? $\endgroup$ – mr eyeglasses Sep 25 '15 at 13:34
• 1
$\begingroup$ The hyperplane itself is perpendicular to the given vector. It's not saying the only vectors that get moved are the ones perpendicular to the vectors that make up the plane. That wouldn't be a reflection (or even a continuous map, since it permutes points on a line but fixes every point on a tubular neighborhood around the line). If $\alpha$ is a vector, then $\alpha^\perp$ is a plane (through the origin), and by definition $\sigma_\alpha$ is reflection across $\alpha^\perp$. Also, as a good exercise, you should verify the formula it gives for $\sigma_\alpha$ if at all possible. $\endgroup$ – whacka Sep 25 '15 at 13:36
3
$\begingroup$
For your first subquestion of 1), the hyperplane is described in the question: it is the hyperplane orthogonal to $\alpha$. You know from linear algebra that this hyperplane is the solution of the equation $\alpha \cdot v = 0$. So your goal is to take any $v$ in that hyperplane, i.e. take any $\nu$ such that $\alpha\cdot v=0$, and prove the equation $\sigma_\alpha(v)=v$.
For your second subquestion of 1), $\alpha$ is a vector, and it is a constant, so it is a constant vector (unlike $v$ which is a vector, and it is a variable, so it is a variable vector). To say that a function $f$ sends $a$ to $b$ means $f(a)=b$. So to say that the function $\sigma_\alpha$ sends $\alpha$ to $-\alpha$ means that $\sigma_\alpha(\alpha)=-\alpha$. That's the equation you are asked to prove.
For 2), you are correct that a function is not a group, but the question does not ask you to believe that a function is a group. Instead, the question asks you to believe that the set of all linear isomorphisms of $\mathbb{R}^n$ is a group under the binary operation of composition --- you may have heard of this group, it is denoted $GL(n,\mathbb{R})$. Also, you are asked to believe that if $\alpha$ is a constant vector then $\sigma_\alpha$ is an element of the group $GL(n,\mathbb{R})$. Also, if you fix two constant vectors $\alpha$ and $\beta$, then you are asked to believe that there is a subgroup of $GL(n,\mathbb{R})$ denoted $\langle \sigma_\alpha,\sigma_\beta \rangle$ and called the subgroup of $GL(n,\mathbb{R})$ that is generated by $\sigma_\alpha,\sigma_\beta$.
$\endgroup$
• $\begingroup$ Thank you. I'm only having trouble visualizing the subgroup now. I don't understand what $\sigma_\alpha,\sigma_\beta$ generates. Or even what $\sigma_\alpha$ generates. I know that $GL(n, \mathbb{R})$ is the group of invertible matrices of size $n x n$. I actually don't have much linear algebra background, but I believe these matrices can represent linear maps. Anyway, I can't seem to visualize functions like $\sigma_\alpha$ as matrices. So if $\alpha$ is some fixed vector, then $\endgroup$ – mr eyeglasses Sep 23 '15 at 20:37
• $\begingroup$ then $\sigma_\alpha$ reflects the hyperplane orthogonal to $\alpha$ (sort of like flipping the hyperplane, but retaining its position). So if we have two of these fixed vectors $\alpha$ and $\beta$, we have two different hyperplanes, unless $\alpha$ and $\beta$ are parallel to each other in which case we have the same hyperplane. What exactly are the group elements here? $\sigma_\alpha(v)$ for each $v$ is an element of the group? $\endgroup$ – mr eyeglasses Sep 23 '15 at 20:39
• $\begingroup$ No, @morphic, $\sigma_\alpha(v)$ is a vector, your group elements should be linear maps; things that move vectors around. I'll say that I think you should focus on the subspace $\operatorname{span}(\alpha, \beta)$, as it will be fixed by the group generated by those reflections. $\endgroup$ – pjs36 Sep 23 '15 at 21:43
• $\begingroup$ @pjs36 Sorry I meant that $\sigma_\alpha$ is an element (since it is a linear map). What is the intuition behind when the subgroup has infinite or finite order? $\endgroup$ – mr eyeglasses Sep 23 '15 at 21:55
• 1
$\begingroup$ Look at the formula for $\sigma_\alpha$. Then look at the formula for $\sigma_\alpha^2 = \sigma_\alpha \circ \sigma_\alpha$. Then look at the formula for $\sigma_\alpha^3 = \sigma_\alpha^2 \circ \sigma_\alpha$. Then look at ………………………. And, an infinite amount of time later when you've got all those formulas in front of you, compare the results to the formula for the identity element of the group. $\endgroup$ – Lee Mosher Sep 23 '15 at 22:37
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.956235 |
aboutsummaryrefslogtreecommitdiff
path: root/form/fty_ipv4.c
blob: 5d1a2098ef94b098fa08234d3febd5d0185a1139 (plain) (blame)
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
/****************************************************************************
* Copyright (c) 1998-2004,2006 Free Software Foundation, Inc. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, distribute with modifications, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included *
* in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
* IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/***************************************************************************
* *
* Author : Per Foreby, [email protected] *
* *
***************************************************************************/
#include "form.priv.h"
MODULE_ID("$Id: fty_ipv4.c,v 1.8 2006/12/02 19:33:02 tom Exp $")
/*---------------------------------------------------------------------------
| Facility : libnform
| Function : static bool Check_IPV4_Field(
| FIELD * field,
| const void * argp)
|
| Description : Validate buffer content to be a valid IP number (Ver. 4)
|
| Return Values : TRUE - field is valid
| FALSE - field is invalid
+--------------------------------------------------------------------------*/
static bool
Check_IPV4_Field(FIELD *field, const void *argp GCC_UNUSED)
{
char *bp = field_buffer(field, 0);
int num = 0, len;
unsigned int d1, d2, d3, d4;
if (isdigit(UChar(*bp))) /* Must start with digit */
{
num = sscanf(bp, "%u.%u.%u.%u%n", &d1, &d2, &d3, &d4, &len);
if (num == 4)
{
bp += len; /* Make bp point to what sscanf() left */
while (isspace(UChar(*bp)))
bp++; /* Allow trailing whitespace */
}
}
return ((num != 4 || *bp || d1 > 255 || d2 > 255
|| d3 > 255 || d4 > 255) ? FALSE : TRUE);
}
/*---------------------------------------------------------------------------
| Facility : libnform
| Function : static bool Check_IPV4_Character(
| int c,
| const void *argp )
|
| Description : Check a character for unsigned type or period.
|
| Return Values : TRUE - character is valid
| FALSE - character is invalid
+--------------------------------------------------------------------------*/
static bool
Check_IPV4_Character(int c, const void *argp GCC_UNUSED)
{
return ((isdigit(UChar(c)) || (c == '.')) ? TRUE : FALSE);
}
static FIELDTYPE typeIPV4 =
{
_RESIDENT,
1, /* this is mutable, so we can't be const */
(FIELDTYPE *)0,
(FIELDTYPE *)0,
NULL,
NULL,
NULL,
Check_IPV4_Field,
Check_IPV4_Character,
NULL,
NULL
};
NCURSES_EXPORT_VAR(FIELDTYPE*) TYPE_IPV4 = &typeIPV4;
/* fty_ipv4.c ends here */
|
__label__pos
| 0.936702 |
Statique
Astuce
Cette page décrit l'utilisation du mot clé static qui permet de définir des méthodes et des propriétés statiques. static peut aussi être utilisé pour définir des variables statiques et pour finir des liaisons statiques. Reportez-vous à ces pages pour plus d'informations sur la significations de static.
Le fait de déclarer des propriétés ou des méthodes comme statiques vous permet d'y accéder sans avoir besoin d'instancier la classe. On ne peut accéder à une propriété déclarée comme statique avec l'objet instancié d'une classe (bien que ce soit possible pour une méthode statique).
Pour des raisons de compatibilité avec PHP 4, si aucune déclaration de visibilité n'est spécifiée, alors la propriété ou la méthode sera automatiquement considérée comme public.
Comme les méthodes statiques peuvent être appelées sans qu'une instance d'objet n'ai été créée, la pseudo-variable $this n'est pas disponible dans les méthodes déclarées comme statiques.
On ne peut pas accéder à des propriétés statiques à travers l'objet en utilisant l'opérateur ->.
L'appel statique de méthodes non-statiques génère une erreur de niveau E_STRICT.
Comme n'importe quelle autre variable PHP statique, les propriétés statiques ne peuvent être initialisées qu'en utilisant un littéral ou une constante ; les expressions ne sont pas permises. Ainsi, vous pouvez initialiser une propriété statique avec un entier ou un tableau, mais pas avec une autre variable, ni avec la valeur de retour d'une fonction, ni avec un objet.
Depuis PHP 5.3.0, il est possible de référencer la classe en utilisant une variable. La valeur de la variable ne peut être un mot-clé (e.g. self, parent et static).
Exemple #1 Exemple avec une propriété statique
<?php
class Foo
{
public static
$my_static 'foo';
public function
staticValue() {
return
self::$my_static;
}
}
class
Bar extends Foo
{
public function
fooStatic() {
return
parent::$my_static;
}
}
print
Foo::$my_static "\n";
$foo = new Foo();
print
$foo->staticValue() . "\n";
print
$foo->my_static "\n"; // "Propriété" my_static non définie
print $foo::$my_static "\n";
$classname 'Foo';
print
$classname::$my_static "\n"// Depuis PHP 5.3.0
print Bar::$my_static "\n";
$bar = new Bar();
print
$bar->fooStatic() . "\n";
?>
Exemple #2 Exemple avec une méthode statique
<?php
class Foo
{
public static function
aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname 'Foo';
$classname::aStaticMethod(); // Depuis PHP 5.3.0
?>
add a note add a note
User Contributed Notes 42 notes
up
50
inkredibl
7 years ago
Note that you should read "Variables/Variable scope" if you are looking for static keyword use for declaring static variables inside functions (or methods). I myself had this gap in my PHP knowledge until recently and had to google to find this out. I think this page should have a "See also" link to static function variables.
http://www.php.net/manual/en/language.variables.scope.php
up
14
aidan at php dot net
9 years ago
To check if a function was called statically or not, you'll need to do:
<?php
function foo () {
$isStatic = !(isset($this) && get_class($this) == __CLASS__);
}
?>
More at (http://blog.phpdoc.info/archives/4-Schizophrenic-Methods.html).
(I'll add this to the manual soon).
up
5
ssj dot narutovash at gmail dot com
7 years ago
It's come to my attention that you cannot use a static member in an HEREDOC string. The following code
class A
{
public static $BLAH = "user";
function __construct()
{
echo <<<EOD
<h1>Hello {self::$BLAH}</h1>
EOD;
}
}
$blah = new A();
produces this in the source code:
<h1>Hello {self::}</h1>
Solution:
before using a static member, store it in a local variable, like so:
class B
{
public static $BLAH = "user";
function __construct()
{
$blah = self::$BLAH;
echo <<<EOD
<h1>Hello {$blah}</h1>
EOD;
}
}
and the output's source code will be:
<h1>Hello user</h1>
up
17
payal001 at gmail dot com
3 years ago
Here statically accessed property prefer property of the class for which it is called. Where as self keyword enforces use of current class only. Refer the below example:
<?php
class a{
static protected
$test="class a";
public function
static_test(){
echo static::
$test; // Results class b
echo self::$test; // Results class a
}
}
class
b extends a{
static protected
$test="class b";
}
$obj = new b();
$obj->static_test();
?>
up
12
webmaster at removethis dot weird-webdesign dot de
5 years ago
On PHP 5.2.x or previous you might run into problems initializing static variables in subclasses due to the lack of late static binding:
<?php
class A {
protected static
$a;
public static function
init($value) { self::$a = $value; }
public static function
getA() { return self::$a; }
}
class
B extends A {
protected static
$a; // redefine $a for own use
// inherit the init() method
public static function getA() { return self::$a; }
}
B::init('lala');
echo
'A::$a = '.A::getA().'; B::$a = '.B::getA();
?>
This will output:
A::$a = lala; B::$a =
If the init() method looks the same for (almost) all subclasses there should be no need to implement init() in every subclass and by that producing redundant code.
Solution 1:
Turn everything into non-static. BUT: This would produce redundant data on every object of the class.
Solution 2:
Turn static $a on class A into an array, use classnames of subclasses as indeces. By doing so you also don't have to redefine $a for the subclasses and the superclass' $a can be private.
Short example on a DataRecord class without error checking:
<?php
abstract class DataRecord {
private static
$db; // MySQLi-Connection, same for all subclasses
private static $table = array(); // Array of tables for subclasses
public static function init($classname, $table, $db = false) {
if (!(
$db === false)) self::$db = $db;
self::$table[$classname] = $table;
}
public static function
getDB() { return self::$db; }
public static function
getTable($classname) { return self::$table[$classname]; }
}
class
UserDataRecord extends DataRecord {
public static function
fetchFromDB() {
$result = parent::getDB()->query('select * from '.parent::getTable('UserDataRecord').';');
// and so on ...
return $result; // An array of UserDataRecord objects
}
}
$db = new MySQLi(...);
UserDataRecord::init('UserDataRecord', 'users', $db);
$users = UserDataRecord::fetchFromDB();
?>
I hope this helps some people who need to operate on PHP 5.2.x servers for some reason. Late static binding, of course, makes this workaround obsolete.
up
5
davidn at xnet dot co dot nz
6 years ago
Static variables are shared between sub classes
<?php
class MyParent {
protected static
$variable;
}
class
Child1 extends MyParent {
function
set() {
self::$variable = 2;
}
}
class
Child2 extends MyParent {
function
show() {
echo(
self::$variable);
}
}
$c1 = new Child1();
$c1->set();
$c2 = new Child2();
$c2->show(); // prints 2
?>
up
6
gratcypalma at gmail dot om
3 years ago
<?php
class foo {
private static
$getInitial;
public static function
getInitial() {
if (
self::$getInitial == null)
self::$getInitial = new foo();
return
self::$getInitial;
}
}
foo::getInitial();
/*
this is the example to use new class with static method..
i hope it help
*/
?>
up
2
Mirco
4 years ago
The simplest static constructor.
Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.
for example.
<?php
function Demonstration()
{
return
'This is the result of demonstration()';
}
class
MyStaticClass
{
//public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
public static $MyStaticVar = null;
public static function
MyStaticInit()
{
//this is the static constructor
//because in a function, everything is allowed, including initializing using other functions
self::$MyStaticVar = Demonstration();
}
}
MyStaticClass::MyStaticInit(); //Call the static constructor
echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
up
1
tolean_dj at yahoo dot com
4 years ago
Starting with php 5.3 you can get use of new features of static keyword. Here's an example of abstract singleton class:
<?php
abstract class Singleton {
protected static
$_instance = NULL;
/**
* Prevent direct object creation
*/
final private function __construct() { }
/**
* Prevent object cloning
*/
final private function __clone() { }
/**
* Returns new or existing Singleton instance
* @return Singleton
*/
final public static function getInstance(){
if(
null !== static::$_instance){
return static::
$_instance;
}
static::
$_instance = new static();
return static::
$_instance;
}
}
?>
up
0
Ano
1 month ago
The doc above says:
"A property declared as static cannot be accessed with an instantiated class object"
But it can, with a double-colon, as shown in the first example (unless I got something wrong).
up
0
Anonymous
1 year ago
It should be noted that in 'Example #2', you can also call a variably defined static method as follows:
<?php
class Foo {
public static function
aStaticMethod() {
// ...
}
}
$classname = 'Foo';
$methodname = 'aStaticMethod';
$classname::{$methodname}(); // As of PHP 5.3.0 I believe
?>
up
-1
vvikramraj at yahoo dot com
6 years ago
when attempting to implement a singleton class, one might also want to either
a) disable __clone by making it private
b) bash the user who attempts to clone by defining __clone to throw an exception
up
-2
valentin at balt dot name
5 years ago
How to implement a one storage place based on static properties.
<?php
class a {
public function
get () {
echo
$this->connect();
}
}
class
b extends a {
private static
$a;
public function
connect() {
return
self::$a = 'b';
}
}
class
c extends a {
private static
$a;
public function
connect() {
return
self::$a = 'c';
}
}
$b = new b ();
$c = new c ();
$b->get();
$c->get();
?>
up
-2
Clment Genzmer
7 years ago
The best solution I found for the non-inherited static problem : pass the name of the class.
<?php
class A {
public static
$my_vars = "I'm in A";
static function
find($class) {
$vars = get_class_vars($class) ;
echo
$vars['my_vars'] ;
}
}
class
B extends A {
public static
$my_vars = "I'm in B";
}
B::find("B");
// Result : "I'm in B"
?>
up
-1
c_daught_d at earthlink dot net
10 years ago
A twist on christian at koch dot net's Singleton example is setting/getting non-static member variables using self::$instance->varname within static method calls.
Within the modified Singleton class below, the member variable $value is set within the getInstance static method instead of the constructor.
Whether this is "pure" OPP, I don't know. But it does work, is worth mentioning, and could be usefull.
class Singleton
{
private static $instance=null;
private $value=null;
private function __construct() {
}
public static function getInstance() {
if ( self::$instance == null ) {
echo "<br>new<br>";
self::$instance = new Singleton("values");
self::$instance->value = "values";
}
else {
echo "<br>old<br>";
}
return self::$instance;
}
}
up
-1
ference at super_delete_brose dot co dot uk
10 years ago
Both static and const fields can be accessed with the :: operator. However, while a constant can't be changed, this is not true for static variables.
If you want to access an array using the :: operator you have to declare the array static, since you can't have a constant array. Beware:
<?php
class foo
{
static
$stuff = array('key1' => 1, 'key2' => 2);
}
class
bar
{
public function
__construct()
{
var_dump(foo::$stuff);
}
}
class
bad
{
public function
__construct()
{
foo::$stuff = FALSE;
}
}
new
bar(); // prints array(2) { ["key1"]=> int(1) ["key2"]=> int(2) }
new bad();
new
bar(); // prints bool(false)
?>
A safe implementation requires a little more effort:
<?php
class foo
{
private static
$stuff = array('key1' => 1, 'key2' => 2);
public final static function
getstuff()
{
return
self::$stuff;
}
}
class
bar
{
public function
__construct()
{
var_dump(foo::getstuff());
}
}
class
bad
{
public function
__construct()
{
foo::$stuff = FALSE;
}
}
new
bar(); // prints array(2) { ["key1"]=> int(1) ["key2"]=> int(2) }
new bad(); // results in a fatal error
?>
up
-1
dmintz at davidmintz dot org
10 years ago
[Editor's Note: This is done for back compatability. Depending on your error level, An E_STRICT error will be thrown.]
PHP 5.0.1 doesn't seem to mind if you call a static method in a non-static context, though it might not be the best of style to do so.
On the other hand, PHP complains if you try to try to call a non-static method in a static context (if your error reporting is cranked up to E_STRICT).
class Test {
static function static_method() {
echo "Here's your static method: Foo!<br />\n";
}
function static_method_caller() {
echo "static_method_caller says: ";$this->static_method();
}
function non_static() {
echo "I am not a static method<br />\n";
}
}
$t = new Test();
$t->static_method();
$t->static_method_caller();
Test::non_static();
up
-2
jan(dot)-re-mov.ethis-mazanek/AT-abeo.cz
8 years ago
This reacts to comment from
michael at digitalgnosis dot removethis dot com from 16-Dec-2004 08:09
> Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.)
In my test on Windows PHP Version 5.1.4 it seems that it *is possible* to override static method.
This code works at my machine without producing E_STRICT error:
<?php
class Base
{
static function
Foo ( $class = __CLASS__ )
{
call_user_func(array($class,'Bar'));
}
}
class
Derived extends Base
{
static function
Foo ( $class = __CLASS__ )
{
parent::Foo($class);
}
static function
Bar ()
{
echo
"Derived::Bar()";
}
}
Derived::Foo(); // This time it works.
?>
up
-2
Jakob Schwendner
9 years ago
Here is my solution to the static search method problem for data objects. I found the debug_trace version posted earlier quite clever, but a little too risky.
<?php
class Foo {
static function
find($class) {
$obj = new $class();
return
$obj;
}
}
class
Bar extends Foo {
static function
find() {
return
parent::find(__CLASS__);
}
function
print_hello() {
echo(
"hello");
}
}
Bar::find()->print_hello();
?>
up
-2
michael at digitalgnosis dot removethis dot com
10 years ago
Here's another way to do the same thing (see my post below) without having to muck up your Foo() function's parameters in the Base and all Derived classes.
However, you cannot use static, and still must define Foo() in derived classes. This way also performs slower and may not always work--but it DOES make for prettier code.
<?php
class Base
{
function
Foo ()
{
$call = debug_backtrace();
call_user_func(array($call[1]['class'],'Bar'));
}
}
class
Derived extends Base
{
function
Foo () { parent::Foo(); }
function
Bar ()
{
echo
"Derived::Bar()";
}
}
Derived::Foo();
?>
up
-1
zerocool at gameinsde dot ru
6 years ago
Hi, here's my simple Singleton example, i think it can be useful for someone. You can use this pattern to connect to the database for example.
<?php
class MySingleton
{
private static
$instance = null;
private function
__construct()
{
$this-> name = 'Freddy';
}
public static function
getInstance()
{
if(
self::$instance == null)
{
print
"Object created!<br>";
self::$instance = new self;
}
return
self::$instance;
}
public function
sayHello()
{
print
"Hello my name is {$this-> name}!<br>";
}
public function
setName($name)
{
$this-> name = $name;
}
}
//
$objA = MySingleton::getInstance(); // Object created!
$objA-> sayHello(); // Hello my name is Freddy!
$objA-> setName("Alex");
$objA-> sayHello(); // Hello my name is Alex!
$objB = MySingleton::getInstance();
$objB-> sayHello(); // Hello my name is Alex!
$objB-> setName("Bob");
$objA-> sayHello(); // Hello my name is Bob!
?>
up
-1
erikzoltan NOSPAM at msn NOSPAM dot com
9 years ago
I had trouble getting a static member to be an instance of a class. Here's a code example that DOESN'T work.
<?php
// This doesn't work.
class XYZ
{
// The following line will throw a syntax error.
public static $ABC = new ABC();
}
class
ABC
{
}
$myXyz = new XYZ();
var_dump($myXyz);
var_dump(XYZ::$ABC);
?>
I get the following entry in my error log.
[05-Apr-2005 18:27:41] PHP Parse error: syntax error, unexpected T_NEW in staticTest.php on line 7
Since PHP doesn't appear to allow static constructor methods, I was only able to resolve this problem by moving the initialization outside of the class. To make my code more self-documenting I put it above the class. The revised example below appears to work.
<?php
// This will work.
// Moved the static variable's initialization logic outside the class.
XYZ::$ABC = new ABC();
class
XYZ
{
// I'm just declaring the static variable here, but I'm not initializing it.
public static $ABC;
}
class
ABC
{
}
$myXyz = new XYZ();
var_dump($myXyz);
var_dump(XYZ::$ABC);
?>
up
-1
Mathijs Vos
6 years ago
<?php
class foo
{
public static
$myStaticClass;
public function
__construct()
{
self::myStaticClass = new bar();
}
}
class
bar
{
public function
__construct(){}
}
?>
Please note, this won't work.
Use self::$myStaticClass = new bar(); instead of self::myStaticClass = new bar(); (note the $ sign).
Took me an hour to figure this out.
up
-1
jkenigso at utk dot edu
1 year ago
It bears mention that static variables (in the following sense) persist:
<?php
class StaticVars
{
public static
$a=1;
}
$b=new StaticVars;
$c=new StaticVars;
echo
$b::$a; //outputs 1
$c::$a=2;
echo
$b::$a; //outputs 2!
?>
Note that $c::$a=2 changed the value of $b::$a even though $b and $c are totally different objects.
up
-1
michaelnospamdotnospamdaly at kayakwiki
6 years ago
Further to the comment by "erikzoltan NOSPAM at msn NOSPAM dot com" on 05-Apr-2005 03:40,
It isn't just constructors that can't be used for static variable initialization, it's functions in general:
class XYZ
{
static $foo = chr(1); // will fail
}
You have to do external initialization:
XYZ::$foo = chr(1);
class XYZ
{
static $foo;
}
up
-1
erikzoltan NOSPAM at msn NOSPAM dot com
9 years ago
I was doing this in a more complex example (than previous note) and found that I had to place the initialization statement AFTER the class in a file where I was using the __autoload function.
up
-1
michael at digitalgnosis dot removethis dot com
10 years ago
If you are trying to write classes that do this:
<?php
class Base
{
static function
Foo ()
{
self::Bar();
}
}
class
Derived extends Base
{
function
Bar ()
{
echo
"Derived::Bar()";
}
}
Derived::Foo(); // we want this to print "Derived::Bar()"
?>
Then you'll find that PHP can't (unless somebody knows the Right Way?) since 'self::' refers to the class which owns the /code/, not the actual class which is called at runtime. (__CLASS__ doesn't work either, because: A. it cannot appear before ::, and B. it behaves like 'self')
But if you must, then here's a (only slightly nasty) workaround:
<?php
class Base
{
function
Foo ( $class = __CLASS__ )
{
call_user_func(array($class,'Bar'));
}
}
class
Derived extends Base
{
function
Foo ( $class = __CLASS__ )
{
parent::Foo($class);
}
function
Bar ()
{
echo
"Derived::Bar()";
}
}
Derived::Foo(); // This time it works.
?>
Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.)
If Foo() takes parameters then list them before $class=__CLASS__ and in most cases, you can just forget about that parameter throughout your code.
The major caveat is, of course, that you must override Foo() in every subclass and must always include the $class parameter when calling parent::Foo().
up
-1
wbcarts at juno dot com
6 years ago
A CLASS WITH MEAT ON IT'S BONES...
I have yet to see an example that I can really get my chops into. So I am offering an example that I hope will satisfy most of us.
class RubberBall
{
/*
* ALLOW these properties to be inherited TO extending classes - that's
* why they're not private.
*
* DO NOT ALLOW outside code to access with 'RubberBall::$property_name' -
* that's why they're not public.
*
* Outside code should use:
* - RubberBall::getCount()
* - RubberBall::setStart()
* These are the only routines outside code can use - very limited indeed.
*
* Inside code has unlimited access by using self::$property_name.
*
* All RubberBall instances will share a "single copy" of these properties - that's
* why they're static.
*/
protected static $count = 0;
protected static $start = 1;
protected static $colors = array('red','yellow','blue','orange', 'green', 'white');
protected static $sizes = array(4, 6, 8, 10, 12, 16);
public $name;
public $color;
public $size;
public function __construct(){
$this->name = 'RB_' . self::$start++;
$this->color = (int) rand(0, 5);
$this->size = self::$sizes[(int) rand(0, 5)];
self::$count++;
}
public static function getCount(){
return self::$count;
}
public static function setStart($val){
self::$start = $val;
}
/*
* Define the sorting rules for RubberBalls - which is to sort by self::$colors.
* PHP's usort() method will call this function many many times.
*/
public static function compare($a, $b){
if($a->color < $b->color) return -1;
else if($a->color == $b->color) return 0;
else return 1;
}
public function __toString(){
return "RubberBall[
name=$this->name,
color=" . self::$colors[$this->color] . ",
size=" . $this->size . "\"]";
}
}
# RubberBall counts the number of objects created, but allows us to
# set the starting count like so:
RubberBall::setStart(100);
# create a PHP Array and initialize it with (12) RubberBall objects
$balls = array();
for($i = 0; $i < 12; $i++) $balls[] = new RubberBall();
# sort the RubberBall objects. PHP's usort() calls RubberBall::compare() to do this.
usort($balls, array("RubberBall", "compare"));
# print the sorted results - uses the static RubberBall::getCount().
echo 'RubberBall count: ' . RubberBall::getCount() . '<br><br>';
foreach($balls as $ball) echo $ball . '<br>';
I'm running out of room so I have not displayed the output, but it is tested and it works great.
up
-2
Jay Cain
5 years ago
Regarding the initialization of complex static variables in a class, you can emulate a static constructor by creating a static function named something like init() and calling it immediately after the class definition.
<?php
class Example {
private static
$a = "Hello";
private static
$b;
public static function
init() {
self::$b = self::$a . " World!";
}
}
Example::init();
?>
up
-1
Anonymous
9 years ago
You misunderstand the meaning of inheritance : there is no duplication of members when you inherit from a base class. Members are shared through inheritance, and can be accessed by derived classes according to visibility (public, protected, private).
The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance.
That is, a static member is shared by all instances of a class although a non static member exists for each instance of class.
Thus, in your example, the static property has the correct value, according to principles of object oriented conception.
class Base
{
public $a;
public static $b;
}
class Derived extends Base
{
public function __construct()
{
$this->a = 0;
parent::$b = 0;
}
public function f()
{
$this->a++;
parent::$b++;
}
}
$i1 = new Derived;
$i2 = new Derived;
$i1->f();
echo $i1->a, ' ', Derived::$b, "\n";
$i2->f();
echo $i2->a, ' ', Derived::$b, "\n";
outputs
1 1
1 2
up
-2
michalf at ncac dot torun dot pl
10 years ago
Inheritance with the static elements is a nightmare in php. Consider the following code:
<?php
class BaseClass{
public static
$property;
}
class
DerivedClassOne extends BaseClass{
}
class
DerivedClassTwo extends BaseClass{
}
DerivedClassOne::$property = "foo";
DerivedClassTwo::$property = "bar";
echo
DerivedClassOne::$property; //one would naively expect "foo"...
?>
What would you expect as an output? "foo"? wrong. It is "bar"!!! Static variables are not inherited, they point to the BaseClass::$property.
At this point I think it is a big pity inheritance does not work in case of static variables/methods. Keep this in mind and save your time when debugging.
best regards - michal
up
-6
myselfasunder at gmail dot com
4 years ago
If you inadvertently call a non-static method in one class from another class, using $this in the former will actually refer to the wrong class.
<?php
class CalledClass
{
function
go()
{
print(
get_class($this) . "\n");
return
true;
}
}
class
CallerClass
{
function
go()
{
CalledClass::Go();
return
true;
}
}
$obj = new CallerClass();
$obj->go();
// Output is "CallerClass" instead of "CalledClass" like it should be.
?>
Dustin Oprea
up
-3
Siarhei
7 years ago
There is a problem to make static property shared only for objects of self class not defining it in every child class.
Example:
class a
{
public static $s;
public function get()
{
return self::$s;
}
}
class b extends a { }
class c extends b { }
a::$s = 'a';
$c = new c();
echo $c->get(); // a
There is solution i found:
class a
{
public final function v($vs = null)
{
static $s = null;
if(!is_null($vs))
$s = $vs;
return $s;
}
}
class b extends a { }
class c extends b { }
$a = new a();
$a->v('a');
$aa = new a();
$aa->v('last a');
$c = new c();
$c->v('c');
echo $a->v().' - '.$c->v(); // last a - c
up
-5
desmatic
1 year ago
Don't use GLOBALS in classes (or anywhere really), use static variables instead. They're better. They can do everything a GLOBAL can and they can be protected by accessor functions so they'll never get clobbered.
class foo {
private static $_private = null;
public function get() {
if (self::$_private === null) {
self::$_private = new stdClass();
}
return self::$_private;
}
}
class bar extends foo {
}
function scope_foo() {
$f = new foo();
$f->get()->name = "superdude";
}
function scope_bar() {
$b = new bar();
$b->get()->description = "an object reference test";
}
scope_foo();
scope_bar();
$my = new bar();
foreach ($my->get() as $key => $value) {
echo "{$key} => {$value}\n";
}
outputs:
name => superdude
description => an object reference test
up
-5
Anonymous
4 years ago
I can't find anything in the PHP manual about this, but the new-ish E_STRICT error reporting will complain if an inherited class overrides a static method with a different call signature (usually a parameter list). Ironically, it seems to only be a problem of 'coding style' because the code works correctly and has done for quite a few versions.
The exact error is "Strict Standards: Declaration of [child-class]::[method]() should be compatible with that of [parent-class]::[method]()".
So if you must code with E_STRICT enabled, you need to rename the method name.
Google shows that this is biting *a lot* of people. (Bugs have been filed, but there has been no response yet.)
up
-3
ianromie at gmail dot com
8 months ago
class A {
public static function getName(){
echo "My Name";
}
public static function getAge(){
return "22";
}
}
A::getName();
echo A::getAge();
up
-3
Denis Ribeiro - dpr001 at gmail dot com
1 year ago
Other point is that static methods just can access static properties, because the pseudo variable $this not exists in this scope like example below:
<?php
//is wrong, because the static methods can only access static properties
class Foo {
public
$property;
public static function
aStaticMethod() {
echo
"Accessing the property: {$this->property}"; //Fatal error:Using $this
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
//Note that property $property is static and then can be using the word self instead of pseudo variable $this
class Foo2 {
static
$property = 'test';
public static function
aStaticMethod() {
echo
"Accessing the property: ". self::$property; //Accessing the property: test
}
}
Foo2::aStaticMethod();
up
-3
manishpatel2280 at gmail dot com
1 year ago
In real world, we can say will use static method when we dont want to create object instance.
e.g ...
validateEmail($email) {
if(T) return true;
return false;
}
//This makes not much sense
$obj = new Validate();
$result = $obj->validateEmail($email);
//This makes more sense
$result = Validate::validateEmail($email);
up
-3
programmer-comfreek at hotmail dot com
3 years ago
If you haven't an instance for your class (e.g. all functions are static), but you also want a __destruct() functionality, consider the following example:
We have a class which loads and saves data so we also want to have an autosave mechanism which is called at the end of the PHP script.
So usually you declare a __destruct function but our class is designed to provide static functions / variables instead:
<?php
class A
{
static private
$autoSave;
static public function
init($autoSave)
{
/* emulating __construct() */
self::$autoSave = $autoSave;
}
static public function
save() { /*...*/ } /* load(), get(), etc. */
}
?>
In order to define a __destruct function (which is definitely called) we create a new instance in the init() function and define a destruct() function (which is called from the 'real' one):
<?php
class B
{
static private
$autoSave;
static public function
init($autoSave)
{
/* emulating __construct() */
self::$autoSave = $autoSave;
new
B();
}
static public function
destruct()
{
if (
self::$autoSave)
self::save();
}
public function
__destruct()
{
B::destruct();
}
}
?>
up
-3
sep16 at psu dot edu
5 years ago
I find having class variables useful for inherited classes, especially when inheriting abstract classes, yet self:: doesn't refer to the class calling the method, rather the actual class in which it was defined. Although it is less memory efficient, this can be circumvented with instance properties, but sometimes even this won't work, i.e., when using resources like class-wide database or prepared statement handles.
The pre-5.3.0 way that I used to get around this limitation was to write a class that stores a central value and sets instance properties as references to this value. In this way objects can have access to the same value while still being able to use inherited methods that reference this property.
Usage example:
<?php // (SharedPropertyClass is defined below)
class Foo extends SharedPropertyClass {
public
$foo = "bar";
public function
showFoo() {
echo
$this->foo, "\n";
}
}
class
FooToo extends Foo {
public function
__construct() {
$this->makeShared('foo');
}
}
$ojjo = new FooToo;
$ojjo->showFoo(); // "bar"
$xjjx = new FooToo;
$xjjx->showFoo(); // "bar"
$ojjo->foo = "new";
$ojjo->showFoo(); // "new"
$xjjx->showFoo(); // "new"
?>
Notice how the showFoo() method, while defined in the parent class, correctly uses the child class's "foo" property (unlike self:: would), and how the "foo" property is shared by all instances of FooToo objects (like a static property). This is essentially how the new static:: keyword will work, and how most people probably expected the self:: keyword to work.
<?php
// ---------------------------------------------------------------
abstract class SharedPropertyClass {
// ---------------------------------------------------------------
/*
Shared properties should be declared as such in the
constructor function of the inheriting class.
The first instance will have the shared property set to
the value in the class definition, if any, otherwise null.
All subsequent instances will also have their shared
property set as a reference to that variable.
*/
private static $shared = array();
public function
makeShared($property) {
$class = get_class($this);
if (!
property_exists($this,$property))
trigger_error("Access to undeclared property "
. "'$property' in class $class.",E_USER_ERROR);
if (!
array_key_exists($class,self::$shared))
self::$shared[$class] = array();
if (!
array_key_exists($property,self::$shared[$class]))
self::$shared[$class][$property]
= isset(
$this->$property)
?
$this->$property
: null;
$this->$property =& self::$shared[$class][$property];
}
public function
isShared($property) {
$class = get_class($this);
if (!
property_exists($this,$property))
trigger_error("Access to undeclared property "
. "'$property' in class $class.",E_USER_ERROR);
return
array_key_exists($class,self::$shared)
&&
array_key_exists($property, self::$shared[$class]);
}
}
?>
up
-3
yesmarklapointe at hotmail dot com
6 years ago
<?php
// experiments with static
// tested on PHP 5.2.6 on 1-21-09
class User{
const
GIVEN = 1// class constants can't be labeled static nor assigned visibility
public $a=2;
public static
$b=3;
public function
me(){
echo
"print me";
}
public static function
you() {
echo
"print you";
}
}
class
myUser extends User {
}
// Are properties and methods instantiated to an object of a class, & are they accessible?
//$object1= new User(); // uncomment this line with each of the following lines individually
//echo $object1->GIVEN . "</br>"; // yields nothing
//echo $object1->GIVE . "</br>"; // deliberately misnamed, still yields nothing
//echo $object1->User::GIVEN . "</br>"; // yields nothing
//echo $object1->a . "</br>"; // yields 2
//echo $object1->b . "</br>"; // yields nothing
//echo $object1->me() . "</br>"; // yields print me
//echo $object1->you() . "</br>"; // yields print you
// Are properties and methods instantiated to an object of a child class, & are accessible?
//$object2= new myUser(); // uncomment this line with each of the following lines individually
//echo $object2->GIVEN . "</br>"; // yields nothing
//echo $object2->a . "</br>"; // yields 2
//echo $object2->b . "</br>"; // yields nothing
//echo $object2->me() . "</br>"; // yields print me
//echo $object2->you() . "</br>"; // yields print you
// Are the properties and methods accessible directly in the class?
//echo User::GIVEN . "</br>"; // yields 1
//echo User::$a . "</br>"; // yields fatal error since it is not static
//echo User::$b . "</br>"; // yields 3
//echo User::me() . "</br>"; // yields print me
//echo User::you() . "</br>"; // yields print you
// Are the properties and methods copied to the child class and are they accessible?
//echo myUser::GIVEN . "</br>"; // yields 1
//echo myUser::$a . "</br>"; // yields fatal error since it is not static
//echo myUser::$b . "</br>"; // yields 3
//echo myUser::me() . "</br>"; // yields print me
//echo myUser::you() . "</br>"; // yields print you
?>
up
-3
wbcarts at juno dot com
6 years ago
[NB: This is a copy of the note by juno dot com on 11-Sep-2008 04:53, but with syntax highlighting.]
A CLASS WITH MEAT ON IT'S BONES...
I have yet to see an example that I can really get my chops into. So I am offering an example that I hope will satisfy most of us.
<?php
class RubberBall
{
/*
* ALLOW these properties to be inherited TO extending classes - that's
* why they're not private.
*
* DO NOT ALLOW outside code to access with 'RubberBall::$property_name' -
* that's why they're not public.
*
* Outside code should use:
* - RubberBall::getCount()
* - RubberBall::setStart()
* These are the only routines outside code can use - very limited indeed.
*
* Inside code has unlimited access by using self::$property_name.
*
* All RubberBall instances will share a "single copy" of these properties - that's
* why they're static.
*/
protected static $count = 0;
protected static
$start = 1;
protected static
$colors = array('red','yellow','blue','orange', 'green', 'white');
protected static
$sizes = array(4, 6, 8, 10, 12, 16);
public
$name;
public
$color;
public
$size;
public function
__construct(){
$this->name = 'RB_' . self::$start++;
$this->color = (int) rand(0, 5);
$this->size = self::$sizes[(int) rand(0, 5)];
self::$count++;
}
public static function
getCount(){
return
self::$count;
}
public static function
setStart($val){
self::$start = $val;
}
/*
* Define the sorting rules for RubberBalls - which is to sort by self::$colors.
* PHP's usort() method will call this function many many times.
*/
public static function compare($a, $b){
if(
$a->color < $b->color) return -1;
else if(
$a->color == $b->color) return 0;
else return
1;
}
public function
__toString(){
return
"RubberBall[
name=
$this->name,
color="
. self::$colors[$this->color] . ",
size="
. $this->size . "\"]";
}
}
# RubberBall counts the number of objects created, but allows us to
# set the starting count like so:
RubberBall::setStart(100);
# create a PHP Array and initialize it with (12) RubberBall objects
$balls = array();
for(
$i = 0; $i < 12; $i++) $balls[] = new RubberBall();
# sort the RubberBall objects. PHP's usort() calls RubberBall::compare() to do this.
usort($balls, array("RubberBall", "compare"));
# print the sorted results - uses the static RubberBall::getCount().
echo 'RubberBall count: ' . RubberBall::getCount() . '<br><br>';
foreach(
$balls as $ball) echo $ball . '<br>';
?>
I'm running out of room so I have not displayed the output, but it is tested and it works great.
To Top
|
__label__pos
| 0.973186 |
B-Tech in Computer Science: Curriculum, Career Prospects, and College
BTech in Computer Science: Curriculum, Career Prospects, and College
Wondering what to do after finishing your 12th-grade education? A BTech in Computer Science degree is an excellent option for you if you enjoy technology and are eager to create new software. We will learn about the Btech in Computing, its curriculum, and its eligibility requirements in this blog. We will also talk about the finest college for this subject and the employment prospects after completing it.
What is BTech in Computer Science
A four-year undergraduate curriculum in computer science called the B Tech focuses on the study of computers, programming, and software development. The course is excellent because it helps students get highly valued abilities in data structures, computer programming, computer applications, research and development, etc.
Eligibility Criteria
To pursue a Btech in Computer science, students have to fulfill these criteria:
• Education Qualification: Students must have finished PCM (physics, chemistry, and math) in their 10+2 education.
• Minimum Marks: Grades at different colleges and institutions often range from 50% to 60%.
• Age Limit: The course is open to students of any age.
Entrance Exam:
• JEE Main: A nationwide exam, the Joint Entrance Examination (JEE) is required for admission to several engineering institutes in India.
• State-Level Entrance Exams: The states may also hold entrance examinations of their own, such as UPSEE (Uttar Pradesh), KCET (Karnataka), and WBJEE (West Bengal).
• Private University Exam: A few universities, such as VITEEE (VIT University) and SRMJEEE (SRM University), offer their entrance tests.
Curriculum Overview:
The Btech program in computer science combines academic understanding with real-world applications in its curriculum. Typically, the four-year B Tech program in computer engineering is broken up into eight semesters. It consists of a well-balanced combination of electives, practical projects, and core studies.
1. Core Subjects
• Programming Language: Python, Java, and C++ are the available languages.
• Data Structure and Algorithms: Essential for efficient problem-solving
• Computer Networks: We can comprehend the communication systems’ infrastructure from this.
• Software Engineering: Study the fundamentals of project management and software development with a focus on software engineering.
• Discrete Mathematics: Discrete mathematics is fundamental to the theory of computer science.
2. Laboratories: There are projects and labs where you may put what you’ve learned to use and work on actual issues.
3. Internships and Projects: Students enrolled in this course can choose between industry projects or internships.
Career Prospects
There are a plethora of employment options in many industries for those who complete their Btech in computer science. Let’s talk about a couple of them:
1. Software Developer: The work of software developers is to design and develop software and its applications.
2. Data Scientists: The Data Scientist role is important because it combines tools, methods, and technology to generate meaning from data
3. Cyber security analysts: They can protect the company systems and data from cyber threats. Its average salary for freshers is ₹3,00,000 to ₹6,00,000 per year.
4. Systems Analyst: A systems analyst is a person who analyzes and designs techniques to solve problems using information technology. Its average salary is ₹4,00,000 to ₹8,00,000 per year for freshers.
5. Web Developer: Web developers design and develop websites and web applications. They work with technologies such as HTML, CSS, and various web development frameworks.
6. Database Administrator: There are many career options for BTech Computer Science graduates as database administrators. Some of the most popular ones include working in IT companies, banks, other financial institutions, government organizations, and even in the healthcare sector.
NIET best computer science engineering college
The Btech program in computer science is offered by numerous schools. One of the top universities in Greater Noida offering a BTech in computer science is NIET. One of the institutions that fulfills all prerequisites for a BTech in computer science is this one. It provides state-of-the-art labs, knowledgeable instructors, and opportunities to create new software and technologies that will support students’ professional development even further. Because of its reasonable pricing structure, the BTech in Computer Science at NIET is an excellent option for those studying computers and science.
Conclusion
If you want to work in technology, the finest course to take is a BTech in Computer Science. It provides a good wage package, a wide range of professional opportunities, and a sound education. For this course, NIET is the greatest option because of its cutting-edge curriculum, knowledgeable faculty, and solid industry ties with tech firms. Selecting NIET, the best computer science engineering college will set you up for success in the sector going forward.
|
__label__pos
| 0.879033 |
6
For a project of mine, I'm trying to implement a small part of the BitTorrent protocol, which can be found here. Specifically, I want to use the "Bencoding" part of it, which is a way to safely encode data for transfer over a socket. The format is as follows:
8:a string => "a string"
i1234e => 1234
l1:a1:be => ['a', 'b']
d1:a1:b3:one3:twoe => {'a':'b', 'one':two}
The encoding part was easy enough, but decoding is become quite a hassle. For example, if I have a list of strings, I have no way to separate them into individual strings. I've tried several different solutions, including PyParsing and a custom token parser. I'm currently attempting to use regexes, and it seems to be going fairly well, but I'm still hung up on the string problem. My current regex is:
(?P<length>\d+):(?P<contents>.{\1})
However, i can't seem to use the first group as the length of the second group. Is there any good way to do this? Or am I approaching this all wrong, and the answer is sitting right in front of me?
• 3
Not sure of the answer, but the original Bit Torrent client is open source. And it's even in Python! So you could try poking around: bittorrent.cvs.sourceforge.net/viewvc/bittorrent/BitTorrent – MatrixFrog Jun 2 '09 at 6:20
• 18
"And now you have two problems!" ::rimshot:: – anonymous coward Jun 2 '09 at 14:23
• Thanks for the link, MatrixFrog. I think that I'm going to just import that file, and use the original implementation in my program. – Nick Meharry Jun 2 '09 at 15:00
8
Any parser you use for this is going to need to be stateful (i.e. remember stuff), and regexes are, by and large, not stateful. They're the wrong tool for this job.
If those are the only data types you have to worry about, I think I'd just write custom parsers for each data type, passing control to the appropriate parser after reading the first character.
I'd actually implement one now, but it's late.
Alright I decided to write an implementation:
from StringIO import StringIO
import string
inputs = ["10:a stringly",
"i1234e" ,
"l1:a1:be",
"d1:a1:b3:one3:twoe"]
# Constants
DICT_TYPE = 'd'
LIST_TYPE = 'l'
INT_TYPE = 'i'
TOKEN_EOF = ''
TOKEN_END = 'e'
COLON = ':'
class BadTypeIndicatorException(Exception):pass
def read_int(stream):
s = ""
while True:
ch = stream.read(1)
if ch not in [TOKEN_EOF, TOKEN_END, COLON]:
s += ch
else:
break
return s
def tokenize(stream):
s = ""
while True:
ch = stream.read(1)
if ch == TOKEN_END or ch == TOKEN_EOF:
return
if ch == COLON:
length = int(s)
yield stream.read(length)
s = ""
else:
s += ch
def parse(stream):
TYPE = stream.read(1)
if TYPE in string.digits:
length = int( TYPE + read_int(stream) )
return stream.read(length)
elif TYPE is INT_TYPE:
return int( read_int(stream) )
elif TYPE is LIST_TYPE:
return list(tokenize(stream))
elif TYPE is DICT_TYPE:
tokens = list(tokenize(stream))
return dict(zip(tokens[0::2], tokens[1::2]))
else:
raise BadTypeIndicatorException
for input in inputs:
stream = StringIO(input)
print parse(stream)
• 1
Regexes ARE stateful. The only difference between a regex and a different parser is that regexes have only fixed, finite state. In fact, that's one common way to define a regular language: any language that can be parsed using a fixed, finite amount of state. – Dietrich Epp Jun 2 '09 at 6:59
• 1
@Dietrich - I understand what you're saying, but really we're talking about two completely different meanings of the word "state". The word in modern programming is most often used as I used it - that some process remembers things between operations. In regular expressions, we might call that context, and regular expressions are by-and-large designed to be context-free. – Triptych Jun 2 '09 at 14:16
• I would choose this as the answer, but I decided to not reinvent the wheel, so I used the BitTorrent implementation that MatrixFrog linked to above. Otherwise, I probably would've used your implementation, or something based off of it. – Nick Meharry Jun 2 '09 at 22:59
• 1
@bluejeansummer - you're allowed to accept it anyway! – Triptych Jun 2 '09 at 23:19
2
You can do it if you parse the string twice. Apply the first regex to get the length. Concatenate the length in your second regex to form a valid expression.
Not sure how that can be done in python, but a sample in C# would be:
string regex = "^[A-Za-z0-9_]{1," + length + "}$"
To match 1 to length no of chars which can be alpanumeric or _ where length is determined from a previous regex that retrieves only the length.
Hope this helps :)
2
You'll want to do this in two steps. Regular expressions are actually a little overkill for such simple parsing problems as this. Here's how I'd do it:
def read_string(stream):
pos = stream.index(':')
length = int(stream[0:pos])
string = stream[pos+1:pos+1+length]
return string, stream[pos+1+length:]
It's a functional-style way of parsing, it returns the value parsed and the rest of the stream.
For lists, maybe:
def read_list(stream):
stream = stream[1:]
result = []
while stream[0] != 'e':
obj, stream = read_object(stream)
result.append(obj)
stream = stream[1:]
return result
And then you'd define a read_object that checks the first character of the stream and dispatches appropriately.
• Sslice syntax on a stream of arbitrary length is probably not a great idea. – Triptych Jun 2 '09 at 14:33
1
You are using the wrong tool for the job... This requires some sort of state keeping, and generally speaking, regular expressions are stateless.
An example implementation of bdecoding (and bencoding) in PERL that I did can be found here.
An explanation of how that function works (since I never did get to comment it [oops]):
Basically what you need to do is setup a recursive function. This function takes a string reference (so it can be modified) and returns "something" (the nature of this means it could be an array, a hashtable, an int, or a string).
The function itself just checks the first character in the string and decides what to do based of that:
• If it is an i, then parse out all the text between the i and the first e, and try to parse it as an int according to the rules of what is allowed.
• If it is a digit, then read all the digits up to :, then read that many characters off the string.
Lists and dictionaries are where things start to get interesting... if there is an l or d as the first character, then you need to strip off the l/d, then pass the current string back into the function, so that it can start parsing elements in the list or dictionary. Then just store the returned values in the appropriate places in an appropriate structure till you hit an e, and return the structure you're left with.
Remember, the function as I implemented it was DESTRUCTIVE. The string passed in is empty when the function returns due to it being passed by reference, or more accurately, it will be devoid of anything it parsed and returned (which is why it can be used recursively: anything it doesn't process is left untouched). In most cases of the initial call though, this should process everything unless you've been doing something odd, so the above holds.
• Python strings are immutable, so you'll have to do it a little differently. – Dietrich Epp Jun 2 '09 at 6:57
• Perhaps pass around an offset variable or something then? Or do it in a loop. My mind works recursively most of the time though. – Matthew Scharley Jun 2 '09 at 7:04
1
Pseudo-code, without syntax checks:
define read-integer (stream):
let number 0, sign 1:
if string-equal ('-', (c <- read-char (stream))):
sign <- -1
else:
number <- parse-integer (c)
while number? (c <- read-char (stream)):
number <- (number * 10) + parse-integer (c)
return sign * number
define bdecode-string (stream):
let count read-integer (stream):
return read-n-chars (stream, count)
define bdecode-integer (stream):
ignore read-char (stream)
return read-integer (stream)
define bdecode-list (stream):
ignore read-char (stream)
let list []:
while not string-equal ('e', peek-char (stream)):
append (list, bdecode (stream))
return list
define bdecode-dictionary (stream):
let list bdecode-list stream:
return dictionarify (list)
define bdecode (stream):
case peek-char (stream):
number? => bdecode-string (stream)
'i' => bdecode-integer (stream)
'l' => bdecode-list (stream)
'd' => bdecode-dictionary (stream)
• I don't know why someone downvoted this, but I just checked how the original bittorrent does it (thanks to MatrixFrog for the link), and it is almost exactly this, plus error checks, and it handles the stream differently. – Svante Jun 2 '09 at 13:11
Your Answer
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.7627 |
source: rtems/cpukit/score/cpu/m32c/rtems/score/cpu.h @ f82752a4
4.115
Last change on this file since f82752a4 was f82752a4, checked in by Daniel Hellstrom <daniel@…>, on Jun 4, 2014 at 9:23:34 AM
Let CPU/BSP Fatal handler have access to source
Without the source the error code does not say that much.
Let it be up to the CPU/BSP to determine the error code
reported on fatal shutdown.
This patch does not change the current behaviour, just
adds the option to handle the source of the fatal halt.
• Property mode set to 100644
File size: 39.0 KB
Line
1/**
2 * @file
3 *
4 * @brief M32C CPU Dependent Source
5 */
6
7/*
8 * This include file contains information pertaining to the XXX
9 * processor.
10 *
11 * @note This file is part of a porting template that is intended
12 * to be used as the starting point when porting RTEMS to a new
13 * CPU family. The following needs to be done when using this as
14 * the starting point for a new port:
15 *
16 * + Anywhere there is an XXX, it should be replaced
17 * with information about the CPU family being ported to.
18 *
19 * + At the end of each comment section, there is a heading which
20 * says "Port Specific Information:". When porting to RTEMS,
21 * add CPU family specific information in this section
22 */
23
24/*
25 * COPYRIGHT (c) 1989-2008.
26 * On-Line Applications Research Corporation (OAR).
27 *
28 * The license and distribution terms for this file may be
29 * found in the file LICENSE in this distribution or at
30 * http://www.rtems.org/license/LICENSE.
31 */
32
33#ifndef _RTEMS_SCORE_CPU_H
34#define _RTEMS_SCORE_CPU_H
35
36#ifdef __cplusplus
37extern "C" {
38#endif
39
40#include <rtems/score/types.h>
41#include <rtems/score/m32c.h>
42
43/* conditional compilation parameters */
44
45#define RTEMS_USE_16_BIT_OBJECT
46
47/**
48 * Should the calls to @ref _Thread_Enable_dispatch be inlined?
49 *
50 * If TRUE, then they are inlined.
51 * If FALSE, then a subroutine call is made.
52 *
53 * This conditional is an example of the classic trade-off of size
54 * versus speed. Inlining the call (TRUE) typically increases the
55 * size of RTEMS while speeding up the enabling of dispatching.
56 *
57 * NOTE: In general, the @ref _Thread_Dispatch_disable_level will
58 * only be 0 or 1 unless you are in an interrupt handler and that
59 * interrupt handler invokes the executive.] When not inlined
60 * something calls @ref _Thread_Enable_dispatch which in turns calls
61 * @ref _Thread_Dispatch. If the enable dispatch is inlined, then
62 * one subroutine call is avoided entirely.
63 *
64 * Port Specific Information:
65 *
66 * XXX document implementation including references if appropriate
67 */
68#define CPU_INLINE_ENABLE_DISPATCH FALSE
69
70/**
71 * Should the body of the search loops in _Thread_queue_Enqueue_priority
72 * be unrolled one time? In unrolled each iteration of the loop examines
73 * two "nodes" on the chain being searched. Otherwise, only one node
74 * is examined per iteration.
75 *
76 * If TRUE, then the loops are unrolled.
77 * If FALSE, then the loops are not unrolled.
78 *
79 * The primary factor in making this decision is the cost of disabling
80 * and enabling interrupts (_ISR_Flash) versus the cost of rest of the
81 * body of the loop. On some CPUs, the flash is more expensive than
82 * one iteration of the loop body. In this case, it might be desirable
83 * to unroll the loop. It is important to note that on some CPUs, this
84 * code is the longest interrupt disable period in RTEMS. So it is
85 * necessary to strike a balance when setting this parameter.
86 *
87 * Port Specific Information:
88 *
89 * XXX document implementation including references if appropriate
90 */
91#define CPU_UNROLL_ENQUEUE_PRIORITY TRUE
92
93/**
94 * Does RTEMS manage a dedicated interrupt stack in software?
95 *
96 * If TRUE, then a stack is allocated in @ref _ISR_Handler_initialization.
97 * If FALSE, nothing is done.
98 *
99 * If the CPU supports a dedicated interrupt stack in hardware,
100 * then it is generally the responsibility of the BSP to allocate it
101 * and set it up.
102 *
103 * If the CPU does not support a dedicated interrupt stack, then
104 * the porter has two options: (1) execute interrupts on the
105 * stack of the interrupted task, and (2) have RTEMS manage a dedicated
106 * interrupt stack.
107 *
108 * If this is TRUE, @ref CPU_ALLOCATE_INTERRUPT_STACK should also be TRUE.
109 *
110 * Only one of @ref CPU_HAS_SOFTWARE_INTERRUPT_STACK and
111 * @ref CPU_HAS_HARDWARE_INTERRUPT_STACK should be set to TRUE. It is
112 * possible that both are FALSE for a particular CPU. Although it
113 * is unclear what that would imply about the interrupt processing
114 * procedure on that CPU.
115 *
116 * Port Specific Information:
117 *
118 * XXX document implementation including references if appropriate
119 */
120#define CPU_HAS_SOFTWARE_INTERRUPT_STACK FALSE
121
122/**
123 * Does the CPU follow the simple vectored interrupt model?
124 *
125 * If TRUE, then RTEMS allocates the vector table it internally manages.
126 * If FALSE, then the BSP is assumed to allocate and manage the vector
127 * table
128 *
129 * Port Specific Information:
130 *
131 * XXX document implementation including references if appropriate
132 */
133#define CPU_SIMPLE_VECTORED_INTERRUPTS TRUE
134
135/**
136 * Does this CPU have hardware support for a dedicated interrupt stack?
137 *
138 * If TRUE, then it must be installed during initialization.
139 * If FALSE, then no installation is performed.
140 *
141 * If this is TRUE, @ref CPU_ALLOCATE_INTERRUPT_STACK should also be TRUE.
142 *
143 * Only one of @ref CPU_HAS_SOFTWARE_INTERRUPT_STACK and
144 * @ref CPU_HAS_HARDWARE_INTERRUPT_STACK should be set to TRUE. It is
145 * possible that both are FALSE for a particular CPU. Although it
146 * is unclear what that would imply about the interrupt processing
147 * procedure on that CPU.
148 *
149 * Port Specific Information:
150 *
151 * XXX document implementation including references if appropriate
152 */
153#define CPU_HAS_HARDWARE_INTERRUPT_STACK TRUE
154
155/**
156 * Does RTEMS allocate a dedicated interrupt stack in the Interrupt Manager?
157 *
158 * If TRUE, then the memory is allocated during initialization.
159 * If FALSE, then the memory is allocated during initialization.
160 *
161 * This should be TRUE is CPU_HAS_SOFTWARE_INTERRUPT_STACK is TRUE.
162 *
163 * Port Specific Information:
164 *
165 * XXX document implementation including references if appropriate
166 */
167#define CPU_ALLOCATE_INTERRUPT_STACK TRUE
168
169/**
170 * Does the RTEMS invoke the user's ISR with the vector number and
171 * a pointer to the saved interrupt frame (1) or just the vector
172 * number (0)?
173 *
174 * Port Specific Information:
175 *
176 * XXX document implementation including references if appropriate
177 */
178#define CPU_ISR_PASSES_FRAME_POINTER 0
179
180/**
181 * @def CPU_HARDWARE_FP
182 *
183 * Does the CPU have hardware floating point?
184 *
185 * If TRUE, then the RTEMS_FLOATING_POINT task attribute is supported.
186 * If FALSE, then the RTEMS_FLOATING_POINT task attribute is ignored.
187 *
188 * If there is a FP coprocessor such as the i387 or mc68881, then
189 * the answer is TRUE.
190 *
191 * The macro name "M32C_HAS_FPU" should be made CPU specific.
192 * It indicates whether or not this CPU model has FP support. For
193 * example, it would be possible to have an i386_nofp CPU model
194 * which set this to false to indicate that you have an i386 without
195 * an i387 and wish to leave floating point support out of RTEMS.
196 */
197
198/**
199 * @def CPU_SOFTWARE_FP
200 *
201 * Does the CPU have no hardware floating point and GCC provides a
202 * software floating point implementation which must be context
203 * switched?
204 *
205 * This feature conditional is used to indicate whether or not there
206 * is software implemented floating point that must be context
207 * switched. The determination of whether or not this applies
208 * is very tool specific and the state saved/restored is also
209 * compiler specific.
210 *
211 * Port Specific Information:
212 *
213 * XXX document implementation including references if appropriate
214 */
215#if ( M32C_HAS_FPU == 1 )
216#define CPU_HARDWARE_FP TRUE
217#else
218#define CPU_HARDWARE_FP FALSE
219#endif
220#define CPU_SOFTWARE_FP FALSE
221
222#define CPU_CONTEXT_FP_SIZE 0
223
224/**
225 * Are all tasks RTEMS_FLOATING_POINT tasks implicitly?
226 *
227 * If TRUE, then the RTEMS_FLOATING_POINT task attribute is assumed.
228 * If FALSE, then the RTEMS_FLOATING_POINT task attribute is followed.
229 *
230 * So far, the only CPUs in which this option has been used are the
231 * HP PA-RISC and PowerPC. On the PA-RISC, The HP C compiler and
232 * gcc both implicitly used the floating point registers to perform
233 * integer multiplies. Similarly, the PowerPC port of gcc has been
234 * seen to allocate floating point local variables and touch the FPU
235 * even when the flow through a subroutine (like vfprintf()) might
236 * not use floating point formats.
237 *
238 * If a function which you would not think utilize the FP unit DOES,
239 * then one can not easily predict which tasks will use the FP hardware.
240 * In this case, this option should be TRUE.
241 *
242 * If @ref CPU_HARDWARE_FP is FALSE, then this should be FALSE as well.
243 *
244 * Port Specific Information:
245 *
246 * XXX document implementation including references if appropriate
247 */
248#define CPU_ALL_TASKS_ARE_FP TRUE
249
250/**
251 * Should the IDLE task have a floating point context?
252 *
253 * If TRUE, then the IDLE task is created as a RTEMS_FLOATING_POINT task
254 * and it has a floating point context which is switched in and out.
255 * If FALSE, then the IDLE task does not have a floating point context.
256 *
257 * Setting this to TRUE negatively impacts the time required to preempt
258 * the IDLE task from an interrupt because the floating point context
259 * must be saved as part of the preemption.
260 *
261 * Port Specific Information:
262 *
263 * XXX document implementation including references if appropriate
264 */
265#define CPU_IDLE_TASK_IS_FP FALSE
266
267/**
268 * Should the saving of the floating point registers be deferred
269 * until a context switch is made to another different floating point
270 * task?
271 *
272 * If TRUE, then the floating point context will not be stored until
273 * necessary. It will remain in the floating point registers and not
274 * disturned until another floating point task is switched to.
275 *
276 * If FALSE, then the floating point context is saved when a floating
277 * point task is switched out and restored when the next floating point
278 * task is restored. The state of the floating point registers between
279 * those two operations is not specified.
280 *
281 * If the floating point context does NOT have to be saved as part of
282 * interrupt dispatching, then it should be safe to set this to TRUE.
283 *
284 * Setting this flag to TRUE results in using a different algorithm
285 * for deciding when to save and restore the floating point context.
286 * The deferred FP switch algorithm minimizes the number of times
287 * the FP context is saved and restored. The FP context is not saved
288 * until a context switch is made to another, different FP task.
289 * Thus in a system with only one FP task, the FP context will never
290 * be saved or restored.
291 *
292 * Port Specific Information:
293 *
294 * XXX document implementation including references if appropriate
295 */
296#define CPU_USE_DEFERRED_FP_SWITCH TRUE
297
298/**
299 * Does this port provide a CPU dependent IDLE task implementation?
300 *
301 * If TRUE, then the routine @ref _CPU_Thread_Idle_body
302 * must be provided and is the default IDLE thread body instead of
303 * @ref _CPU_Thread_Idle_body.
304 *
305 * If FALSE, then use the generic IDLE thread body if the BSP does
306 * not provide one.
307 *
308 * This is intended to allow for supporting processors which have
309 * a low power or idle mode. When the IDLE thread is executed, then
310 * the CPU can be powered down.
311 *
312 * The order of precedence for selecting the IDLE thread body is:
313 *
314 * -# BSP provided
315 * -# CPU dependent (if provided)
316 * -# generic (if no BSP and no CPU dependent)
317 *
318 * Port Specific Information:
319 *
320 * XXX document implementation including references if appropriate
321 */
322#define CPU_PROVIDES_IDLE_THREAD_BODY TRUE
323
324/**
325 * Does the stack grow up (toward higher addresses) or down
326 * (toward lower addresses)?
327 *
328 * If TRUE, then the grows upward.
329 * If FALSE, then the grows toward smaller addresses.
330 *
331 * Port Specific Information:
332 *
333 * XXX document implementation including references if appropriate
334 */
335#define CPU_STACK_GROWS_UP TRUE
336
337/**
338 * The following is the variable attribute used to force alignment
339 * of critical RTEMS structures. On some processors it may make
340 * sense to have these aligned on tighter boundaries than
341 * the minimum requirements of the compiler in order to have as
342 * much of the critical data area as possible in a cache line.
343 *
344 * The placement of this macro in the declaration of the variables
345 * is based on the syntactically requirements of the GNU C
346 * "__attribute__" extension. For example with GNU C, use
347 * the following to force a structures to a 32 byte boundary.
348 *
349 * __attribute__ ((aligned (32)))
350 *
351 * NOTE: Currently only the Priority Bit Map table uses this feature.
352 * To benefit from using this, the data must be heavily
353 * used so it will stay in the cache and used frequently enough
354 * in the executive to justify turning this on.
355 *
356 * Port Specific Information:
357 *
358 * XXX document implementation including references if appropriate
359 */
360#define CPU_STRUCTURE_ALIGNMENT __attribute__ ((aligned (2)))
361
362#define CPU_TIMESTAMP_USE_STRUCT_TIMESPEC TRUE
363
364/**
365 * @defgroup CPUEndian Processor Dependent Endianness Support
366 *
367 * This group assists in issues related to processor endianness.
368 *
369 */
370/**@{**/
371
372/**
373 * Define what is required to specify how the network to host conversion
374 * routines are handled.
375 *
376 * NOTE: @a CPU_BIG_ENDIAN and @a CPU_LITTLE_ENDIAN should NOT have the
377 * same values.
378 *
379 * @see CPU_LITTLE_ENDIAN
380 *
381 * Port Specific Information:
382 *
383 * XXX document implementation including references if appropriate
384 */
385#define CPU_BIG_ENDIAN TRUE
386
387/**
388 * Define what is required to specify how the network to host conversion
389 * routines are handled.
390 *
391 * NOTE: @ref CPU_BIG_ENDIAN and @ref CPU_LITTLE_ENDIAN should NOT have the
392 * same values.
393 *
394 * @see CPU_BIG_ENDIAN
395 *
396 * Port Specific Information:
397 *
398 * XXX document implementation including references if appropriate
399 */
400#define CPU_LITTLE_ENDIAN FALSE
401
402/** @} */
403
404/**
405 * @ingroup CPUInterrupt
406 *
407 * The following defines the number of bits actually used in the
408 * interrupt field of the task mode. How those bits map to the
409 * CPU interrupt levels is defined by the routine @ref _CPU_ISR_Set_level.
410 *
411 * Port Specific Information:
412 *
413 * XXX document implementation including references if appropriate
414 */
415#define CPU_MODES_INTERRUPT_MASK 0x00000001
416
417#define CPU_PER_CPU_CONTROL_SIZE 0
418
419/*
420 * Processor defined structures required for cpukit/score.
421 *
422 * Port Specific Information:
423 *
424 * XXX document implementation including references if appropriate
425 */
426
427/* may need to put some structures here. */
428
429typedef struct {
430 /* There is no CPU specific per-CPU state */
431} CPU_Per_CPU_control;
432
433/**
434 * @defgroup CPUContext Processor Dependent Context Management
435 *
436 * From the highest level viewpoint, there are 2 types of context to save.
437 *
438 * -# Interrupt registers to save
439 * -# Task level registers to save
440 *
441 * Since RTEMS handles integer and floating point contexts separately, this
442 * means we have the following 3 context items:
443 *
444 * -# task level context stuff:: Context_Control
445 * -# floating point task stuff:: Context_Control_fp
446 * -# special interrupt level context :: CPU_Interrupt_frame
447 *
448 * On some processors, it is cost-effective to save only the callee
449 * preserved registers during a task context switch. This means
450 * that the ISR code needs to save those registers which do not
451 * persist across function calls. It is not mandatory to make this
452 * distinctions between the caller/callee saves registers for the
453 * purpose of minimizing context saved during task switch and on interrupts.
454 * If the cost of saving extra registers is minimal, simplicity is the
455 * choice. Save the same context on interrupt entry as for tasks in
456 * this case.
457 *
458 * Additionally, if gdb is to be made aware of RTEMS tasks for this CPU, then
459 * care should be used in designing the context area.
460 *
461 * On some CPUs with hardware floating point support, the Context_Control_fp
462 * structure will not be used or it simply consist of an array of a
463 * fixed number of bytes. This is done when the floating point context
464 * is dumped by a "FP save context" type instruction and the format
465 * is not really defined by the CPU. In this case, there is no need
466 * to figure out the exact format -- only the size. Of course, although
467 * this is enough information for RTEMS, it is probably not enough for
468 * a debugger such as gdb. But that is another problem.
469 *
470 * Port Specific Information:
471 *
472 * XXX document implementation including references if appropriate
473 */
474/**@{**/
475
476/**
477 * @ingroup Management
478 *
479 * This defines the minimal set of integer and processor state registers
480 * that must be saved during a voluntary context switch from one thread
481 * to another.
482 */
483typedef struct {
484 /** This will contain the stack pointer. */
485 uint32_t sp;
486 /** This will contain the frame base pointer. */
487 uint32_t fb;
488} Context_Control;
489
490/**
491 * @ingroup Management
492 *
493 * This macro returns the stack pointer associated with @a _context.
494 *
495 * @param[in] _context is the thread context area to access
496 *
497 * @return This method returns the stack pointer.
498 */
499#define _CPU_Context_Get_SP( _context ) \
500 (_context)->sp
501
502/**
503 * @ingroup Management
504 *
505 * This defines the set of integer and processor state registers that must
506 * be saved during an interrupt. This set does not include any which are
507 * in @ref Context_Control.
508 */
509typedef struct {
510 /**
511 * This field is a hint that a port will have a number of integer
512 * registers that need to be saved when an interrupt occurs or
513 * when a context switch occurs at the end of an ISR.
514 */
515 uint32_t special_interrupt_register;
516} CPU_Interrupt_frame;
517
518/** @} */
519
520/**
521 * @defgroup CPUInterrupt Processor Dependent Interrupt Management
522 *
523 * On some CPUs, RTEMS supports a software managed interrupt stack.
524 * This stack is allocated by the Interrupt Manager and the switch
525 * is performed in @ref _ISR_Handler. These variables contain pointers
526 * to the lowest and highest addresses in the chunk of memory allocated
527 * for the interrupt stack. Since it is unknown whether the stack
528 * grows up or down (in general), this give the CPU dependent
529 * code the option of picking the version it wants to use.
530 *
531 * NOTE: These two variables are required if the macro
532 * @ref CPU_HAS_SOFTWARE_INTERRUPT_STACK is defined as TRUE.
533 *
534 * Port Specific Information:
535 *
536 * XXX document implementation including references if appropriate
537 *
538 */
539/**@{**/
540
541/*
542 * Nothing prevents the porter from declaring more CPU specific variables.
543 *
544 * Port Specific Information:
545 *
546 * XXX document implementation including references if appropriate
547 */
548
549/* XXX: if needed, put more variables here */
550
551/**
552 * Amount of extra stack (above minimum stack size) required by
553 * MPCI receive server thread. Remember that in a multiprocessor
554 * system this thread must exist and be able to process all directives.
555 *
556 * Port Specific Information:
557 *
558 * XXX document implementation including references if appropriate
559 */
560#define CPU_MPCI_RECEIVE_SERVER_EXTRA_STACK 0
561
562/**
563 * This defines the number of entries in the @ref _ISR_Vector_table managed
564 * by RTEMS.
565 *
566 * Port Specific Information:
567 *
568 * XXX document implementation including references if appropriate
569 */
570#define CPU_INTERRUPT_NUMBER_OF_VECTORS 32
571
572/** This defines the highest interrupt vector number for this port. */
573#define CPU_INTERRUPT_MAXIMUM_VECTOR_NUMBER (CPU_INTERRUPT_NUMBER_OF_VECTORS - 1)
574
575/**
576 * This is defined if the port has a special way to report the ISR nesting
577 * level. Most ports maintain the variable @a _ISR_Nest_level.
578 */
579#define CPU_PROVIDES_ISR_IS_IN_PROGRESS FALSE
580
581/** @} */
582
583/**
584 * @ingroup CPUContext
585 *
586 * Should be large enough to run all RTEMS tests. This ensures
587 * that a "reasonable" small application should not have any problems.
588 *
589 * Port Specific Information:
590 *
591 * XXX document implementation including references if appropriate
592 */
593#define CPU_STACK_MINIMUM_SIZE (2048L)
594
595#ifdef __m32cm_cpu__
596 #define CPU_SIZEOF_POINTER 4
597#else
598 #define CPU_SIZEOF_POINTER 2
599#endif
600
601/**
602 * CPU's worst alignment requirement for data types on a byte boundary. This
603 * alignment does not take into account the requirements for the stack.
604 *
605 * Port Specific Information:
606 *
607 * XXX document implementation including references if appropriate
608 */
609#define CPU_ALIGNMENT 2
610
611/**
612 * This number corresponds to the byte alignment requirement for the
613 * heap handler. This alignment requirement may be stricter than that
614 * for the data types alignment specified by @ref CPU_ALIGNMENT. It is
615 * common for the heap to follow the same alignment requirement as
616 * @ref CPU_ALIGNMENT. If the @ref CPU_ALIGNMENT is strict enough for
617 * the heap, then this should be set to @ref CPU_ALIGNMENT.
618 *
619 * NOTE: This does not have to be a power of 2 although it should be
620 * a multiple of 2 greater than or equal to 2. The requirement
621 * to be a multiple of 2 is because the heap uses the least
622 * significant field of the front and back flags to indicate
623 * that a block is in use or free. So you do not want any odd
624 * length blocks really putting length data in that bit.
625 *
626 * On byte oriented architectures, @ref CPU_HEAP_ALIGNMENT normally will
627 * have to be greater or equal to than @ref CPU_ALIGNMENT to ensure that
628 * elements allocated from the heap meet all restrictions.
629 *
630 * Port Specific Information:
631 *
632 * XXX document implementation including references if appropriate
633 */
634#define CPU_HEAP_ALIGNMENT 4
635
636/**
637 * This number corresponds to the byte alignment requirement for memory
638 * buffers allocated by the partition manager. This alignment requirement
639 * may be stricter than that for the data types alignment specified by
640 * @ref CPU_ALIGNMENT. It is common for the partition to follow the same
641 * alignment requirement as @ref CPU_ALIGNMENT. If the @ref CPU_ALIGNMENT is
642 * strict enough for the partition, then this should be set to
643 * @ref CPU_ALIGNMENT.
644 *
645 * NOTE: This does not have to be a power of 2. It does have to
646 * be greater or equal to than @ref CPU_ALIGNMENT.
647 *
648 * Port Specific Information:
649 *
650 * XXX document implementation including references if appropriate
651 */
652#define CPU_PARTITION_ALIGNMENT CPU_ALIGNMENT
653
654/**
655 * This number corresponds to the byte alignment requirement for the
656 * stack. This alignment requirement may be stricter than that for the
657 * data types alignment specified by @ref CPU_ALIGNMENT. If the
658 * @ref CPU_ALIGNMENT is strict enough for the stack, then this should be
659 * set to 0.
660 *
661 * NOTE: This must be a power of 2 either 0 or greater than @ref CPU_ALIGNMENT.
662 *
663 * Port Specific Information:
664 *
665 * XXX document implementation including references if appropriate
666 */
667#define CPU_STACK_ALIGNMENT 0
668
669/*
670 * ISR handler macros
671 */
672
673/**
674 * @ingroup CPUInterrupt
675 *
676 * Support routine to initialize the RTEMS vector table after it is allocated.
677 *
678 * Port Specific Information:
679 *
680 * XXX document implementation including references if appropriate
681 */
682#define _CPU_Initialize_vectors()
683
684/**
685 * @ingroup CPUInterrupt
686 *
687 * Disable all interrupts for an RTEMS critical section. The previous
688 * level is returned in @a _isr_cookie.
689 *
690 * @param[out] _isr_cookie will contain the previous level cookie
691 *
692 * Port Specific Information:
693 *
694 * XXX document implementation including references if appropriate
695 */
696#define _CPU_ISR_Disable( _isr_cookie ) \
697 do { \
698 int _flg; \
699 m32c_get_flg( _flg ); \
700 _isr_cookie = _flg; \
701 __asm__ volatile( "fclr I" ); \
702 } while(0)
703
704/**
705 * @ingroup CPUInterrupt
706 *
707 * Enable interrupts to the previous level (returned by _CPU_ISR_Disable).
708 * This indicates the end of an RTEMS critical section. The parameter
709 * @a _isr_cookie is not modified.
710 *
711 * @param[in] _isr_cookie contain the previous level cookie
712 *
713 * Port Specific Information:
714 *
715 * XXX document implementation including references if appropriate
716 */
717#define _CPU_ISR_Enable(_isr_cookie) \
718 do { \
719 int _flg = (int) (_isr_cookie); \
720 m32c_set_flg( _flg ); \
721 } while(0)
722
723/**
724 * @ingroup CPUInterrupt
725 *
726 * This temporarily restores the interrupt to @a _isr_cookie before immediately
727 * disabling them again. This is used to divide long RTEMS critical
728 * sections into two or more parts. The parameter @a _isr_cookie is not
729 * modified.
730 *
731 * @param[in] _isr_cookie contain the previous level cookie
732 *
733 * Port Specific Information:
734 *
735 * XXX document implementation including references if appropriate
736 */
737#define _CPU_ISR_Flash( _isr_cookie ) \
738 do { \
739 int _flg = (int) (_isr_cookie); \
740 m32c_set_flg( _flg ); \
741 __asm__ volatile( "fclr I" ); \
742 } while(0)
743
744/**
745 * @ingroup CPUInterrupt
746 *
747 * This routine and @ref _CPU_ISR_Get_level
748 * Map the interrupt level in task mode onto the hardware that the CPU
749 * actually provides. Currently, interrupt levels which do not
750 * map onto the CPU in a generic fashion are undefined. Someday,
751 * it would be nice if these were "mapped" by the application
752 * via a callout. For example, m68k has 8 levels 0 - 7, levels
753 * 8 - 255 would be available for bsp/application specific meaning.
754 *This could be used to manage a programmable interrupt controller
755 * via the rtems_task_mode directive.
756 *
757 * Port Specific Information:
758 *
759 * XXX document implementation including references if appropriate
760 */
761#define _CPU_ISR_Set_level( _new_level ) \
762 do { \
763 if (_new_level) __asm__ volatile( "fclr I" ); \
764 else __asm__ volatile( "fset I" ); \
765 } while(0)
766
767/**
768 * @ingroup CPUInterrupt
769 *
770 * Return the current interrupt disable level for this task in
771 * the format used by the interrupt level portion of the task mode.
772 *
773 * NOTE: This routine usually must be implemented as a subroutine.
774 *
775 * Port Specific Information:
776 *
777 * XXX document implementation including references if appropriate
778 */
779uint32_t _CPU_ISR_Get_level( void );
780
781/* end of ISR handler macros */
782
783/* Context handler macros */
784
785/**
786 * @ingroup CPUContext
787 *
788 * Initialize the context to a state suitable for starting a
789 * task after a context restore operation. Generally, this
790 * involves:
791 *
792 * - setting a starting address
793 * - preparing the stack
794 * - preparing the stack and frame pointers
795 * - setting the proper interrupt level in the context
796 * - initializing the floating point context
797 *
798 * This routine generally does not set any unnecessary register
799 * in the context. The state of the "general data" registers is
800 * undefined at task start time.
801 *
802 * @param[in] _the_context is the context structure to be initialized
803 * @param[in] _stack_base is the lowest physical address of this task's stack
804 * @param[in] _size is the size of this task's stack
805 * @param[in] _isr is the interrupt disable level
806 * @param[in] _entry_point is the thread's entry point. This is
807 * always @a _Thread_Handler
808 * @param[in] _is_fp is TRUE if the thread is to be a floating
809 * point thread. This is typically only used on CPUs where the
810 * FPU may be easily disabled by software such as on the SPARC
811 * where the PSR contains an enable FPU bit.
812 * @param[in] tls_area is the thread-local storage (TLS) area
813 *
814 * Port Specific Information:
815 *
816 * XXX document implementation including references if appropriate
817 */
818void _CPU_Context_Initialize(
819 Context_Control *the_context,
820 uint32_t *stack_base,
821 size_t size,
822 uint32_t new_level,
823 void *entry_point,
824 bool is_fp,
825 void *tls_area
826);
827
828/**
829 * This routine is responsible for somehow restarting the currently
830 * executing task. If you are lucky, then all that is necessary
831 * is restoring the context. Otherwise, there will need to be
832 * a special assembly routine which does something special in this
833 * case. For many ports, simply adding a label to the restore path
834 * of @ref _CPU_Context_switch will work. On other ports, it may be
835 * possibly to load a few arguments and jump to the restore path. It will
836 * not work if restarting self conflicts with the stack frame
837 * assumptions of restoring a context.
838 *
839 * Port Specific Information:
840 *
841 * XXX document implementation including references if appropriate
842 */
843void _CPU_Context_Restart_self(
844 Context_Control *the_context
845);
846
847/**
848 * @ingroup CPUContext
849 *
850 * The purpose of this macro is to allow the initial pointer into
851 * a floating point context area (used to save the floating point
852 * context) to be at an arbitrary place in the floating point
853 * context area.
854 *
855 * This is necessary because some FP units are designed to have
856 * their context saved as a stack which grows into lower addresses.
857 * Other FP units can be saved by simply moving registers into offsets
858 * from the base of the context area. Finally some FP units provide
859 * a "dump context" instruction which could fill in from high to low
860 * or low to high based on the whim of the CPU designers.
861 *
862 * @param[in] _base is the lowest physical address of the floating point
863 * context area
864 * @param[in] _offset is the offset into the floating point area
865 *
866 * Port Specific Information:
867 *
868 * XXX document implementation including references if appropriate
869 */
870#define _CPU_Context_Fp_start( _base, _offset ) \
871 ( (void *) _Addresses_Add_offset( (_base), (_offset) ) )
872
873/**
874 * This routine initializes the FP context area passed to it to.
875 * There are a few standard ways in which to initialize the
876 * floating point context. The code included for this macro assumes
877 * that this is a CPU in which a "initial" FP context was saved into
878 * @a _CPU_Null_fp_context and it simply copies it to the destination
879 * context passed to it.
880 *
881 * Other floating point context save/restore models include:
882 * -# not doing anything, and
883 * -# putting a "null FP status word" in the correct place in the FP context.
884 *
885 * @param[in] _destination is the floating point context area
886 *
887 * Port Specific Information:
888 *
889 * XXX document implementation including references if appropriate
890 */
891#define _CPU_Context_Initialize_fp( _destination ) \
892 { \
893 *(*(_destination)) = _CPU_Null_fp_context; \
894 }
895
896/* end of Context handler macros */
897
898/* Fatal Error manager macros */
899
900/**
901 * This routine copies _error into a known place -- typically a stack
902 * location or a register, optionally disables interrupts, and
903 * halts/stops the CPU.
904 *
905 * Port Specific Information:
906 *
907 * XXX document implementation including references if appropriate
908 */
909#define _CPU_Fatal_halt( _source, _error ) \
910 { \
911 }
912
913/* end of Fatal Error manager macros */
914
915/* Bitfield handler macros */
916
917/**
918 * @defgroup CPUBitfield Processor Dependent Bitfield Manipulation
919 *
920 * This set of routines are used to implement fast searches for
921 * the most important ready task.
922 */
923/**@{**/
924
925/**
926 * This definition is set to TRUE if the port uses the generic bitfield
927 * manipulation implementation.
928 */
929#define CPU_USE_GENERIC_BITFIELD_CODE TRUE
930
931/**
932 * This definition is set to TRUE if the port uses the data tables provided
933 * by the generic bitfield manipulation implementation.
934 * This can occur when actually using the generic bitfield manipulation
935 * implementation or when implementing the same algorithm in assembly
936 * language for improved performance. It is unlikely that a port will use
937 * the data if it has a bitfield scan instruction.
938 */
939#define CPU_USE_GENERIC_BITFIELD_DATA TRUE
940
941/**
942 * This routine sets @a _output to the bit number of the first bit
943 * set in @a _value. @a _value is of CPU dependent type
944 * @a Priority_bit_map_Word. This type may be either 16 or 32 bits
945 * wide although only the 16 least significant bits will be used.
946 *
947 * There are a number of variables in using a "find first bit" type
948 * instruction.
949 *
950 * -# What happens when run on a value of zero?
951 * -# Bits may be numbered from MSB to LSB or vice-versa.
952 * -# The numbering may be zero or one based.
953 * -# The "find first bit" instruction may search from MSB or LSB.
954 *
955 * RTEMS guarantees that (1) will never happen so it is not a concern.
956 * (2),(3), (4) are handled by the macros @ref _CPU_Priority_Mask and
957 * @ref _CPU_Priority_bits_index. These three form a set of routines
958 * which must logically operate together. Bits in the _value are
959 * set and cleared based on masks built by @ref _CPU_Priority_Mask.
960 * The basic major and minor values calculated by @ref _Priority_Major
961 * and @ref _Priority_Minor are "massaged" by @ref _CPU_Priority_bits_index
962 * to properly range between the values returned by the "find first bit"
963 * instruction. This makes it possible for @ref _Priority_Get_highest to
964 * calculate the major and directly index into the minor table.
965 * This mapping is necessary to ensure that 0 (a high priority major/minor)
966 * is the first bit found.
967 *
968 * This entire "find first bit" and mapping process depends heavily
969 * on the manner in which a priority is broken into a major and minor
970 * components with the major being the 4 MSB of a priority and minor
971 * the 4 LSB. Thus (0 << 4) + 0 corresponds to priority 0 -- the highest
972 * priority. And (15 << 4) + 14 corresponds to priority 254 -- the next
973 * to the lowest priority.
974 *
975 * If your CPU does not have a "find first bit" instruction, then
976 * there are ways to make do without it. Here are a handful of ways
977 * to implement this in software:
978 *
979@verbatim
980 - a series of 16 bit test instructions
981 - a "binary search using if's"
982 - _number = 0
983 if _value > 0x00ff
984 _value >>=8
985 _number = 8;
986
987 if _value > 0x0000f
988 _value >=8
989 _number += 4
990
991 _number += bit_set_table[ _value ]
992@endverbatim
993
994 * where bit_set_table[ 16 ] has values which indicate the first
995 * bit set
996 *
997 * @param[in] _value is the value to be scanned
998 * @param[in] _output is the first bit set
999 *
1000 * Port Specific Information:
1001 *
1002 * XXX document implementation including references if appropriate
1003 */
1004
1005#if (CPU_USE_GENERIC_BITFIELD_CODE == FALSE)
1006#define _CPU_Bitfield_Find_first_bit( _value, _output ) \
1007 { \
1008 (_output) = 0; /* do something to prevent warnings */ \
1009 }
1010#endif
1011
1012/* end of Bitfield handler macros */
1013
1014/**
1015 * This routine builds the mask which corresponds to the bit fields
1016 * as searched by @ref _CPU_Bitfield_Find_first_bit. See the discussion
1017 * for that routine.
1018 *
1019 * Port Specific Information:
1020 *
1021 * XXX document implementation including references if appropriate
1022 */
1023#if (CPU_USE_GENERIC_BITFIELD_CODE == FALSE)
1024
1025#define _CPU_Priority_Mask( _bit_number ) \
1026 ( 1 << (_bit_number) )
1027
1028#endif
1029
1030/**
1031 * This routine translates the bit numbers returned by
1032 * @ref _CPU_Bitfield_Find_first_bit into something suitable for use as
1033 * a major or minor component of a priority. See the discussion
1034 * for that routine.
1035 *
1036 * @param[in] _priority is the major or minor number to translate
1037 *
1038 * Port Specific Information:
1039 *
1040 * XXX document implementation including references if appropriate
1041 */
1042#if (CPU_USE_GENERIC_BITFIELD_CODE == FALSE)
1043
1044#define _CPU_Priority_bits_index( _priority ) \
1045 (_priority)
1046
1047#endif
1048
1049/** @} */
1050
1051/* end of Priority handler macros */
1052
1053/* functions */
1054
1055/**
1056 * This routine performs CPU dependent initialization.
1057 *
1058 * Port Specific Information:
1059 *
1060 * XXX document implementation including references if appropriate
1061 */
1062void _CPU_Initialize(void);
1063
1064/**
1065 * @ingroup CPUInterrupt
1066 *
1067 * This routine installs a "raw" interrupt handler directly into the
1068 * processor's vector table.
1069 *
1070 * @param[in] vector is the vector number
1071 * @param[in] new_handler is the raw ISR handler to install
1072 * @param[in] old_handler is the previously installed ISR Handler
1073 *
1074 * Port Specific Information:
1075 *
1076 * XXX document implementation including references if appropriate
1077 */
1078void _CPU_ISR_install_raw_handler(
1079 uint32_t vector,
1080 proc_ptr new_handler,
1081 proc_ptr *old_handler
1082);
1083
1084/**
1085 * @ingroup CPUInterrupt
1086 *
1087 * This routine installs an interrupt vector.
1088 *
1089 * @param[in] vector is the vector number
1090 * @param[in] new_handler is the RTEMS ISR handler to install
1091 * @param[in] old_handler is the previously installed ISR Handler
1092 *
1093 * Port Specific Information:
1094 *
1095 * XXX document implementation including references if appropriate
1096 */
1097void _CPU_ISR_install_vector(
1098 uint32_t vector,
1099 proc_ptr new_handler,
1100 proc_ptr *old_handler
1101);
1102
1103/**
1104 * @ingroup CPUInterrupt
1105 *
1106 * This routine installs the hardware interrupt stack pointer.
1107 *
1108 * NOTE: It need only be provided if @ref CPU_HAS_HARDWARE_INTERRUPT_STACK
1109 * is TRUE.
1110 *
1111 * Port Specific Information:
1112 *
1113 * XXX document implementation including references if appropriate
1114 */
1115void _CPU_Install_interrupt_stack( void );
1116
1117/**
1118 * This routine is the CPU dependent IDLE thread body.
1119 *
1120 * NOTE: It need only be provided if @ref CPU_PROVIDES_IDLE_THREAD_BODY
1121 * is TRUE.
1122 *
1123 * Port Specific Information:
1124 *
1125 * XXX document implementation including references if appropriate
1126 */
1127void *_CPU_Thread_Idle_body( uintptr_t ignored );
1128
1129/**
1130 * @ingroup CPUContext
1131 *
1132 * This routine switches from the run context to the heir context.
1133 *
1134 * @param[in] run points to the context of the currently executing task
1135 * @param[in] heir points to the context of the heir task
1136 *
1137 * Port Specific Information:
1138 *
1139 * XXX document implementation including references if appropriate
1140 */
1141void _CPU_Context_switch(
1142 Context_Control *run,
1143 Context_Control *heir
1144);
1145
1146/**
1147 * @ingroup CPUContext
1148 *
1149 * This routine is generally used only to restart self in an
1150 * efficient manner. It may simply be a label in @ref _CPU_Context_switch.
1151 *
1152 * @param[in] new_context points to the context to be restored.
1153 *
1154 * NOTE: May be unnecessary to reload some registers.
1155 *
1156 * Port Specific Information:
1157 *
1158 * XXX document implementation including references if appropriate
1159 */
1160void _CPU_Context_restore(
1161 Context_Control *new_context
1162) RTEMS_COMPILER_NO_RETURN_ATTRIBUTE;
1163
1164static inline void _CPU_Context_volatile_clobber( uintptr_t pattern )
1165{
1166 /* TODO */
1167}
1168
1169static inline void _CPU_Context_validate( uintptr_t pattern )
1170{
1171 while (1) {
1172 /* TODO */
1173 }
1174}
1175
1176/* FIXME */
1177typedef CPU_Interrupt_frame CPU_Exception_frame;
1178
1179void _CPU_Exception_frame_print( const CPU_Exception_frame *frame );
1180
1181/**
1182 * @ingroup CPUEndian
1183 *
1184 * The following routine swaps the endian format of an unsigned int.
1185 * It must be static because it is referenced indirectly.
1186 *
1187 * This version will work on any processor, but if there is a better
1188 * way for your CPU PLEASE use it. The most common way to do this is to:
1189 *
1190 * swap least significant two bytes with 16-bit rotate
1191 * swap upper and lower 16-bits
1192 * swap most significant two bytes with 16-bit rotate
1193 *
1194 * Some CPUs have special instructions which swap a 32-bit quantity in
1195 * a single instruction (e.g. i486). It is probably best to avoid
1196 * an "endian swapping control bit" in the CPU. One good reason is
1197 * that interrupts would probably have to be disabled to ensure that
1198 * an interrupt does not try to access the same "chunk" with the wrong
1199 * endian. Another good reason is that on some CPUs, the endian bit
1200 * endianness for ALL fetches -- both code and data -- so the code
1201 * will be fetched incorrectly.
1202 *
1203 * @param[in] value is the value to be swapped
1204 * @return the value after being endian swapped
1205 *
1206 * Port Specific Information:
1207 *
1208 * XXX document implementation including references if appropriate
1209 */
1210static inline uint32_t CPU_swap_u32(
1211 uint32_t value
1212)
1213{
1214 uint32_t byte1, byte2, byte3, byte4, swapped;
1215
1216 byte4 = (value >> 24) & 0xff;
1217 byte3 = (value >> 16) & 0xff;
1218 byte2 = (value >> 8) & 0xff;
1219 byte1 = value & 0xff;
1220
1221 swapped = (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4;
1222 return swapped;
1223}
1224
1225/**
1226 * @ingroup CPUEndian
1227 *
1228 * This routine swaps a 16 bir quantity.
1229 *
1230 * @param[in] value is the value to be swapped
1231 * @return the value after being endian swapped
1232 */
1233#define CPU_swap_u16( value ) \
1234 (((value&0xff) << 8) | ((value >> 8)&0xff))
1235
1236typedef uint32_t CPU_Counter_ticks;
1237
1238CPU_Counter_ticks _CPU_Counter_read( void );
1239
1240static inline CPU_Counter_ticks _CPU_Counter_difference(
1241 CPU_Counter_ticks second,
1242 CPU_Counter_ticks first
1243)
1244{
1245 return second - first;
1246}
1247
1248#ifdef __cplusplus
1249}
1250#endif
1251
1252#endif
Note: See TracBrowser for help on using the repository browser.
|
__label__pos
| 0.997445 |
function [t,y] = eulersys(dydt,tspan,y0,h,varargin) % eulode: Euler ODE solver % [t,y] = eulode(dydt,tspan,y0,h,p1,p2,...): % uses Euler's method to integrate % input: % dydt = name of the M-file that evaluates the system ODE % tspan = [ti, tf] where ti and tf = initial and % final values of independent variable % y0 = initial value of dependent variables % h = step size % p1,p2,... = additional parameters used by dydt % output: % t = vector of independent variable % y = vector of solution for dependent variable % modified from eulerode.m on June 9, 2017 by Whenson Zhou % using a hint from rkr4.m if nargin<4,error('at least 4 input arguments required'),end ti = tspan(1);tf = tspan(2); if ~(tf>ti),error('upper limit must be greater than lower'),end t = (ti:h:tf)'; n = length(t); % if necessary, add an additional value of t % so that range goes from t = ti to tf if t(n)
|
__label__pos
| 0.985559 |
7.10
Conclusion
In this chapter, we learned what single-page apps are and how to build them in Elm. We also learned how to Create, Read, Update, and Delete (CRUD) resources on a server from an Elm app. The built-in modules — Http, Json.Decode, and Json.Encode — provide everything we need for creating CRUD requests.
As we started adding more features to our app, we realized that we needed to split our code into smaller modules. We followed a simple yet highly scalable structure recommended by Evan Czaplicki — the creator of Elm — to organize our code.
We built separate pages for creating, updating, and retrieving resources from a server. The elm/browser and elm/url packages allowed us to build a robust navigation system for routing users to correct pages based on paths.
In the next chapter, we’ll learn how to interact with JavaScript from Elm using ports.
Back to top
Close
|
__label__pos
| 0.913603 |
Typed arrays
Getting values from typed arrays an important behavior difference between PHP and KPHP.
Getting an unexisting element is T, not null
When you have T[], reading by any index infers as T. So, reading unexisting returns empty T:
$a = [1,2,3];
$int = $a[100]; // int (0)
["a", "b"][999]; // string ""
$tuples = [tuple(5, "a")];
$tuples['asdf']; // tuple(0, "")
$int2 = [[1],[2]]; // int[][]
$int2[100]; // array()
If T can handle null, then this problem doesn't exist. For instance, objects and mixed are nullable:
$a = [1, 2, null, 4]; // (int|null)[]
$a[100]; // null => as in PHP
[new User][100]; // null => as in PHP
$mixed_arr['unexisting']; // null => as in PHP
This behavior exists on purpose, because if indexing T[] would be ?T, it would tremendously spoil all types.
Getting an existing element is T
This case can be found in float[] which mixes floats and ints:
$a = [1, 2, 4.12]; // float[]
$a[0]; // float (1.0)! not int (1)!
Typically, it is not a problem (surprising!)
When you get 0 instead of null, you typically compare it / sum it up / etc. null often behaves like empty T:
$v = $int_arr[100500]; // 0 in KPHP, null in PHP
if ($v) ; // equal (false)
if ($v > 1.2) ; // equal (false)
$v == 0; // equal (true) (since ==, not ===)
$v + 3.5; // equal (3.5)
10 << $v; // equal (10)
$s = $str_arr[100500]; // "" in KPHP, null in PHP
"style='$s'"; // equal (style='')
$s[0]; // equal ('')
strlen($s); // equal (0)
$a = $arr_arr[100500]; // [] in KPHP, null in PHP
count($a); // equal (0)
if ($a); // equal (false)
if ($a['some_idx']); // equal (false)
isset($a[0]); // equal (false)
If the result may differ, KPHP produces compilation errors
Examples above work identically, regardless of different actual values in PHP/KPHP.
Here are examples that produce different results because of this problem:
$v = $float_arr[0]; // 1.0 in KPHP, 1 in PHP
is_float($v); // would work differently
$v = $int_arr[100500]; // 0 in KPHP, null in PHP
$v === 0; // would work differently (since ===, not ==)
KPHP is able to find such cases and produce an error.
Example — and an error:
$v = $float_arr[0];
is_float($v);
// 6:is_float($v);
isset, !==, ===, is_array or similar function result may differ from PHP
Probably, this happened because as expression: $float_arr[.] : float at dev.php: demo:5 of type double can't be null in KPHP, while it can be in PHP
Example 2 — and a similar error:
$v = $int_arr[100500];
$v === 0;
// 9: $v === 0;
isset, !==, ===, is_array or similar function result may differ from PHP
Probably, this happened because as expression: $int_arr[.] : int at dev.php: demo:9 of type int can't be null in KPHP, while it can be in PHP
But still, echo and some others would work differently. In practice, it's very unlikely to come across such misbehavior.
How to deal with this error ‘… result may differ from PHP'?
This error protects you from getting an unexisting index. Real-life example:
function getMarkupElements(): array {
$html = '<div></div>';
$js = '';
return ['html' => $html, 'js' => $js];
}
function renderUI(array $markup): string {
$js = $markup['js'];
if ($js !== '')
$js = "<script>$js</script>";
return $markup['html'] . $js;
}
renderUI(getMarkupElements());
You try to compile this valid code and get a compilation error:
// 11: if ($js !== '')
isset, !==, ===, is_array or similar function result may differ from PHP
Probably, this happened because as expression: $markup[.] : string at dev.php: renderUI:10 of type string can't be null in KPHP, while it can be in PHP
You analyze the error and understand, that array $markup was inferred as string[], and if ($js !== '') would work differently if ['js'] key doesn't exist in $markup.
But you know, that key exists. The compiler is right in general, but in this case, you want to suppress this error:
// either
$js = (string)$markup['js'];
// or
$js = not_null($markup['js']);
Using not_null() is more elegant and semantic, it is a preferred solution.
Concluding typed arrays
Getting unexisting elements from typed arrays differs in PHP and KPHP, but typically it’s not a problem.
If KPHP finds potential misbehavior, it warns you.
Sometimes KPHP is correct and you should reconsider your code.
Sometimes you know better and suppress it with cast or not_null().
|
__label__pos
| 0.847705 |
SQL graphic
NoSQL vs SQL
NoSQL Graphic
SQL vs NoSQL Difference
SQL and NoSQL represent two of the most common types of databases. SQL stands for Structured Query Language and is used in most modern relational database management systems (RDBMS). NoSQL means either “no SQL” (it does not use any SQL for querying) or “not only SQL” (it uses both SQL and non-SQL querying methods). NoSQL is generally used in a non-relational database (in that it doesn’t support foreign keys and joins across tables). The differences between SQL vs NoSQL databases include how they are built, the structure and types of data they hold, and how the data is stored and queried.
Relational (SQL) databases use a rigid structure of tables with columns and rows. There is one entry per row and each column contains a specific piece of information. The highly organized data requires normalization, which reduces data redundancy and improves reliability. SQL is a highly-controlled standard, supported by the American National Standards Institute (ANSI) and the International Standards Organization (ISO).
Non-relational databases are often implemented as NoSQL systems. There is not one type of NoSQL database. There are many different schemas, from key-value stores, to document stores, graph databases, time series databases and wide-column stores. Some NoSQL systems also support “multi-model” schemas, meaning they can support more than one data schema internally.
Unlike the ANSI/ISO processes for the SQL standard, there is no industry standard around implementing NoSQL systems. The exact manner of supporting various NoSQL schemas is up to the various individual software developers. Implementations of NoSQL databases can be widely divergent and incompatible. For instance, even if two systems are both key-value databases, their APIs, data models, and storage methods may be highly divergent and mutually incompatible.
NoSQL systems don’t rely on, nor can they support, joined tables.
Diagram depicting the key differences between SQL Database and NoSQL Databases.
Figure 1: Diagram depicting the key differences between SQL Database and NoSQL Databases.
When to Use NoSQL vs SQL
NoSQL vs SQL performance comparison is based on attributes like consistency, availability and speed. The needs of an enterprise generally determine which type of database system to use.
A relational (SQL) database is ideal for handling data models that are well-understood, may not change often, require adherence to strict international standards, and for businesses that value data consistency over transaction speed.
A non-relational (NoSQL) database is ideal for companies facing changing data requirements, those that can adapt to rapidly-evolving vendor-driven standards and APIs, and those who need to deal with multiple types of data and high traffic volumes.
But there are always exceptions. Time series data models are well understood and so are key values, which are not traditional SQL models. Many NoSQL databases are consistent, though not ACID.
SQL and NoSQL Databases
Popular relational (SQL) databases include:
• IBM DB2
• Oracle Database
• Microsoft SQL Server
• MySQL
Popular non-relational (NoSQL) databases include:
• Apache Cassandra
• Apache HBase
• MongoDB
• Redis
• Scylla
Common types of NoSQL databases include:
• Key-value store — Stores data with simple indexed keys and values. Examples include Oracle NoSQL database, Redis, Aerospike, Oracle Berkeley DB, Voldemort, Amazon DynamoDB and Infinity DB.
• Wide column store — Uses tables, rows and columns. But the format and naming of the columns can vary in different rows within the same table. Examples include Apache Cassandra, Scylla, Datastax Enterprise, Apache HBase, Apache Kudu, Apache Parquet and MonetDB.
• Document database — A more complex and structured version of the key-value model, which gives each document its own retrieval key. Examples include Orient DB, MarkLogic, MongoDB, IBM Cloudant, Couchbase, and Apache CouchDB.
• Graph database — Presents interconnected data as a logical graph. Examples include Neo4j, JanusGraph, FlockDB and GraphDB.
Multi-model Databases
A major trend in modern databases is to support more than one data model. For example, systems that support both traditional SQL as well as one (or more) NoSQL schema. Other systems may support multiple NoSQL data models, but not SQL. The combinations are myriad.
For example Cassandra and Scylla, though classified as wide column stores, also readily support key-value use cases. As well, through add-on packages such as JanusGraph, these three NoSQL systems can also support graph database schemas as well. In another example Amazon DynamoDB, though it has origins as a key-value store, also works as a document database.
Big Data Market Size: SQL vs NoSQL
A 2017 IDC report predicted worldwide revenues for operational SQL and NoSQL database management systems would increase from $27 billion in 2017 to $40.4 billion by 2022.
The market share of databases is shifting because of NoSQL database vs SQL database competition. As of 2016 SQL still represented 89 percent of the paid database market, according to Gartner. But so-called “mega-vendors” like Oracle and IBM lost two percent of the market in the past five years. And Gartner claims as much as a quarter of the SQL market consists of unpaid, open source databases like MySQL servers and PostgreSQL.
Meanwhile, the NoSQL market is expected to grow more than 20 percent annually to reach $3.4 billion by 2024, according to Market Research Media.
SQL vs CQL
Structured Query Language (SQL) is used in relational databases and other interfaces are used in non-relational databases. For example MongoDB, uses a JavaScript query API. NoSQL databases may have their own custom, proprietary interfaces, or they may share a common query method. For example, a number of NoSQL databases, including Apache Cassandra, Scylla, DataStax Enterprise, and even cloud-native databases like Microsoft Azure Cosmos DB support the Cassandra Query Language (CQL).
While CQL and SQL share many similarities, a key difference between SQL and CQL is that CQL cannot perform joins against tables like SQL can. Query results are also presented differently. SQL returns data type values while CQL can return objects. CQL is also massively scalable, designed to query across a horizontally-distributed cluster of servers.
Other differences include:
SQL
• Used in relational databases (where tables can have joins between them).
• Manages structured data.
• Handles moderate volume and low velocity data from a few locations.
• Creates tables with and without a primary key.
• Adds columns on the right side of the table.
CQL
• Used in non-relational databases.
• Manages unstructured and semi-structured data.
• Handles very high volume and high velocity data from many locations.
• Creates the tables with only a primary key, which acts as a partition key.
• Adds columns in alphabetical order.
SQL and CQL have similarities, too. They both possess database sub-languages and use similar data manipulation statements to store and modify data. They share commands, including:
• “Create” for creating objects.
• “Alter” for changing structure.
• “Drop” for deleting objects.
• “Truncate” for removing records.
• “Rename” for renaming objects.
JSON in NoSQL and SQL
JSON (JavaScript Object Notation) is a format that encapsulates data, such as when it is transported from a server to a web application. It is most often employed in document-oriented databases.
JSON is a simple and lightweight format that is easy to read and write. With the rise of non-relational databases, web-based APIs and microservices, many developers prefer the JSON format. However, it can also be used to parse, store and export data across other databases, both SQL and NoSQL.
JSON lets programmers easily communicate sets of values, lists, and key-value mappings across systems. Data formats in JSON use the following forms:
• Object — unordered set of name/value pairs.
• Array — ordered collection of values.
• Value — a string, number, true/false/null, object or array.
• String — sequence of characters that follow an encoding standard.
• Number — Java numbers such as byte, short and long.
The simplicity of JSON is being embraced by application developers, who prefer JSON over the more complicated XML serialization format for transporting data. JSON also works well in agile environments because JSON allows for efficient usage of data.
This is creating demand for JSON features in both relational and non-relational databases.
Table Joins
A join connects tables based on matching columns in a SQL database. Joins create a relationship between the tables through a link known as foreign keys.
A SQL join combines data from multiple tables for the purpose of understanding the relationship between pieces of data. For example, seeing a customer’s order history. A join of the customer table and the orders table will establish the relationship between one customer and all their orders.
The types of join and join commands vary depending on which records a query retrieves. Join types can be used only after data is loaded into a relational database.
There are five types of table joins:
1. Inner
2. Left
3. Right
4. Full
5. Cross
There is also a self-join when a table can join to itself. The following commands are used for join operations:
• Hash join
• Sort-merge join
• Nested loop join
Normalized vs Denormalized Data
The difference between normalized and denormalized data is the method used for storing and retrieving it.
Denormalized data is combined in one table. This speeds up data retrieval because a query doesn’t have to search multiple tables to find information as it would in the normalized process. Everything is in one place, but data may be duplicated. The added speed comes at the expense of more data redundancy and less data integrity.
This is what a denormalized database looks like:
denormalized database table
Normalized data is stored in multiple tables. One type of data is organized in one table. Related data is stored in another table. Then table JOINs are used to connect relationships between the tables. The benefits of normalized data include reduced redundancy, better consistency and greater data integrity. But the practice can produce slow results, especially when there are complex queries with a lot of data to process.
In a normalized database, there are no repeating fields or columns. The repeating fields are put into new database tables along with the key from the unnormalized database table.
This is what a normalized database table looks like:
normalized database table
Other differences include:
Normalized
• Used in OLTP SQL systems
• Emphasis on faster insert, delete and update
• Maintains data integrity
• Eliminates redundant data sets
• Increases number of tables and JOINS
• Optimizes disk space
Denormalized
• Used in OLAP SQL systems and many NoSQL systems
• Emphasis on faster search and analysis
• Difficult to retain data integrity
• Increases redundant data
• Reduces number of tables and can reduce or eliminate JOINS
• Wastes disk space because the same data is stored in different places
Databases don’t have to be exclusively normalized or denormalized. There is a hybrid option. If speed is a concern, a SQL database can be partially denormalized by removing a certain number of JOINS. If organization and redundancy is a concern, a portion of the data can be normalized in separate tables.
Some circumstances call for denormalization. For example, a denormalized data process is preferred for applications with large tables that run multiple-JOIN queries because creating the JOINS of a normalized database can be expensive and time consuming. Applications that store unstructured data like emails, images and videos are also better suited for denormalization.
Strong vs Eventual Consistency
Consistency refers to a database query returning the same data each time the same request is made. Strong consistency means the latest data is returned, but, due to internal consistency methods, it may result with higher latency or delay. With eventual consistency, results are less consistent early on, but they are provided much faster with low latency.
Early results of eventual consistency data queries may not have the most recent updates. This is because it takes time for updates to reach replicas across a database cluster.
In strong consistency, data is sent to every replica the moment a query is made. This causes delay because responses to any new requests must wait while the replicas are updated. When the data is consistent, the waiting requests are handled in the order they arrived and the cycle repeats.
SQL databases generally support strong consistency, which makes them useful for transactional data in the banking and finance industries.
CQL-compliant NoSQL databases have tunable consistency, which provides low latency and high write throughput best suited for analytical and time-series data.
Other NoSQL databases span the gamut. Some may support strong consistency and others eventual consistency.
CAP Theorem
The CAP theorem explains why a distributed database cannot guarantee both consistency and availability in the face of network partitions. The theorem says an application can guarantee only two of the following three features at the same time:
• Consistency — the same answer is given to all
• Availability — access continues, even during a partial system failure
• Partition tolerance — operations remain in tact, even if some nodes can’t communicate
A useful compromise is to allow for eventual consistency in favor of better scalability. Determining if your application data is a suitable candidate for eventual consistency is a business decision.
When an application gives up strong consistency — where every copy of the data in the system has to match before the transaction is considered complete — it instead becomes eventually consistent. This compromise is often made for the purpose of better scalability. The decision is based on business considerations: how important is each transaction? For situations where each write of data is vital then strong consistency is a requirement. For situations where the aggregate speed or scale of big data management is more important than the specific correctness of any one particular query result, then eventual consistency may make sense.
Cloud-native applications tend to choose the guarantees of availability and partition tolerance over strong consistency. This is because cloud-native applications usually prefer to keep up with scalability targets than to ensure database nodes are always in communication.
While there are three elements in the CAP theorem, the trade-off is mostly between two: availability and consistency. The third element, partition-tolerance, is often considered a requirement; there is no way you can design a network-based distributed system that can avoid a partitioned state, even if temporarily. Therefore partition-tolerance is a necessity for scalability and resiliency, especially when it comes to NoSQL databases.
ACID vs BASE
ACID and BASE are models of database design. The ACID model has four goals that stand for:
• Atomicity — If any part of a transaction isn’t executed successfully, the entire operation is rolled back.
• Consistency — Ensures that a database remains structurally sound with every transaction.
• Isolation — Transactions occur independently of each other and the access to data is moderated.
• Durability — All transaction results are permanently preserved in the database.
Relational databases and some NoSQL databases (those that support strong consistency) that meet these four goals are considered ACID-compliant. This means data is consistent after transactions are complete.
Other non-relational NoSQL databases, however, turn to the BASE model to achieve benefits like scale and resilience. BASE stands for:
• Basic Availability — Data is available most of the time, even during a failure that disrupts part of the database. Data is replicated and spread across many different storage systems.
• Soft-state — Replicas are not consistent all the time.
• Eventual consistency — Data will become consistent at some point in time, with no guarantee when.
BASE principles are less strict than ACID guarantees. BASE values availability over any other value because BASE users care most about scalability. Industries like banking that require data reliability and consistency depend on an ACID-compliant database.
Distribution and Scalability
Scaling up a relational SQL database often requires taking it offline so new hardware can be added to the servers. But the hardware would remain even when it came time to scale down.
Single node peer-to-peer architecture, however, allows for easy scalability. As new nodes are added to the database clusters, performance is increased. This scaleout architecture also adds more servers running replicas of the database. A simple click of the mouse can scale clusters up and down to meet demand.
B-Trees vs Log-Structured Merge Trees
B-tree data structures were created nearly 50 years ago to sort, search, insert and delete data in logarithmic time. The B-tree uses row-based storage that allows for low latency and high throughput. Many SQL databases use traditional B-tree architecture. A newer version of this data structure, known as a B+ tree, which puts all the data in leaf nodes, therefore supporting even greater fan-out. B+ trees also support ordered linked lists of data elements and data stored in RAM. B+ trees are used across many modern SQL and NoSQL systems.
Log-structured merge trees (also known as LSM trees) were created in the mid-1990s to meet the demand for larger datasets. The LSM tree has become the preferred way to manage fast-growing data because it is best suited for data with high write volume. LSM trees are commonly used in NoSQL databases.
LSM trees can write sequentially much faster than B-trees and even B+ trees. For this reason, B-trees are best for applications that don’t require high write throughput. LSM trees are designed for high write throughput, but they use more memory and CPU resources than B-trees. B+ trees may have better read performance than LSM trees.
Dense vs Sparse Data
Dense data refers to databases that require almost all fields of a database to be filled with data. Imagine a web form where most almost every element was a “required” field. In the database, there would be data for nearly every cell. .
Sparse data, on the other hand, refers to a database where there may be a very low percentage of fields where information is available. For example, imagine a list of all the jobs in the world. How many of those jobs have you personally held? If you could check two or even twelve or twenty jobs over your career, it would still leave most jobs blank for your record.
The benefit of sparse data is the ability to see large clusters of information that show clear answers in the midst of the empty cells. The uniqueness of sparse data makes it valuable for businesses that seek customer insights based on it.
The flood of dense data might flow faster, but it provides so much information that everything looks the same and it becomes impossible to see a meaningful trend.
For this reason, sparse data is better suited for NoSQL database solutions that put more value on analysis than speed.
How Does Scylla Fit In?
Scylla is a column-oriented NoSQL database that provides a dynamic schema for unstructured data. Scylla lets users add more columns and data types after initial creation of the table.
Scylla is a open source NoSQL database that uses the Cassandra Query Language (CQL), along with Scylla-specific extensions to CQL. It is similar to Structured Query Language (SQL) common in relational database management systems (RDBMS) in that it describes data organized into tables, by columns and rows. CQL differs from relational databases in that, though Scylla does support multiple tables, it does not support JOIN operations between its tables.
Instead of the B-tree format common in traditional RDBMS, Scylla uses a log-structured merge tree (LSM tree) storage engine that is more efficient for storing sparse data. This column-oriented data structure enables creation and management of wide rows, which is why Scylla can be classified as one of the graph databases or wide column stores.
Scylla can be used in conjunction with other SQL or NoSQL databases and become part of broader data ecosystems through integration with open source platforms like Apache Kafka and Apache Spark. Scylla Cloud is a fully managed NoSQL DBaaS offering that gives you access to fully managed Scylla clusters with automatic backup, repairs, performance optimization, security hardening, 24*7 maintenance and support. All for a fraction of the cost of other DBaaS providers.
|
__label__pos
| 0.772335 |
What is Control Unit : Components & Its Design
The control unit is the main component of a central processing unit (CPU) in computers that can direct the operations during the execution of a program by the processor/computer. The main function of the control unit is to fetch and execute instructions from the memory of a computer. It receives the input instruction/information from the user and converts it into control signals, which are then given to the CPU for further execution. It is included as a part of Von Neumann architecture developed by John Neumann. It is responsible for providing the timing signals, and control signals and directs the execution of a program by the CPU. It is included as an internal part of the CPU in modern computers. This article describes complete information about the control unit.
What is the Control Unit?
The component which receives the input signal/information/instruction from the user and converts into control signals for the execution in the CPU. It controls and directs the main memory, arithmetic & logic unit (ALU), input and output devices, and also responsible for the instructions that are sent to the CPU of a computer. It fetches the instructions from the main memory of a processor and sent to the processor instruction register, which contains register contents.
Control Unit Block Diagram
Control Unit Block Diagram
The control unit converts the input into control signals and then sent to the processor and directs the execution of a program. The operations that have to performed are directed by the processor on the computer. Mainly Central Processing Unit (CPU) and Graphical Processing Unit (GPU) require a control unit as the internal part. The block diagram of the control unit is shown above.
Components of a Control Unit
The components of this unit are instruction registers, control signals within the CPU, control signals to/from the bus, control bus, input flags, and clock signals.
The components of the Hardwired control unit are instruction register (contains opcode and address field), timing unit, control state generator, control signal generation matrix, and instruction decoder.
The components of the Micro programmed control unit are the next address generator, a control address register, control memory, and control data register.
Functions
The functions of the control unit include the following.
• It directs the flow of data sequence between the processor and other devices.
• It can interpret the instructions and controls the flow of data in the processor.
• It generates the sequence of control signals from the received instructions or commands from the instruction register.
• It has the responsibility to control the execution units such as ALU, data buffers, and registers in the CPU of a computer.
• It has the ability to fetch, decode, handle the execution, and store results.
• It cannot process and store the data
• To transfer the data, it communicates with the input and output devices and controls all the units of the computer.
Design of Control Unit
The design of this can be done using two types of a control unit which include the following.
• Hardwire based
• Microprogrammed based(single-level and two-level)
Hardwired Control Unit
The basic design of a hardwired control unit is shown above. In this type, the control signals are generated by a special hardware logic circuit without any change in the structure of the circuit. In this, the generated signal cannot be modified for execution in the processor.
The basic data of an opcode (operation code of an instruction is sent to the instruction decoder for decoding. The instruction decoder is the set of decoders to decode different types of data in the opcode. This results in output signals which contain values of active signals that are given as the input to the matrix generator to generate control signals for the execution of a program by the processor of the computer.
Hardwire based Control unit
Hardwire based Control unit
The matrix generator provides states of controls unit and the signals out from the processor (interrupt signals). Matrix is built as the programmable logic array. The control signals generated by the matrix generator are given as the input to the next generator matrix and combines with the timing signals of the timing unit that contains rectangular patterns.
For fetching of new instruction, the control unit turns into an initial stage for the execution of new instruction. The control unit remains in the initial stage or first stage as long as the timing signals, input signals, and states of instruction of a computer are unchanged. The change in the state of the control unit can be raised if there any change in any of the generated signals.
When an external signal or interrupt occurs, the control unit goes to the next state and performs the processing of the interrupt signal. The flags and states are used to select the desired states to perform the execution cycle of instruction.
In the last state, the control unit fetches the next instruction and sends the output to the program counter, then to the memory address register, to the buffer register, and then to the instruction register to read the instruction. Finally, if the last instruction (which is fetched by the control unit) is end instruction, then it goes to the operating state of the processor and waits until the user directs the next program.
Micro Programmed Control Unit
In this type, the control store is used to store the control signals which are encoded during the execution of a program. The control signal is not generated immediately and decoded because the microprogram stores address field in the control store. The whole process is a single level.
The micro-operations are done for the execution of micro-instructions in the program. The block diagram of the Micro programmed control unit is shown above. From the diagram, the address of the micro-instruction is obtained from the control memory address register. All the info of the control unit is permanently stored in the control memory called ROM.
Microprogrammed based Control Unit
Microprogrammed based Control Unit
The micro-instruction from the control memory is held by the control register. Since the micro-instruction is in the form of control word (contains binary control values) that needs 1 or more micro-operations to be performed for the data processing.
During the execution of micro-instructions, the next address generator computed the next address of the micro-instruction and then send to the control address register to read the next micro-instruction.
The sequence of micro-operations of a micro-program is performed by the next address generator and acts as microprogram sequencer to get the sequence address i.e., read from the control memory.
Verilog Code for the Control Unit
Verilog code for Control Unit is shown below.
`include “prj_definition.v”
module CONTROL_UNIT(MEM_DATA, RF_DATA_W, RF_ADDR_W, RF_ADDR_R1, RF_ADDR_R2, RF_READ, RF_WRITE, ALU_OP1, ALU_OP2, ALU_OPRN, MEM_ADDR, MEM_READ, MEM_WRITE, RF_DATA_R1, RF_DATA_R2, ALU_RESULT, ZERO, CLK, RST)
// Output signals
// Outputs for register file
output [`DATA_INDEX_LIMIT:0] RF_DATA_W;
output [`ADDRESS_INDEX_LIMIT:0] RF_ADDR_W, RF_ADDR_R1, RF_ADDR_R2;
output RF_READ, RF_WRITE;
// Outputs for ALU
output [`DATA_INDEX_LIMIT:0] ALU_OP1, ALU_OP2;
output [`ALU_OPRN_INDEX_LIMIT:0] ALU_OPRN;
// Outputs for memory
output [`ADDRESS_INDEX_LIMIT:0] MEM_ADDR;
output MEM_READ, MEM_WRITE;
// Input signals
input [`DATA_INDEX_LIMIT:0] RF_DATA_R1, RF_DATA_R2, ALU_RESULT;
input ZERO, CLK, RST;
// Inout signal
inout [`DATA_INDEX_LIMIT:0] MEM_DATA;
// State nets
wire [2:0] proc_state;
//holds program counter value, stores the current instruction, stack pointer register
reg MEM_READ, MEM_WRITE;
reg MEM_ADDR;
reg ALU_OP1, ALU_OP2;
reg ALU_OPRN;
reg RF_ADDR_W, RF_ADDR_R1, RF_ADDR_R2;
reg RF_DATA_W;
reg [1:0] state, next_state;
PROC_SM state_machine(.STATE(proc_state),.CLK(CLK),.RST(RST));
always @ (posedge CLK)
begin
if (RST)
state <= RST;
else
state <= next_state;
end
always @ (state)
begin
MEM_READ = 1’b0; MEM_WRITE = 1’b0; MEM_ADDR = 1’b0;
ALU_OP1 = 1’b0; ALU_OP2 = 1’b0; ALU_OPRN = 1’b0;
RF_ADDR_R1 = 1’b0; RF_ADDR_R2 = 1’b0; RF_ADDR_W = 1’b0; RF_DATA_W = 1’b0;
case( state )
`PROC_FETCH : begin
next_state = `PROC_DECODE;
MEM_READ = 1’b1;
RF_ADDR_R1 = 1’b0; RF_ADDR_R2 = 1’b0;
RF_ADDR_W = 1’b1;
end
`PROC_DECODE : begin
next_state = `PROC_EXE;
MEM_ADDR = 1’b1;
ALU_OP1 = 1’b1; ALU_OP2 = 1’b1; ALU_OPRN = 1’b1;
MEM_WRITE = 1’b1;
RF_ADDR_R1 = 1’b1; RF_ADDR_R2 = 1’b1;
end
`PROC_EXE : begin
next_state = `PROC_MEM;
ALU_OP1 = 1’b1; ALU_OP2 = 1’b1; ALU_OPRN = 1’b1;
RF_ADDR_R1 = 1’b0;
end
`PROC_MEM: begin
next_state = `PROC_WB;
MEM_READ = 1’b1; MEM_WRITE = 1’b0;
end
`PROC_WB: begin
next_state = `PROC_FETCH;
MEM_READ = 1’b1; MEM_WRITE = 1’b0;
end
endcase
end
endmodule;
module PROC_SM(STATE,CLK,RST);
// list of inputs
input CLK, RST;
// list of outputs
output [2:0] STATE;
// input list
input CLK, RST;
// output list
output STATE;
reg [2:0] STATE;
reg [1:0] state;
reg [1:0] next_state;
reg PC_REG, INST_REG, SP_REF;
`define PROC_FETCH 3’h0
`define PROC_DECODE 3’h1
`define PROC_EXE 3’h2
`define PROC_MEM 3’h3
`define PROC_WB 3’h4
// initiation of state
initial
begin
state = 2’bxx;
next_state = `PROC_FETCH;
end
// reset signal handling
always @ (posedge RST)
begin
state = `PROC_FETCH;
next_state = `PROC_FETCH;
end
always @ (posedge CLK)
begin
state = next_state;
end
always @(state)
begin
if (state === `PROC_FETCH)
begin
next_state = `PROC_DECODE;
print_instruction(INST_REG);
end
if (state === `PROC_DECODE)
begin
next_state = `PROC_EXE;
end
if (state === `PROC_EXE)
begin
next_state = `PROC_MEM;
print_instruction(SP_REF);
end
if (state === `PROC_MEM)
begin
next_state = `PROC_WB;
end
if (state === `PROC_WB)
begin
next_state = `PROC_FETCH;
print_instruction(PC_REG);
end
end
task print_instruction;
input [`DATA_INDEX_LIMIT:0] inst;
reg [5:0] opcode;
reg [4:0] rs;
reg [4:0] rt;
reg [4:0] rd;
reg [4:0] shamt; reg [5:0] funct; reg [15:0] immediate; reg [25:0] address;
begin
// parse the instruction
// R-type
{opcode, rs, rt, rd, shamt, funct} = inst;
// I-type
{opcode, rs, rt, immediate } = inst;
// J-type
{opcode, address} = inst;
$write(“@ %6dns -> [0X%08h] “, $time, inst);
case(opcode) // R-Type
6’h00 : begin
case(funct)
6’h20: $write(“add r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h22: $write(“sub r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h2c: $write(“mul r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h24: $write(“and r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h25: $write(“or r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h27: $write(“nor r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h2a: $write(“slt r[%02d], r[%02d], r[%02d];”, rs, rt, rd);
6’h00: $write(“sll r[%02d], %2d, r[%02d];”, rs, shamt, rd);
6’h02: $write(“srl r[%02d], 0X%02h, r[%02d];”, rs, shamt, rd);
6’h08: $write(“jr r[%02d];”, rs);
default: $write(“”);
endcase
end
// I-type
6’h08 : $write(“addi r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h1d : $write(“muli r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h0c : $write(“andi r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h0d : $write(“ori r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h0f : $write(“lui r[%02d], 0X%04h;”, rt, immediate);
6’h0a : $write(“slti r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h04 : $write(“beq r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h05 : $write(“bne r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h23 : $write(“lw r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
6’h2b : $write(“sw r[%02d], r[%02d], 0X%04h;”, rs, rt, immediate);
// J-Type
6’h02 : $write(“jmp 0X%07h;”, address);
6’h03 : $write(“jal 0X%07h;”, address);
6’h1b : $write(“push;”);
6’h1c : $write(“pop;”);
default: $write(“”);
endcase
$write (“\n”);
end
endtask
end module;
FAQs
1). What is the work of a control unit?
The work of the control unit is to direct the flow of data or instructions for the execution by the processor of a computer. It controls, manages and co-ordinates main memory, ALU, registers, input, and output units. It fetches the instructions and generates control signals for the execution.
2). What is the control memory?
Control memory is usually RAM or ROM to store the address and data of the control register.
3). What is the Wilkes control unit?
The sequential and combinational circuits of the hardwired control unit are replaced by the Wilkes control unit. It uses a storage unit to store the sequences of instructions of a micro-program.
4). What is a hardwired control unit?
The hardwired control unit generates the control signals by changing from one state to another state in every clock pulse without any physical change in the circuit. The generation of control signals depends on instructions register, decoder, and interrupt signals.
5). What is the control memory?
The information of the control unit or data is temporarily or permanently stored in the control memory.
Control memory is of two types. They are Random Access Memory(RAM) and Read-Only Memory(ROM).
Thus, this is all about the definition, components, design, diagram, functions, and types of Control Unit. Here is a question for you, “What is the purpose of the control address register?”
|
__label__pos
| 0.995516 |
Purchase Solution
Statistical Significance and Effect Size
Not what you're looking for?
Ask Custom Question
How does effect size impact statistical significance?
What is the importance of effect size in the statistical significance in research studies?
Purchase this Solution
Solution Summary
This solution is 263 words and a reference and shows with a very small data set how significance is easily to find with a large effect size.
Solution Preview
When you have a small sample, variations between data points can be just random variation. In order to be sure that the distance between data points is due to something other than chance, you need a certain number of data points. The number of data points needed to find a difference is related to the size of the difference (effect size).
For example, if you think your entire high school class has all gained weight, how many of that class would you ...
Solution provided by:
Education
• BSc, University of Virginia
• MSc, University of Virginia
• PhD, Georgia State University
Recent Feedback
• "hey just wanted to know if you used 0% for the risk free rate and if you didn't if you could adjust it please and thank you "
• "Thank, this is more clear to me now."
• "Awesome job! "
• "ty"
• "Great Analysis, thank you so much"
Purchase this Solution
Free BrainMass Quizzes
Measures of Central Tendency
Tests knowledge of the three main measures of central tendency, including some simple calculation questions.
Measures of Central Tendency
This quiz evaluates the students understanding of the measures of central tendency seen in statistics. This quiz is specifically designed to incorporate the measures of central tendency as they relate to psychological research.
Know Your Statistical Concepts
Each question is a choice-summary multiple choice question that presents you with a statistical concept and then 4 numbered statements. You must decide which (if any) of the numbered statements is/are true as they relate to the statistical concept.
Terms and Definitions for Statistics
This quiz covers basic terms and definitions of statistics.
|
__label__pos
| 0.840911 |
The Octave Developer Hub
Welcome to the Octave developer hub. You'll find comprehensive guides and documentation to help you start working with Octave as quickly as possible, as well as support if you get stuck. Let's jump right in!
Get Started
Setting a Value From a REST API Call
This topic describes how to set a value on an Octave edge device from an external entity using the Octave REST API.
The Octave REST API allows you to programmatically set Actuator values on an Octave edge device from any device with an internet connection.
Here are the main options available with the Octave REST API for changing Resources on the edge:
The following subsections use the example of setting the LCD value on the LCD screen included with the mangOH Red, to illustrate the two methods for setting a value.
Permanently Changing a Value via the Device State
You can set a value by invoking the Update a Device endpoint of the Octave REST API. Follow the steps to invoke this endpoint using cURL, to set the text on the mangOH Red's LCD screen:
1. Open a browser and log in to the Octave Dashboard.
2. Locate your username and master token on the user screen in the Octave Dashboard.
3. Copy the username and master token. You must provide these in the X-Auth-User and X-Auth-Token headers respectively, when invoking the endpoint.
4. Navigate to Build > Device > Details and copy the ID value. This is the unique ID of your mangOH Red that must be included as a path parameter for the REST API call.
5. (Recommended) In a command-line window, invoke the GET /device/<device_identifier> endpoint to obtain the full state object for the device. You will need to send a full state object in the next step. See the warning below.
❗️
Warning: You Must Provide the Full Device State Object
When setting a value (performed in Step 6 below) you must supply the full object to update even a single compound attribute (i.e., a single attribute inside the "state" object). If you only supply a partial state object (i.e., only the attribute(s) that you want to update), then the state object will be updated to contain only the attribute(s) you provide.
Therefore it's recommended that you first invoke the GET /device/<device_identifier> endpoint as suggested in Step 6, to obtain the full state object and then use that as the base object on which modify, add, and/or remove the attributes of the state object that you will send.
1. In a command line window enter the following, replacing the items surrounded by "<" and ">" with the required values:
curl -X PUT https://octave-api.sierrawireless.io/v5.0/<your company name>/device/<your device ID> \
-H "X-Auth-User: <your user name>" \
-H "X-Auth-Token: <your user token>" \
-d '{
"state": {
"/lcd/txt1" : "<some text>",
"/util/cellular/signal/period": 30,
"/cloudInterface/developer_mode/enable": true,
"/cloudInterface/store_forward/period": 60,
"/util/cellular/signal/enable": true
}
}'
After the endpoint executes, the first line of the LCD screen should update with the value specified for /lcd/txt1 in the state body parameter.
The status field in the response indicates if the request was successful, and the body contains the entire updated state of the device:
{
"head":{
"status":200,
"ok":true,
"messages":[
],
"errors":[
],
"references":{
}
},
"body":{
"id":"d5c7...",
"avSystemId":"a1c0...",
"blueprintId":{
"id":"b5d2...",
"version":2
},
"broadcastDate":1568834780509,
...
}
}
For more information, see the Device object REST API page.
Temporarily Changing a Value via an Event
You can change a value of one or several Resources on a device by calling the Creating an Event endpoint of the Octave REST API. The Event will have to be sent to the :command stream of the device.
Follow the steps below to invoke this endpoint using cURL to set the text on the mangOH Red's LCD screen.
Gathering the Auth Token and User
1. Open a browser and log in to the Octave Dashboard.
2. Locate your username and master token on the user screen in the Octave Dashboard.
3. Copy the username and master token. You must provide these in the X-Auth-User and X-Auth-Token headers respectively, when invoking the endpoint.
Changing the Value
Choose one of the following methods to send an Event.
Method 1 - POSTing to the Command Stream Directly
Follow the steps below to POST directly the device's Command Stream. This is the more commonly used method because you only need to know the path/endpoint of the device to POST to its Command Stream:
1. Open a command-line window and enter the following, replacing the items surrounded by "<" and ">" with the required values:
curl -X "POST" "https://octave-api.sierrawireless.io/v5.0/<your company name>/event" \
-H "X-Auth-User: <your user name>" \
-H "X-Auth-Token: <your user token>" \
-H 'Content-Type: text/plain; charset=utf-8' \
-d $'{
"path" : "/company_name/devices/device_name/:command",
"elems" : { "/lcd/txt1": "Pong" }
}'
Method 2 - POSTing to the Command Stream Using its Stream ID
Follow the steps below to identify the ID of the device's :command Stream and to POST an Event directly to that Stream. Note that this method is less commonly used than Method 1 because it requires you to know/identify the ID of the device's Command Stream:
1. Navigate to Build > Device > Streams and locate the :command stream.
2. Select the `:command Stream.
3. Copy the unique identifier of the Stream for the url: this is the unique ID of the :command Stream of your device that must be included as a path parameter for the REST API call.
1. Open a command-line window and enter the following, replacing the items surrounded by "<" and ">" with the required values:
curl -X POST https://octave-api.sierrawireless.io/v5.0/<your company name>/event/<your stream id> \
-H "X-Auth-User: <your user name>" \
-H "X-Auth-Token: <your user token>" \
-d '{
"elems": { "/lcd/txt1": "Pong" }
}'
Verifying the Result
After the endpoint executes, the first line of the LCD screen should update with the value specified in the Event. You should also see that the Event was added to the :command Stream of your device.
Like in previous example, you can know if the command has been processed on the device and if there was some error, looking for COMMAND_START / COMMAND_COMPLETE or COMMAND_FAULT in the :inbox Stream of your device; they also appear in the Recent changes widget of the Device details screen.
📘
Resource Path
Most of the time you will need to change the sub resource value of a Resource, in this case you add value to the Resource path: /app/NAME/value.
Example of event to send in order to update a virtual resource named lightThreshold :
{
"elems": {
"virtual/lightThreshold/value": 1200
}
}
It is possible to add a timeout or ttl: time to live parameter to the Event you are sending to the :command Stream of a device. When this parameter is set, Octave will attempt to deliver the command to the device until it succeeds, or the timeout is exceeded. Timeout and TTL are defined as optional attributes of the event metadata field, parameter is milliseconds.
In the example below the command will timeout after 1 minute:
curl -X POST https://octave-api.sierrawireless.io/v5.0/<your company name>/event/<your stream id> \
-H "X-Auth-User: <your user name>" \
-H "X-Auth-Token: <your user token>" \
-d '{
"elems": { "/lcd/txt1": "Pong" },
"metadata": { "ttl": 60000 } \
}'
Updated 3 months ago
Setting a Value From a REST API Call
This topic describes how to set a value on an Octave edge device from an external entity using the Octave REST API.
Suggested Edits are limited on API Reference Pages
You can only suggest edits to Markdown body content, but not to the API spec.
|
__label__pos
| 0.911307 |
Debian
Cara membuat dan menjalankan skrip Perl di Debian 10
Cara membuat dan menjalankan skrip Perl di Debian 10
Pengenalan:
Skrip Perl adalah kaedah lain yang kuat untuk melaksanakan program yang kompleks dengan usaha yang sangat minimum. Orang yang mempunyai pengetahuan yang baik tentang pengaturcaraan dalam C dan C ++ bergaul dengan Perl dengan sangat baik kerana kemiripannya dengan bahasa-bahasa ini. Dalam artikel ini, kami akan mengajar anda kaedah membuat skrip Perl pertama anda dan menjalankannya dalam Debian 10.
Kaedah Membuat Skrip Perl dalam Debian 10:
Untuk membuat skrip Perl sederhana di Debian 10, ada tiga langkah utama yang perlu anda ikuti:
Langkah # 1: Memeriksa Versi Perl:
Anda harus memastikan bahawa anda telah memasang Perl pada sistem Debian 10 anda. Anda boleh melakukannya hanya dengan memeriksa versi Perl dengan menjalankan perintah berikut di terminal anda:
perl - penukaran
Sekiranya Perl sudah dipasang pada sistem anda, maka menjalankan perintah yang disebutkan di atas akan menjadikan versi Perl yang dipasang pada sistem Debian 10 anda seperti yang ditunjukkan dalam gambar di bawah:
Langkah # 2: Memastikan Kehadiran Pentafsir Perl:
Oleh kerana setiap bahasa skrip memerlukan jurubahasa yang dapat membantu dalam pelaksanaan program yang dibuat dalam bahasa itu, oleh itu, anda juga perlu memastikan bahawa jurubahasa Perl telah dipasang pada sistem anda atau tidak. Anda boleh memeriksanya dengan menjalankan perintah berikut di terminal anda:
perl yang mana
Menjalankan perintah ini akan menunjukkan jalan ke binari Perl seperti yang ditunjukkan dalam gambar di bawah:
Walau bagaimanapun, jika anda juga ingin memeriksa jalur fail sumber dan halaman manual Perl bersama dengan fail binari untuk jaminan tambahan, maka anda boleh menjalankan perintah berikut di terminal anda:
mana perl
Keluaran arahan "Whereis" ditunjukkan dalam gambar di bawah:
Langkah # 3: Membuat Skrip Perl di Debian 10:
Setelah anda memastikan kehadiran Perl dan jurubahasa masing-masing pada sistem Debian 10 anda, tiba giliran membuat skrip Perl. Skrip Perl dapat dibuat dengan mudah dengan melaksanakan perintah berikut di terminal anda:
sudo nano MyFirstPerlScript.pl
Penyunting teks lain juga dapat digunakan untuk melayani tujuan yang sama dan bukan penyunting nano, namun, kami telah menggunakan editor ini semata-mata kerana ia adalah penyunting teks lalai sistem Linux. Selain itu, anda boleh mempunyai nama untuk skrip Perl anda yang mesti diikuti oleh a .peluasan pl.
Apabila anda menjalankan perintah ini, fail skrip Perl kosong akan dibuka dengan penyunting nano. Anda hanya perlu mengetik skrip berikut dalam fail anda. Baris pertama skrip ini adalah “#!/ bin / perl ”yang ada untuk menyatakan secara jelas bahawa skrip berikut adalah skrip Perl. Kemudian kita hanya mencetak pesanan palsu dengan menggunakan perintah "cetak". Setelah mengetik skrip Perl ini dalam fail anda, anda harus menyimpannya dan keluar dari editor dengan menekan Ctrl + X.
Kaedah Menjalankan Skrip Perl dalam Debian 10:
Anda boleh menjalankan skrip Perl dengan menggunakan salah satu daripada dua kaedah yang disenaraikan di bawah:
Kaedah # 1: Menggunakan Perintah "chmod" untuk Menetapkan Pelaksanaan Kebenaran:
Untuk kaedah ini, pertama-tama anda harus menetapkan kebenaran pelaksanaan untuk skrip Perl anda dan selepas itu anda akhirnya dapat menjalankannya. Perincian kedua-dua langkah ini disenaraikan di bawah:
Langkah # 1: Menetapkan Izin Jalankan:
Anda harus membuat skrip Perl yang baru anda buat, dapat dilaksanakan dengan menjalankan perintah berikut di terminal anda:
sudo chmod + x MyFirstPearlScript.pl
Langkah # 2: Menjalankan Skrip Perl:
Setelah membuat skrip Perl anda dapat dilaksanakan, anda boleh menjalankannya dengan menjalankan perintah berikut di terminal anda:
./ MyFirstPerlScript.pl
Menjalankan skrip ini akan menunjukkan outputnya pada terminal seperti yang ditunjukkan dalam gambar di bawah:
Kaedah # 2: Menggunakan Perintah "perl":
Kaedah ini adalah penyelesaian yang lebih mudah untuk menjalankan skrip Perl di Debian 10. Ini kerana ia tidak memerlukan anda untuk menetapkan kebenaran pelaksanaan sebaliknya anda boleh menjalankan skrip Perl anda secara langsung.
Anda boleh menjalankan skrip Perl anda dengan menjalankan perintah berikut di terminal anda:
perl MyFirstPerlScript.pl
Menjalankan skrip ini akan menunjukkan outputnya pada terminal seperti yang ditunjukkan dalam gambar di bawah:
Kesimpulan:
Dengan mengikuti prosedur membuat dan menjalankan skrip Perl yang dijelaskan dalam artikel ini, anda dapat membuat hidup anda lebih mudah dengan mengotomatisasi tugas yang biasa anda lakukan dengan bantuan skrip Perl. Artikel ini hanya mengajar anda kaedah asas untuk membuat dan menjalankan skrip Perl sederhana. Sebaik sahaja anda berjaya mengetahui ini, anda boleh menggunakan skrip Perl untuk banyak masalah lain yang dapat diprogramkan secara kompleks.
Tutorial Battle for Wesnoth
The Battle for Wesnoth adalah salah satu permainan strategi sumber terbuka paling popular yang boleh anda mainkan pada masa ini. Bukan hanya permainan...
0 A.D. Tutorial
Daripada banyak permainan strategi di luar sana, 0 A.D. berjaya menonjol sebagai tajuk yang komprehensif dan permainan taktikal yang sangat mendalam w...
Tutorial Unity3D
Pengenalan Unity 3D Unity 3D adalah enjin pengembangan permainan yang kuat. Ini adalah platform silang yang memungkinkan anda membuat permainan untuk ...
|
__label__pos
| 0.991521 |
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up
Join the Stack Overflow community to:
1. Ask programming questions
2. Answer and help your peers
3. Get recognized for your expertise
I've come up against a weird problem: The WCF web service I'm building runs in debug mode but not in release.
I've got a simple Hello web method in the web service that just returns a string and does nothing else (no logging, exception handling, nothing). I run the WCFTestClient from within Visual Studio by selecting the .svc file and clicking F5 to start debugging. When the WCFTestClient is open I double-click on the Hello web method and Invoke it. In Debug mode it runs fine. In Release mode almost instantly I get the following error:
Object reference not set to an instance of an object.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IVehicleRisk.Hello()
at VehicleRiskClient.Hello()
(the web service is VehicleRisk.svc and the service contract is IVehicleRisk).
Adding breakpoints to the application I can see when I invoke the Hello web method the Application_BeginRequest method in Global.asax.cs is being called (it's an empty method). When the exception is thrown no breakpoints in VehicleRisk.svc.cs are being hit, in either the constructor or the Hello method (when the web method works, the breakpoints are being hit).
I looked at the project build properties in Visual Studio (right click on the project in Solution Explorer, select Properties, open the Build tab in the Properties window). The only difference I can see between Debug and Release modes are:
1. Define DEBUG constant: Set on in Debug mode, off in Release;
2. Optimize code: Set off in Debug mode, on in Release;
3. Advanced > Output Debug Info: Set to full in Debug mode, pdb-only in Release.
Experimenting with changing the Build properties in Release mode, I found that I can get the web method to work only when Optimize code is set off and Advanced > Output Debug Info is set to full. Setting the DEBUG constant on or off makes no difference.
Does anyone have any idea why a simple web method would fail when code optimization is turned on, or when debug info is set to pcb-only?
share|improve this question
sure optimization can sometimes be tricky - how is Hello() implemented - and details of ServiceBehavior attribute on the service? – YK1 May 22 '13 at 23:09
@YK1: You're right, optimization turned out to be very tricky in this case. The problem was in a helper class instantiated in the constructor of the web service class, not in the Hello method itself. See my answer for details. Cheers, Simon. – Simon Tewsi May 23 '13 at 3:17
up vote 2 down vote accepted
It turns out the problem wasn't to do with WCF per se.
I was calling a simple Hello method in the service class but the constructor of that class was setting up logging (although I wasn't actually using the logging in the Hello method). The logging helper class that was being instantiated in the service class constructor had a method GetCallingMethodName. This method walks up through the stack trace to determine the names of the class and method logging a message, to include the names in the log message.
The key to the problem was that GetCallingMethodName skipped the first method call in the stack trace, which would normally be the GetCallingMethodName method itself. The 64-bit JIT compiler on the web server must have been inlining the method, so there was no second stack frame in the stack trace. Attempting to skip the first frame in the stack trace was therefore causing an error.
The solution was to start walking the stack trace from the first stack frame instead of the second.
This problem didn't appear when the web service was deployed to the server in Debug mode as the compiler optimizations were turned off, so the compiler couldn't inline the method. Nor did it appear on my development PC in Release mode as the 32-bit JIT compiler must have been optimizing the code differently from the 64-bit compiler on the server.
share|improve this answer
Without seeing your code it's hard to say what might be going wrong.
To recreate an example project that does work, I created a WCF Service Application with the following service interface:
using System.ServiceModel;
namespace HelloWCF
{
[ServiceContract]
public interface IHelloService
{
[OperationContract]
string SayHello(string name);
}
}
I then implemented this interface with the following class:
namespace HelloWCF
{
public class HelloService : IHelloService
{
public string SayHello(string name)
{
return string.Format("Hello, {0}", name);
}
}
}
I also added the following services config to the <system.servicemodel> section of web.config:
<services>
<service name="HelloWCF.HelloService"
behaviorConfiguration="SimpleBehavior">
<endpoint
binding="basicHttpBinding"
contract="HelloWCF.IHelloService" />
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
I also named the service behavior:
<behaviors>
<serviceBehaviors>
<behavior name="SimpleBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
I build and ran the service in both debug and release mode using the WCF Test Client and it worked as expected: WCF Test Client
I also was able to ping the service using IE (http://localhost:<port-number)/HelloService.svc) and was able to see the service info page and access its MEX.
HTH.
share|improve this answer
It turned out the problem had nothing to do with WCF (see my answer for details) but I think your answer may be useful to other beginners wanting to create a simple WCF service. So +1. Cheers, Simon. – Simon Tewsi May 23 '13 at 3:15
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.68705 |
++ed by:
DJO NEBULOUS ZURBORG DBOEHMER EMAZEP
138 PAUSE users
93 non-PAUSE users.
Karen Etheridge ಠ_ಠ 🌋
and 122 contributors
NAME
Moose::Spec::Role - Formal spec for Role behavior
VERSION
version 2.1404
DESCRIPTION
NOTE: This document is currently incomplete.
Components of a Role
Excluded Roles
A role can have a list of excluded roles, these are basically roles that they shouldn't be composed with. This is not just direct composition either, but also "inherited" composition.
This feature was taken from the Fortress language and is really of most use when building a large set of role "building blocks" some of which should never be used together.
Attributes
A roles attributes are similar to those of a class, except that they are not actually applied. This means that methods that are generated by an attributes accessor will not be generated in the role, but only created once the role is applied to a class.
Methods
These are the methods defined within the role. Simple as that.
Required Methods
A role can require a consuming class (or role) to provide a given method. Failure to do so for classes is a fatal error, while for roles it simply passes on the method requirement to the consuming role.
Required Attributes
Just as a role can require methods, it can also require attributes. The requirement fulfilling attribute must implement at least as much as is required. That means, for instance, that if the role requires that the attribute be read-only, then it must at least have a reader and can also have a writer. It means that if the role requires that the attribute be an ArrayRef, then it must either be an ArrayRef or a subtype of an ArrayRef.
Overridden Methods
The override and super keywords are allowed in roles, but their behavior is different from that of its class counterparts. The super in a class refers directly to that class's superclass, while the super in a role is deferred and only has meaning once the role is composed into a class. Once that composition occurs, super then refers to that class's superclass.
It is key to remember that roles do not have hierarchy, so they can never have a super role.
Method Modifiers
These are the before, around and after modifiers provided in Moose classes. The difference here is that the modifiers are not actually applied until the role is composed into a class (this is just like attributes and the override keyword).
Role Composition
Composing into a Class
Excluded Roles
Required Methods
Required Attributes
Attributes
Methods
Overridden methods
Method Modifiers (before, around, after)
Composing into a Instance
Composing into a Role
Excluded Roles
Required Methods
Required Attributes
Attributes
Methods
Overridden methods
Method Modifiers (before, around, after)
Role Summation
When multiple roles are added to another role (using the with @roles keyword) the roles are composed symmetrically. The product of the composition is a composite role (Moose::Meta::Role::Composite).
Excluded Roles
Required Methods
Required Attributes
Attributes
Attributes with the same name will conflict and are considered a unrecoverable error. No other aspect of the attribute is examined, it is enough that just the attribute names conflict.
The reason for such early and harsh conflicts with attributes is because there is so much room for variance between two attributes that the problem quickly explodes and rules get very complex. It is my opinion that this complexity is not worth the trouble.
Methods
Methods with the same name will conflict, but no error is thrown, instead the method name is added to the list of required methods for the new composite role.
To look at this in terms of set theory, each role can be said to have a set of methods. The symmetric difference of these two sets is the new set of methods for the composite role, while the intersection of these two sets are the conflicts. This can be illustrated like so:
Role A has method set { a, b, c }
Role B has method set { c, d, e }
The composite role (A,B) has
method set { a, b, d, e }
conflict set { c }
Overridden methods
An overridden method can conflict in one of two ways.
The first way is with another overridden method of the same name, and this is considered an unrecoverable error. This is an obvious error since you cannot override a method twice in the same class.
The second way for conflict is for an overridden method and a regular method to have the same name. This is also an unrecoverable error since there is no way to combine these two, nor is it okay for both items to be composed into a single class at some point.
The use of override in roles can be tricky, but if used carefully they can be a very powerful tool.
Method Modifiers (before, around, after)
Method modifiers are the only place where the ordering of role composition matters. This is due to the nature of method modifiers themselves.
Since a method can have multiple method modifiers, these are just collected in order to be later applied to the class in that same order.
In general, great care should be taken in using method modifiers in roles. The order sensitivity can possibly lead to subtle and difficult to find bugs if they are overused. As with all good things in life, moderation is the key.
Composition Edge Cases
This is a just a set of complex edge cases which can easily get confused. This attempts to clarify those cases and provide an explanation of what is going on in them.
Role Method Overriding
Many people want to "override" methods in roles they are consuming. This works fine for classes, since the local class method is favored over the role method. However in roles it is trickier, this is because conflicts result in neither method being chosen and the method being "required" instead.
Here is an example of this (incorrect) type of overriding.
package Role::Foo;
use Moose::Role;
sub foo { ... }
package Role::FooBar;
use Moose::Role;
with 'Role::Foo';
sub foo { ... }
sub bar { ... }
Here the foo methods conflict and the Role::FooBar now requires a class or role consuming it to implement foo. This is very often not what the user wants.
Now here is an example of the (correct) type of overriding, only it is not overriding at all, as is explained in the text below.
package Role::Foo;
use Moose::Role;
sub foo { ... }
package Role::Bar;
use Moose::Role;
sub foo { ... }
sub bar { ... }
package Role::FooBar;
use Moose::Role;
with 'Role::Foo', 'Role::Bar';
sub foo { ... }
This works because the combination of Role::Foo and Role::Bar produce a conflict with the foo method. This conflict results in the composite role (that was created by the combination of Role::Foo and Role::Bar using the with keyword) having a method requirement of foo. The Role::FooBar then fulfills this requirement.
It is important to note that Role::FooBar is simply fulfilling the required foo method, and **NOT** overriding foo. This is an important distinction to make.
Now here is another example of a (correct) type of overriding, this time using the excludes option.
package Role::Foo;
use Moose::Role;
sub foo { ... }
package Role::FooBar;
use Moose::Role;
with 'Role::Foo' => { -excludes => 'foo' };
sub foo { ... }
sub bar { ... }
By specifically excluding the foo method during composition, we allow Role::FooBar to define its own version of foo.
SEE ALSO
Traits
Roles are based on Traits, which originated in the Smalltalk community.
http://www.iam.unibe.ch/~scg/Research/Traits/
This is the main site for the original Traits papers.
Class::Trait
I created this implementation of traits several years ago, after reading the papers linked above. (This module is now maintained by Ovid and I am no longer involved with it).
Roles
Since they are relatively new, and the Moose implementation is probably the most mature out there, roles don't have much to link to. However, here is some bits worth looking at (mostly related to Perl 6)
http://www.oreillynet.com/onlamp/blog/2006/08/roles_composable_units_of_obje.html
This is chromatic's take on roles, which is worth reading since he was/is one of the big proponents of them.
http://svn.perl.org/perl6/doc/trunk/design/syn/S12.pod
This is Synopsis 12, which is all about the Perl 6 Object System. Which, of course, includes roles.
AUTHORS
• Stevan Little <[email protected]>
• Dave Rolsky <[email protected]>
• Jesse Luehrs <[email protected]>
• Shawn M Moore <[email protected]>
• יובל קוג'מן (Yuval Kogman) <[email protected]>
• Karen Etheridge <[email protected]>
• Florian Ragwitz <[email protected]>
• Hans Dieter Pearcey <[email protected]>
• Chris Prather <[email protected]>
• Matt S Trout <[email protected]>
COPYRIGHT AND LICENSE
This software is copyright (c) 2006 by Infinity Interactive, Inc..
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
|
__label__pos
| 0.538385 |
Combinatorial number - examples - page 3
1. Class pairs
pair_1 In a class of 34 students, including 14 boys and 20 girls. How many couples (heterosexual, boy-girl) we can create? By what formula?
2. Cards
cards_4 The player gets 8 cards of 32. What is the probability that it gets a) all 4 aces b) at least 1 ace
3. Sum or product
dice_6 What is the probability that two dice fall will have the sum 7 or product 12?
4. Combinations of sweaters
sveter I have 4 sweaters two are white, 1 red and 1 green. How many ways can this done?
5. The confectionery
ice_cream The confectionery sold 5 kinds of ice cream. In how many ways can I buy 3 kinds if order of ice creams does not matter?
6. Disco
vencek On the disco goes 12 boys and 15 girls. In how many ways can we select four dancing couples?
7. Roses 2
ruze Aunt Rose went to the flower shop to buy a bouquet with three roses. The flower shop had white, yellow and red roses. How many different flowers bouquet can a flower make for Aunt Rose create? Write all the bouquet options.
8. Cards
cards_8 From a set of 32 cards we randomly pull out three cards. What is the probability that it will be seven king and ace?
9. VCP equation
combinatorics3 Solve the following equation with variations, combinations and permutations: 4 V(2,x)-3 C(2,x+ 1) - x P(2) = 0
10. Balls
spheres_1 The urn is 8 white and 6 black balls. We pull 4 randomly balls. What is the probability that among them will be two white?
11. Ice cream
zmrzlina Annie likes much ice cream. In the shop are six kinds of ice cream. In how many ways she can buy ice cream to three scoop if each have a different flavor mound and the order of scoops doesn't matter?
12. Hockey match
football_2 The hockey match ended with result 3:1. How many different storylines may have the match?
13. First class
prvni_jakost The shipment contains 40 items. 36 are first grade, 4 are defective. How many ways can select 5 items, so that it is no more than one defective?
14. Combinations
math_2 From how many elements we can create 990 combinations 2nd class without repeating?
15. Volleyball
volejbal 8 girls wants to play volleyball against boys. On the field at one time can be six players per team. How many initial teams of this girls may trainer to choose?
16. Division
skauti_3 Division has 18 members: 10 girls and 6 boys, 2 leaders. How many different patrols can be created, if one patrol is 2 boys, 3 girls and 1 leader?
17. Two aces
cards_7 From a 32 card box we randomly pick 1 card and then 2 more cards. What is the probability that last two drawn cards are aces?
18. Prize
metals_1 How many ways can be rewarded 9 participants with the first, second and third prize in a sports competition?
19. Competition
sutaz 15 boys and 10 girls are in the class. On school competition of them is selected 6-member team composed of 4 boys and 2 girls. How many ways can we select students?
20. Combinations
kvadrat_3 If the number of elements increase by 3, it increases the number of combinations of the second class of these elements 5 times. How many are the elements?
Do you have an interesting mathematical example that you can't solve it? Enter it, and we can try to solve it.
To this e-mail address, we will reply solution; solved examples are also published here. Please enter e-mail correctly and check whether you don't have a full mailbox.
See also our combinations calculator.
|
__label__pos
| 0.970029 |
camera
RMIT University
VPS – digital non-public server is without doubt one of the most revolutionary applied sciences accessible in the present day in the case of computing. Bain works with leading technology companies to construct strategic plans that address the industry’s challenges, such as how technical and enterprise mannequin improvements shape the growth of an organization’s core enterprise; the ways in which cloud computing will impact the enterprise; and whether a company ought to consider entry into the companies profit pools of the business—and if so, how.
In addition, technology ensures readability, in both audio and visual systems, thus one can have the benefit of every space of communication. They understood that a lifetime spent taking part in with what others considered as toys and mindless devices would finally result in indispensable technology.
Distraction in the classroom: College students love to make use of technology in the classroom, but it surely tends to distract them, for example, the usage of cellphones to study within the classroom, distracts some college students. Examples include Google’s AutoML , DataRobot and the H2O AutoML interface Though we have seen promising results from these instruments, we might caution businesses towards viewing them as the sum total of their machine-learning journey.
The invention of the telephone and radio companies has broadened human communication. Compared to standard units and equipment, future technology news states that ultramodern devices are more workable and highly effective of their performance. When combined with another term, corresponding to “medical technology” or “space technology,” it refers to the state of the respective subject’s knowledge and instruments.
Future technology will bring a lot more innovations and equipment to upgrade human lifestyles. Technology is a phrase used to collectively describe or portray the advancements, skills,creations, undertakings, views, and data of a singular group of individuals: we as human-sort.
|
__label__pos
| 0.91656 |
Surprising polymorphism in React applications
Benedikt Meurer
Mar 14, 2017 · 3 min read
Modern web applications based on the React framework usually manage their state via immutable data structures, i.e. using the popular Redux state container. This pattern has a couple of benefits and is becoming ever more popular even outside the React/Redux world.
The core of this mechanism are so-called reducers. Those are functions that map one state of the application to the next one according to a specific action — i.e. in response to user interaction. Using this core abstraction, complex state and reducers can be composed of simpler ones, which makes it easy to unit test the code in separation. Consider the following example from the Redux documentation:
The todo reducer maps an existing state to a new state in response to a given action. The state is represented as plain old JavaScript object. Looking at this code from a performance perspective, it seems to follow the principles for monomorphic code, i.e. keeping the object shape the same.
Speaking naively the property accesses in render should be monomorphic, i.e. the state objects should have the same shape — map or hidden class in V8 speak — all the time, both s1 and s2 have id, text and completed properties in this order. However, running this code in the d8 shell and tracing the ICs (inline caches), we observe that render sees different object shapes and the state.id and state.text property accesses become polymorphic:
Image for post
Image for post
So where does this polymorphism comes from? It’s actually pretty subtle and has to do with the way V8 handles object literals. Each object literal — i.e. expression of the form {a:va,...,z:vb} defines a root map in the transition tree of maps (remember map is V8 speak for object shape). So if you use an empty object literal {} than the transition tree root is a map that doesn’t contain any properties, whereas if you use {id:id, text:text, completed:completed} object literal, then the transition tree root is a map that contains these three properties. Let’s look at a simplified example:
You can run this code in Node.js passing the --allow-natives-syntax command line flag (which enables the use of the %HaveSameMap intrinsic), i.e.:
Image for post
Image for post
So despite these objects a and b looking the same — having the same properties with the same types in the same order — they don’t have the same map. The reason being that they have different transition trees, as illustrated by the following diagram:
Image for post
Image for post
So polymorphism hides where objects are allocated via different (incompatible) object literals. This especially applies to common uses of Object.assign, for example
still yields different maps, because the object b starts out as empty object (the {} literal) and Object.assign just slaps properties on it.
Image for post
Image for post
This also applies if you use spread properties and transpile it using Babel, because Babel — and probably other transpilers as well — use Object.assign for spread properties.
Image for post
Image for post
One way to avoid this is to consistently use Object.assign so that all objects start from the empty object literal. But this can become a performance bottleneck in the state management logic:
That being said, it’s not the end of the world if some code becomes polymorphic. Staying monomorphic might not matter at all for most of your code. You should measure really carefully before making the decision to optimize the wrong thing.
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade
Get the Medium app
A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
|
__label__pos
| 0.540511 |
R/waveletTransform.R
Defines functions WaveletTransform_2D WaveletTransform
Documented in WaveletTransform WaveletTransform_2D
#' Perform a 1D wavelet transform on a FAIMS data matrix
#'
#' @param FAIMSObject a FAIMS object
#' @param discardTopLevels number of levels to discard as noise (0 keeps all
#' data)
#'
#' @return a matrix of wavelet-transformed FAIMS data
#' @export
#'
#' @importFrom wavethresh wd accessD
WaveletTransform <- function(FAIMSObject, discardTopLevels=2){
if (!inherits(FAIMSObject, "FAIMS")) stop("FAIMSObject must inherit class FAIMS")
dataMatrix <- FAIMSObject$data
faimsDim <- FAIMSObject$faimsDim
##----------------------------------------------------------------------
## FIND USEFUL VALUES --------------------------------------------------
##----------------------------------------------------------------------
nDataItems = nrow(dataMatrix)
nFeatures = ncol(dataMatrix)
numRows = faimsDim[1]
numCols = nFeatures / faimsDim[1]
nWavelets = 2^(ceiling(log2(numRows)) - discardTopLevels)
data.wd = matrix(0, nDataItems, nWavelets * numCols)
row.names(data.wd) = row.names(dataMatrix)
##----------------------------------------------------------------------
## GENERATE THE WAVELET TRANSFORMED DATA -------------------------------
##----------------------------------------------------------------------
pb <- progBarInit(c(0, nDataItems * numCols))
count <- 0
for (i in 1:nDataItems){
waveColIndex <- 1
for (j in 1:numCols) {
count <- count + 1
pb <- progBarUpdate(pb, count)
colIndex = 1:numRows + (j - 1) * numRows
currentData = dataMatrix[i, colIndex]
working = numeric(2^(ceiling(log2(numRows))))
working[1:numRows] = currentData
current.wd = wd(working, filter.number=1, bc="symmetric", family = "DaubExPhase")
for (k in 0:(current.wd$nlevels - 1 - discardTopLevels)) {
data.wd[i, waveColIndex:(waveColIndex + 2^k - 1)] <- accessD(current.wd, k)
waveColIndex <- waveColIndex + 2^k
}
}
}
##----------------------------------------------------------------------
## REMOVE ANY ZERO-VARIANCE FEATURES -----------------------------------
##----------------------------------------------------------------------
sigmaValues = apply(data.wd, 2, sd)
keep = which(sigmaValues>0)
data.wd = data.wd[, keep]
attr(data.wd, "keptColumns") <- keep
return(data.wd)
}
#' Perform a 2D wavelet transform on a FAIMS data matrix
#'
#' This function expects an input matrix of dimension (nDataItems * nFeatures)
#' each row is therefore the 1D representation of the 2D data for a single item
#' This means that this function needs to know the underlying dimensionality of
#' the 2D FAIMS run
#'
#' @param FAIMSObject A FAIMS object
#' @param cropSize size to crop image to
#' @param discardHighestNLevels number of levels to discard as noise
#'
#' @return A matrix of wavelet-transformed FAIMS data
#' @export
#'
#' @importFrom wavethresh imwd lt.to.name
WaveletTransform_2D <- function(FAIMSObject, cropSize=NULL, discardHighestNLevels=2){
if (!inherits(FAIMSObject, "FAIMS")) stop("FAIMSObject must inherit class FAIMS")
dataMatrix <- FAIMSObject$data
faimsDim <- FAIMSObject$faimsDim
##----------------------------------------------------------------------
## FIND USEFUL VALUES --------------------------------------------------
##----------------------------------------------------------------------
dataMatrix <- as.matrix(dataMatrix)
nDataItems <- nrow(dataMatrix)
nFeatures <- ncol(dataMatrix)
pixelsPerRun <- prod(faimsDim)
nFaimsRuns <- nFeatures / pixelsPerRun
##----------------------------------------------------------------------
## GENERATE THE WAVELET TRANSFORMED DATA -------------------------------
##----------------------------------------------------------------------
pb <- progBarInit(c(0, nDataItems * nFaimsRuns))
count <- 0
for (i in 1:nDataItems){
working.data <- c()
for (runNum in 1:nFaimsRuns) {
count <- count + 1
pb <- progBarUpdate(pb, count)
currentData <- dataMatrix[i, 1:pixelsPerRun + (runNum - 1) * pixelsPerRun]
dim(currentData) <- faimsDim
##PAD IMAGE WITH ZEROS, TO MAKE A SQUARE MATRIX OF SIZE 2^N
nSize <- 2^ceiling(log2(max(faimsDim)))
data.padded <- matrix(0, nSize, nSize)
data.padded[1:faimsDim[1], 1:faimsDim[2]] <- currentData
##OPTION TO CROP THE SQUARE MATRIX
##this is pretty specific to the FAIMS format....
if (is.null(cropSize)==FALSE){
edgeSize = (nSize - cropSize) / 2
lower = 1 + edgeSize
upper = lower + cropSize - 1
data.padded = data.padded[lower:upper, 1:cropSize]
}
##WAVELET TRANSFORM
current.wd = imwd(data.padded,
filter.number=1,
bc="symmetric",
family = "DaubExPhase")
nLevels = current.wd$nlevels-1-discardHighestNLevels
if (nLevels < 0) stop("Can't discard more levels than are in the transform")
working.data = c(working.data, current.wd$w0Lconstant)
for (j in 0:nLevels) {
for (k in 1:4){
working.data = c(working.data,current.wd[[ lt.to.name(j, k) ]])
}
}
}
if (i==1){
data.wd = matrix(0, nDataItems, length(working.data))
row.names(data.wd) = row.names(dataMatrix)
}
data.wd[i, ] = working.data
}
return(data.wd)
}
mattdneal/FAIMSToolkit documentation built on May 21, 2019, 12:57 p.m.
|
__label__pos
| 0.996318 |
Top
Applying In-Depth Research and Analysis to Achieve Better Outcomes
May 18, 2020
Over the past 20 years, two of the domains to which I have applied my research and analysis skills are UX research and career exploration. I’ve noticed a lot of similarities between the approaches I use in these two domains to get the most desirable and effective outcomes.
• In UX research, the goal is to have the best possible impact on product design and innovation—to help product teams innovate, design, or improve a digital service or product that achieves the highest level of usability, usage, and user satisfaction.
• In career exploration, the goal is to identify the career that best suits a person, in which that person would thrive, excel, and achieve his or her full potential, maximizing personal fulfillment, and contributing to the benefit of the company, community, and the planet.
In both of these domains, the approach, methods, and tools you choose for research and analysis make a big difference in achieving the desired outcomes. My experience has taught me that in-depth research and analysis provide more optimal outcomes over the long term.
Champion Advertisement
Continue Reading…
Unfortunately, research and analysis all too often just skim the surface. For example, a product manager might ask a researcher to evaluate an existing product that does not actually meet a user need. While doing this might seem more efficient in the short term, it tends to generate solutions that do not solve the real problem. Such solutions often require revision in the future, ultimately resulting in higher costs and wasting time, money, and energy.
In this article, I’ll share six keys to applying in-depth research and analysis to achieve better outcomes in User Experience and career exploration.
1. Dive deeply enough.
In both UX research and career exploration, it’s necessary to dive deep enough to gather foundational data and discover insights that can lead to truly innovative and effective long-term results—meaningful results that last instead of short-term patches that don’t solve a problem at a deep enough level. Short-term, quick approaches might initially seem more efficient. You might save time, energy, and money in the short term by doing a quicker evaluation. But the extra time, energy, and money you fail to invest up front often result in headaches, unsatisfactory solutions, and incessant adjustments in the future, leading to more wasted time, energy, and money.
Apply this adage: Go slow to go fast.
I would add: Go deep to go further.
In UX research—especially foundational research—it’s necessary to move beyond any current product or user-interface design. So, instead of evaluating the current user interface, you need to move past the existing solution to explore the underlying user needs that the product is trying to solve. To understand users’ underlying needs, take a step back and explore the problem more deeply. The current product may not address the user’s true needs. By investing some extra time and energy in foundational research, you can ensure that the product’s functionality and design meet users’ needs and are built on the right foundation.
Similarly, in career exploration, rather than evaluating a person’s current or past work—as most people or counselors tend to do—set the current work situation aside for the present so you can explore the underlying needs that work should meet for that person. What are the person’s values? What does that person love doing? What are his or her passions and interests? What are that person’s natural talents and strengths? What is that person’s unique operating manual—the person’s personality patterns.
When people do not like their work, that indicates their work is misaligned with their unique blueprint and operating manual. To help someone discover work they truly love, you must take the time to fully explore and understand the ingredients that would make a great career for that person—before considering the current or past careers. This is why, in my approach to career exploration, I don’t need to look at my clients’ resumes. Nor do I consider the types of careers that are out there before looking at what need the solution—that is, the career—is trying to solve.
This approach to discovering a person’s most fulfilling career is a bottom-up rather than a top-down approach, as the diagram in Figure 1 shows.
Figure 1—Discovering a person’s most fulfilling career
Discovering a person's most fulfilling career
The process of discovering a person’s most fulfilling career comprises the following steps:
1. Identify the person’s unique blueprint, or authentic self.
2. Discover the person’s life purpose.
3. Identify the career that is in alignment with your learnings from steps 1 and 2.
2. Expand the scope of research.
In the domains of both UX research and career exploration, you need to expand not only the depth, but also the scope of your research to reveal unforeseen data and opportunities that can have a significant impact on outcomes—whether on product and design strategy or on your career path. To get different, more effective, more innovative results that will stick, you need to think outside the box you’re currently in. If you limit the scope of your research to the current state and, thus, operate within the same box, you’ll get the same types of results.
“We cannot solve our problems with the same level of thinking that created them.”—Albert Einstein
In UX research, if you want to create a product that people love and want to use, you need to do exploratory research that goes beyond the scope of the current product. If you just keep exploring how people are using the current product—or what works and doesn’t work with the current product—you’ll stay stuck in the same paradigm and limit the scope and impact of potential solutions. You should instead do exploratory research that goes beyond the use of the current product, as well as beyond the scope of the user needs the current product covers. Exploratory research—such as ethnographic research, field interviews, and shadowing, or observing people in their day-to-day life and context—is great for looking beyond the use of a specific product and the scope of the problem that the product is solving.
When I was at Yahoo!, working alongside the other Search UX researchers, we conducted shadow sessions and contextual inquiries in people’s homes to explore the broader context of information searching—how and when—beyond Internet searches. We observed what triggered an information search and what information sources people were using—both offline and online—to reveal unforeseen opportunities for search-product innovation.
Similarly, in career exploration, when I work with clients to discover the career they’ll love, I guide them in expanding the scope of data collection to include their whole life, not just their current or past work experience. We move beyond their field of work to reveal unforeseen opportunities that may lie outside it. Many career counselors and career explorers make the mistake of analyzing data only from the work context, thinking that other data wouldn’t be relevant to work. As a result, they keep operating from the same paradigm that created their problem in the first place and stay at the same level of thinking that isn’t working for them. No wonder they run in circles or find only temporary solutions that don’t solve the root of the problem.
The answers to finding the career that would be your best fit may lie outside your current work experience, especially if what you’ve done so far in your career has not been satisfying to you or doesn’t engage your interests and strengths. If your job is not the right fit for you, but you won’t find your answers by analyzing what you’re doing now. This is why it is essential that you look at your life more broadly. By broadening the scope of your exploration of your values, passions, and talents to your whole life—outside of work—you’ll find the answers you need. Otherwise, you’ll keep making quick, temporary careers fixes that won’t bring you true satisfaction over the long term.
3. Triangulate data from multiple methods and sources.
It’s important to know that no one input, method, or source can give us all the data we need—or even enough reliable data. Each method, source, or type of data has its own biases and limitations. By triangulating different data points, methods, and sources, you can ensure both the completeness and accuracy of your findings. Triangulated data not only supports solid recommendations and projections but also convinces stakeholders and clients of the validity and robustness of both your findings and recommendations. The more triangulation that occurs at different levels, the more robust your outcomes will be. Leave no stone unturned, so you can have the highest level of confidence possible in your results.
In UX research, triangulation can happen at different levels—from your overall research strategy to the individual research method you use—for example:
• By mixing quantitative and qualitative analysis and research methods, you can gather both quantitative and qualitative data. Collaboration between different specialists and teams is often key to getting optimal results—for example, UX researchers, market researchers, and data-mining analysts.
• You can also triangulate different evaluation methods—for example, by combining heuristic evaluation, benchmark testing, and usability testing.
• When using a particular research method such as field study or lab usability testing, it is essential to gather both observational and self-reported data, as I discuss in my article “When Observing Users Is Not Enough.”
In career exploration, triangulation can happen at different levels—for example, by
• exploring different facets of a person’s unique blueprint, including values, strengths, personality patterns, and life purpose
• combining different sources of information to cover the whole Johari Window Model, which is shown in Figure 2, and to ensure you don’t fail to discover any major blind spots. Sources can be either self-discovered and self-reported—that is, known to the self—or other reported, other observed, or from assessments—that is, not known to the self. Others who could share what they’ve observed might be people who know the person—such as family, friends, and coworkers, as well as the career coach.
• combining different data-gathering approaches for these facets and sources—such as inquiries, coaching questions listening, visualizations, teaching and explaining, and reading
Figure 2—The Johari Window Model
The Johari Window Model
Image source: Communication Theory
4. Use the right tools and approaches to collect accurate data.
In addition to triangulating, you must ensure that you use the right approach or tool to gather the most accurate data possible. If you triangulate using tools or approaches that give you inaccurate or false data, you’ll lose the benefits of both the method and the triangulation. This inaccurate data would negatively impact your findings, predictions, and recommendations. One pitfall to avoid is choosing a tool just because it’s popular, taking it at face value, and failing to question its accuracy. Another is going too fast and choosing the easy route, without challenging the accuracy and validity of your data.
In UX research, one example of gathering inaccurate data would be doing usability testing with people who do not belong to the target audience for the product you’re testing or with people who are not passionate about the product. In my article “When Role Playing Doesn’t Work,” I quote Jared Spool, who said:
“Passion on a subject changes how participants invest in usability test tasks. That change can have profound effects on the results and the recommendations produced by the team.”
To get accurate results, you need to recruit participants who are actually involved in the process you’re testing and are passionate about it. This is especially true if you want to test how users respond to specific content or functionality, how they navigate and search for information, or whether certain content is useful and valuable to users. To collect accurate data in usability testing, you also need to have participants perform realistic tasks and task scenarios that are tailored to participants’ real tasks, as I discuss in my article “When Role Playing Doesn’t Work.”
Otherwise, your recommendations won’t have dramatic impacts on use or sales. Jared Spool gives a striking example: “The design recommendation seemed solid, yet sales had dropped 23% immediately after the changes were made.”
In career exploration, an example is the use of the Myers-Briggs Type Indicator (MBTI) by many career coaches and counselors to help identify a client’s personality type. As much as I believe in the validity of the theory behind the sixteen personality types and that this is a great tool to use in career exploration, the instrument itself has many limitations. When I took my Myers-Briggs Type Indicator certification, I learned that, in about 40% of cases, the type the instrument indicates is not people’s best-fit type. There are also many limitations to using the letters representing types individually—for example, T versus F or S versus N. This is why I don’t use the instrument in my practice, and I don’t use the letters either. Instead, I use the InterStrength CORE Approach™, a holistic approach that my mentor Linda Berens has developed, which triangulates two or three different data points to clarify personality type.
I guide my clients through Linda Berens’s CORE Self-Discovery Process™, which is way more effective and accurate than taking the MTBI assessment alone. For many of my clients, the type we identify through Berens’s process is different and much more accurate than the type the MTBI assessment had identified. This is important because your best-fit personality type has a major impact on the type of work environment and tasks that would be the best fit for you. If the data you collect are inaccurate, the outcomes won’t be fully accurate either.
5. Optimize the accuracy of data collection during interviews.
To optimize the accuracy of the qualitative data that you collect—whether through observation or as self-reported data—just choosing the right approach or tool is not enough. You also need to make the most of your method by collecting data effectively. In particular, you must place thoughtful attention on truly hearing what people are saying and avoid erroneous interpretations or letting your own false assumptions color what you hear. Covering this subject fully would require an entire article in itself.
In UX research, the quality of your listening and observing skills can make a big difference in the accuracy of the data you collect. I talked about this at length in my article “When Role Playing Doesn’t Work.” One key thing to be aware of is that you should not rely on any assumptions you might make about the meaning of what study participants are saying or doing. Avoiding this requires high-quality listening. It is so easy to read too quickly into what others are saying or doing and projecting our own meaning onto them. This happens a lot in personal and professional relationships because most people have not been taught the art of listening well. So check your assumptions. Here are some tips for accurately collecting data from my article “When Role Playing Doesn’t Work”:
• Make objective and precise observations. Reflect what you observe instead of making assumptions.
• Be aware of your assumptions or projections on the meaning of what the person is saying. You can learn more about this in my article “When Observing Users Is Not Enough.”
In career exploration, the same principle applies when you’re guiding someone through a career exploration. Active listening, getting other people’s worlds, and not projecting or assuming are key to gathering accurate data and helping people see themselves clearly. If you’re making assumptions, check your assumptions with your client to see whether they’re true. For example, you might say, “It sounds like independence in your work is very important to you. Is that true?” The great thing about asking is that your client will generally not only confirm or correct your assumption but extend your understanding by giving you more information. Another way to fully get other people’s worlds—and help them understand their own world—is to ask Why? Use the 5 Whys Method, which some people call the Root-Cause Analysis Tool.
6. Expand the richness of the data you collect by adapting on the fly.
When you’re collecting qualitative data about people through live interactions, it’s important to be willing to adapt your process to the person with whom you’re talking. Doing so greatly enriches the data you’ll collect—sometimes in unexpected ways. This is key and is an art more than a science.
In UX research, this adaptation can happen at different levels, as follows:
• at the study level—As you’re conducting a research study, it can be beneficial to make ad hoc additions or changes to respond to what’s happening during sessions with participants. For a concept research study at Yahoo!, I designed a research plan that included a comics storyboard walkthrough and paper prototyping. During the study, some participants wanted to draw what they imagined the user interface should look like. Adapting in the moment, I added some ad hoc participatory design to the session, which provided very rich findings to the team—much richer than if I had stuck to the original plan and gone by the book.
• at the session level—Some examples of adaptation include the following:
• changing a task or skipping it altogether—If, during usability testing, you realize that a participant cannot relate to a task at all, adapt it to that participant.
• going along with a user’s flow—Disregard the sequence of questions you’ve planned for a user interview. For example, perhaps a user starts talking about a topic you intended to address at the end of your interview. While much depends on the particular situation, I generally recommend letting users talk about the topic rather than telling them you’d prefer to go back to it at some point later on. If a user spontaneously raises a point you wanted to know about, it is golden.
• allowing unpredictability and flexibility—Don’t follow a test script by the book! Don’t be afraid of going off the beaten path! You might encounter an unexpected, enlightening, or rich insight that can help you have greater impact on the design.
• at the task level—Adapt to each participant’s context and tailor your tasks, your storytelling, and your examples to that participant’s passions, interests, and needs. For example, if you are researching the usage or usability of a search function and a participant tells you he’s passionate about cars, ask him to search for information about cars.
Similarly, in career exploration, adaptation can take place at different levels:
• at the whole-process level—With my clients, I follow a step-by-step process that has proven effective throughout my seven years of experience while working with hundreds of clients. Although each step is important and builds on the others, it is important to adapt to what is emerging during the process—for individual clients and what they need or what works for them. For example, after Step 1 or 2, some clients are not yet ready to move onto the following steps. Some inner blocks are being revealed that we need to address first—before we can move onto the following steps. Sometimes, we can address these blocks in just one or two sessions. But at other times, they’re so deep seated that it takes the rest of the process to address them. A release of past wounds or negative beliefs must happen before they’re ready to step into the career of their dreams.
• at the session level—During the first part of the process, there is a predefined agenda for each session that aligns with homework the client had to do to prepare for the session. However, it is important to adapt to what is emerging in the moment for each client. Sometimes, clients have an expected life challenge or situation that they’re facing that triggers emotions such as grief, fear, or sadness. When these emotions are alive and present, they require attention before a client can be ready to move onto something else. Processing these emotions or situations can take a few minutes or a whole session. Often, being with whatever is emerging allows a client to address, release, or transform some inner blocks, which is exactly what the client needs for the whole process to succeed. It is important to trust that this is what the client needs in the moment.
• at the activity level—It sometimes happens that certain exercises or activities do not align with what a client needs. If the client is not showing resistance to diving into something important, you should listen and adapt to whatever is in the best interests of the client. There is an art to distinguishing the clients’ growth edge versus what does not align with what the client needs.
• at the moment level—Another skill requires dancing in the moment, or adapting to what is emerging in the conversation with the client rather than following a strict agenda. This also requires following what is alive in a conversation, where the energy is the strongest.
Conclusion
In both UX research and career exploration, in-depth research and analysis can have profound impacts on outcomes, revealing unforeseen opportunities and solutions.
However, in UX research, rapid studies often overlook opportunities to create optimal solutions because they remain within the same scope or at the same level of thinking that created the problem in the first place. Plus, they often result in solutions that don’t get to the root of the problem, so fail to solve the problem over the long term, and require multiple revisions of a process in the future. This can be costly in time, energy, and money and cause headaches for both the people who use our products and services and the businesses who employ us.
Whether in UX research or career exploration, spending the extra time, energy, and money it takes to truly solve a problem is usually worthwhile. Truly solving a problem requires the right strategy, method, and tools, as well as the accurate collection and triangulation of data.
You can uncover insights that enable you to solve a problem effectively and achieve significant results. Plus, you can save time, energy, and money down the road. If you’re a UX researcher, your insights can lead to significant impacts on product and design strategy and innovation. If your goal is career exploration, you can identify a career or work environment that is the best fit for you.
All of this might not be new to you if you’re working in the field of UX research. However, have you ever thought about applying the principles of in-depth UX research and analysis to your own career? If not, this is time to start! Ensure that your career is on the right path and that you are fully leveraging your talents, interests, values, and your unique blueprint, to maximize your career satisfaction and success—whether within the field of User Experience or beyond it.
To learn more about Isabelle Peyrichoux’s career-exploration process, check out the following content online.
And read her articles on UXmatters.
Bibliography
Berens, Linda. “The Leading Edge of Psychological Type.” Whitepaper, 2002–2013. Retrieved May 12, 2020.
Berens, Linda. Understanding Yourself and Others: An Introduction to the 4 Temperaments, 4.0. West Hollywood, CA: Radiance House, 2010.
Berens, Linda. Understanding Yourself and Others: An Introduction to Interaction Styles, 2.0. Huntington Beach, CA: Telos Publications, 2008.
Berens, Linda, and Dario Nardi. The Sixteen Personality Types: Descriptions for Self-Discovery. Huntington Beach, CA: Telos Publications, 1999.
Peyrichoux, Isabelle. “3 Keys to Discovering the Career You Absolutely Love.” Webinar, Dominican University of California, September 10, 2015. Retrieved May 12, 2020.
Peyrichoux, Isabelle. “Type and Career Calling: Using Type, Temperament, Interaction Style to Transform Careers, Lives, and the Planet, One Person at a Time.” A forthcoming talk at APTi Conference 2021.
Peyrichoux, Isabelle. “When Observing Users Is Not Enough: 10 Guidelines for Getting More Out of Users’ Verbal Comments.” UXmatters, April 9, 2007. Retrieved May 12, 2020.
Peyrichoux, Isabelle. “When Role Playing Doesn’t Work: Seven Guidelines for Grounding Usability Testing in Participants’ Real Lives.” UXmatters, September 8, 2008. Retrieved May 12, 2020.
Spool, Jared M. “Interview-Based Tasks: Learning from Leonardo DiCaprio.” User Interface Engineering, March 7, 2006. Retrieved June 8, 2008.
CEO and Founder at Brilliant Seeds LLC
San Francisco Bay Area, California, USA
Isabelle PeyrichouxIsabelle has 20 years of experience applying her research and analysis skills to User Experience and career exploration. With a multifaceted education and background in information science, psychology, coaching, personality differences, and relational mastery, she has contributed to innovative approaches in the fields of UX research and career exploration. Isabelle has created a step-by-step approach to career reinvention that goes beyond the limitations of traditional career counseling and has helped hundreds of people find fulfilling careers. Currently based in the San Francisco Bay Area, she has lived and worked in France, Switzerland, the United Kingdom, and Canada and has conducted several international user-research studies. As a user researcher, she has worked for companies such as Yahoo!, Bell Canada, and the French Speaking University Agency. An engaging speaker, Isabelle has given presentations and workshops for professional associations and conferences such as the IA Summit and at General Assembly. She will be speaking at the Association for Psychological Type International in 2021. Read More
Other Articles on Analysis
New on UXmatters
|
__label__pos
| 0.59029 |
Правила синтаксиса файла .gitignore
Правила синтаксиса файла .gitignore
В этой статье будут приведены примеры редактирования файла .gitignore и дан поный список правил синтаксиса.
Правила синтаксиса
• Одна строчка - одно правило,
• Пустые строки игнорируются,
• Комментарии доступны через решётку(#) в начале строки,
• Символ "/" в начале строки указывает, что правило применяется только к файлам и папкам, которые располагаются в той же папке, что и сам файл .gitignore,
• Доступно использовать спецсимволы: звёздочка(*) заменяет любое количество символов(ноль или больше), вопросик(?) заменяет от нуля до одного символа. Можно размещать в любом месте правила,
• Две звёздочки(**) используются для указания любого количества поддиректорий, подробнее смотри ниже в примерах,
• Восклицательный знак(!) в начале строки означает инвертирование правила, необходим для указания исключений из правил игнорирования,
• Символ "\" используется для экранирования спецсимволов, например, чтобы игнорировать файл с именем "!readme!.txt", нужно написать такое правило: "\!readme!.txt",
• Для игнорирования всей директории, правило должно оканчиваться на слэш(/), в противном случае правило считается именем файла.
Пример файла .gitignore
# Игнор-лист файлов проекта
# Игнорировать ВСЕ файлы и директории, включая поддиректории и файлы в них
*
# ---- ФАЙЛЫ ----
# Игнорирование по типу файла, будут игнорироваться в АБСОЛЮТНО всех директориях
# Например /files/data.zip, /server.log, /uploads/users/data/info.xls
*.zip
*.log
*.pdf
*.xls
# Игнорирование файла во ВСЕХ директориях
# Например /params/db/config.php, /config.php
config.php
# Игнорирование конкретного файла ТОЛЬКО в корне проекта
# (корнём считается расположение файла .gitignore)
# Например НЕ БУДЕТ проигнорирован файл /db/config.php
/config.php
# Игнорирование конкретного файла ТОЛЬКО в указанной директории
# Например НЕ БУДЕТ проигнорирован файл /prod/params/config.php
/params/config.php
# ---- ДИРЕКТОРИИ ----
# Игнорирование всех файлов и папок ТОЛЬКО в конкретной директории(включая поддиректории и файлы в них)
# Например /images/user.jpg, /images/company/logo.png
# НЕ БУДУТ проигнорированы файлы и папки /prod/images/user.jpg
/images/*
# Игнорирование всех файлов и папок в ЛЮБЫХ директориях с указанным именем
# Например /images/user.jpg, /core/images/user.jpg
images/*
# Игнорирование ВСЕХ html-файлов в ОДНОЙ КОНКРЕТНОЙ директории(НЕ ВКЛЮЧАЯ поддиректории)
# Например /private/index.html
# НЕ БУДУТ проигнорированы файлы в /private/ivan/index.html
/private/*.html
# Игнорирование ВСЕХ html-файлов в КОНКРЕТНОЙ директории ВКЛЮЧАЯ поддиректории
# Например /private/info.html, /private/users/ivan/info.html
/private/**/*.html
# ---- РАЗНОЕ ----
# Исключение из игнорирования
# Игнорирование ВСЕХ файлов и папок внутри директории /secret,
# за исключением файла /secret/free.txt, он не будет проигнорирован
/secret/*
!/secret/free.txt
# Игнорирование файла с именем, содержащим спецсимволы
# Например !readme!.txt
\!readme!.txt
# Игнорирование всех JPG и JPEG файлов внутри директорий,
# которые начинаются на "h" и МОГУТ содержать ещё один символ после
# Например /images/h4/user.jpg, /images/h/company.jpeg
/images/h?/*.jp?g
Была ли эта статья полезной?
Пользователи, считающие этот материал полезным: 25 из 28
Если статья оказалась вам полезна, пожалуйста, отблагодарите посильной суммой :)
Еще есть вопросы? Отправить запрос
0 Комментарии
Войдите в службу, чтобы оставить комментарий.
На базе технологии Zendesk
|
__label__pos
| 0.531987 |
Dismiss
Announcing Stack Overflow Documentation
We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
Sign up and start helping → Learn more about Documentation →
I'm trying to write a cross-browser event addition method but it's not working in IE at all, here's the code :
index.html
<!doctype html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="helper.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
helper.js
var eventUtil = {
add : function(el, type, fn){
if(typeof(addEventListener) !== "undefined"){
el.addEventListener(type, fn, false);
} else if (typeof(attachEvent) !== "undefined"){
el.attachEvent("on"+type, fn);
} else {
el["on"+type] = fn;
}
}
}
script.js
(function(){
var printMsg= function(){
document.write("hello");
};
eventUtil.add(document.body, "click" , printMsg);
}());
share|improve this question
up vote 2 down vote accepted
You need to do:
add : function(el, type, fn){
if(typeof(el.addEventListener) !== "undefined"){
el.addEventListener(type, fn, false);
} else if (typeof(el.attachEvent) !== "undefined"){
el.attachEvent("on"+type, fn);
} else {
el["on"+type] = fn;
}
As you had it with:
if(typeof(addEventListener) !== "undefined"){
that will always be undefined as addEventListener is not a global variable/function it's a method on the element.
share|improve this answer
actually, addEventListener is defined if window.addEventListener is defined. – kennebec Jul 21 '12 at 2:44
@kennebec - that is no different than what I said - I'm not sure what new information you're adding. window.addEventListener is the same as a global variable/function named addEventListener because the global javascript namespace in a browser is window. – jfriend00 Jul 21 '12 at 4:14
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.605884 |
GCC Code Coverage Report
Directory: src/ Exec Total Coverage
File: src/resources/db/statdb.cpp Lines: 14 98 14.3 %
Date: 2020-06-04 Branches: 2 210 1.0 %
Line Branch Exec Source
1
/*
2
* The ManaPlus Client
3
* Copyright (C) 2016-2019 The ManaPlus Developers
4
*
5
* This file is part of The ManaPlus Client.
6
*
7
* This program is free software; you can redistribute it and/or modify
8
* it under the terms of the GNU General Public License as published by
9
* the Free Software Foundation; either version 2 of the License, or
10
* any later version.
11
*
12
* This program is distributed in the hope that it will be useful,
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
* GNU General Public License for more details.
16
*
17
* You should have received a copy of the GNU General Public License
18
* along with this program. If not, see <http://www.gnu.org/licenses/>.
19
*/
20
21
#include "resources/db/statdb.h"
22
23
#include "configuration.h"
24
25
#include "enums/being/attributesstrings.h"
26
27
#include "utils/checkutils.h"
28
29
#include "resources/beingcommon.h"
30
31
#include "utils/gettext.h"
32
33
#include "debug.h"
34
35
namespace
36
{
37
bool mLoaded = false;
38
1
STD_VECTOR<BasicStat> mBasicStats;
39
1
std::map<std::string, STD_VECTOR<BasicStat> > mStats;
40
1
STD_VECTOR<std::string> mPages;
41
} // namespace
42
43
void StatDb::addDefaultStats()
44
{
45
mBasicStats.push_back(BasicStat(Attributes::PLAYER_STR,
46
"str",
47
// TRANSLATORS: player stat
48
_("Strength")));
49
mBasicStats.push_back(BasicStat(Attributes::PLAYER_AGI,
50
"agi",
51
// TRANSLATORS: player stat
52
_("Agility")));
53
mBasicStats.push_back(BasicStat(Attributes::PLAYER_VIT,
54
"vit",
55
// TRANSLATORS: player stat
56
_("Vitality")));
57
mBasicStats.push_back(BasicStat(Attributes::PLAYER_INT,
58
"int",
59
// TRANSLATORS: player stat
60
_("Intelligence")));
61
mBasicStats.push_back(BasicStat(Attributes::PLAYER_DEX,
62
"dex",
63
// TRANSLATORS: player stat
64
_("Dexterity")));
65
mBasicStats.push_back(BasicStat(Attributes::PLAYER_LUK,
66
"luk",
67
// TRANSLATORS: player stat
68
_("Luck")));
69
}
70
71
1
const STD_VECTOR<BasicStat> &StatDb::getBasicStats()
72
{
73
1
return mBasicStats;
74
}
75
76
const STD_VECTOR<BasicStat> &StatDb::getStats(const std::string &page)
77
{
78
return mStats[page];
79
}
80
81
1
const STD_VECTOR<std::string> &StatDb::getPages()
82
{
83
1
return mPages;
84
}
85
86
void StatDb::load()
87
{
88
if (mLoaded)
89
unload();
90
91
logger->log1("Initializing stat database...");
92
93
loadXmlFile(paths.getStringValue("statFile"), SkipError_false);
94
loadXmlFile(paths.getStringValue("statPatchFile"), SkipError_true);
95
loadXmlDir("statPatchDir", loadXmlFile)
96
mLoaded = true;
97
}
98
99
static void loadBasicStats(XmlNodeConstPtr rootNode)
100
{
101
const int maxAttr = static_cast<int>(Attributes::MAX_ATTRIBUTE);
102
for_each_xml_child_node(node, rootNode)
103
{
104
if (xmlNameEqual(node, "stat"))
105
{
106
const std::string name = XML::getProperty(node, "name", "");
107
const std::string attr = XML::getProperty(node, "attr", "");
108
if (attr.empty() || AttributesEnum::find(attr) == false)
109
{
110
const int id = XML::getProperty(node, "id", 0);
111
if (id <= 0 || id >= maxAttr)
112
{
113
reportAlways("Wrong attr or id for basic "
114
"stat with name %s",
115
name.c_str())
116
continue;
117
}
118
const std::string tag = XML::getProperty(node, "tag", "");
119
mBasicStats.push_back(BasicStat(static_cast<AttributesT>(id),
120
tag,
121
name));
122
}
123
else
124
{
125
const std::string tag = XML::getProperty(node, "tag", "");
126
mBasicStats.push_back(BasicStat(AttributesEnum::get(attr),
127
tag,
128
name));
129
}
130
}
131
}
132
}
133
134
static void loadStats(XmlNodeConstPtr rootNode,
135
const std::string &page)
136
{
137
const int maxAttr = static_cast<int>(Attributes::MAX_ATTRIBUTE);
138
STD_VECTOR<BasicStat> &stats = mStats[page];
139
mPages.push_back(page);
140
for_each_xml_child_node(node, rootNode)
141
{
142
if (xmlNameEqual(node, "stat"))
143
{
144
const std::string name = XML::getProperty(node, "name", "");
145
const std::string attr = XML::getProperty(node, "attr", "");
146
if (attr.empty() || AttributesEnum::find(attr) == false)
147
{
148
const int id = XML::getProperty(node, "id", 0);
149
if (id <= 0 || id >= maxAttr)
150
{
151
reportAlways("Wrong attr or id for extended "
152
"stat with name %s",
153
name.c_str())
154
continue;
155
}
156
stats.push_back(BasicStat(static_cast<AttributesT>(id),
157
std::string(),
158
name));
159
}
160
else
161
{
162
stats.push_back(BasicStat(AttributesEnum::get(attr),
163
std::string(),
164
name));
165
}
166
}
167
}
168
}
169
170
void StatDb::loadXmlFile(const std::string &fileName,
171
const SkipError skipError)
172
{
173
XML::Document doc(fileName,
174
UseVirtFs_true,
175
skipError);
176
XmlNodeConstPtrConst rootNode = doc.rootNode();
177
178
if ((rootNode == nullptr) || !xmlNameEqual(rootNode, "stats"))
179
{
180
logger->log("StatDb: Error while loading %s!",
181
fileName.c_str());
182
if (skipError == SkipError_false)
183
addDefaultStats();
184
return;
185
}
186
187
for_each_xml_child_node(node, rootNode)
188
{
189
if (xmlNameEqual(node, "include"))
190
{
191
const std::string name = XML::getProperty(node, "name", "");
192
if (!name.empty())
193
loadXmlFile(name, skipError);
194
continue;
195
}
196
else if (xmlNameEqual(node, "basic"))
197
{
198
loadBasicStats(node);
199
}
200
else if (xmlNameEqual(node, "extended"))
201
{
202
// TRANSLATORS: stats page name
203
loadStats(node, _("Extended"));
204
}
205
else if (xmlNameEqual(node, "page"))
206
{
207
std::string page = XML::langProperty(node, "name", "");
208
if (page.empty())
209
{
210
reportAlways("Page without name in stats.xml")
211
page = "Unknown";
212
}
213
loadStats(node, page);
214
}
215
}
216
if (skipError == SkipError_false)
217
{
218
if (mBasicStats.empty() &&
219
mStats.empty())
220
{
221
reportAlways("StatDb: no stats found")
222
addDefaultStats();
223
}
224
}
225
}
226
227
215
void StatDb::unload()
228
{
229
215
logger->log1("Unloading stat database...");
230
231
215
mBasicStats.clear();
232
215
mStats.clear();
233
215
mPages.clear();
234
215
mLoaded = false;
235
218
}
|
__label__pos
| 0.949131 |
Skip to content
HTTPS clone URL
Subversion checkout URL
You can clone with
or
.
Download ZIP
tree: 77e45352e7
Fetching contributors…
Cannot retrieve contributors at this time
553 lines (471 sloc) 19.266 kB
require 'set'
require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/kernel'
module Dependencies #:nodoc:
extend self
# Should we turn on Ruby warnings on the first load of dependent files?
mattr_accessor :warnings_on_first_load
self.warnings_on_first_load = false
# All files ever loaded.
mattr_accessor :history
self.history = Set.new
# All files currently loaded.
mattr_accessor :loaded
self.loaded = Set.new
# Should we load files or require them?
mattr_accessor :mechanism
self.mechanism = :load
# The set of directories from which we may automatically load files. Files
# under these directories will be reloaded on each request in development mode,
# unless the directory also appears in load_once_paths.
mattr_accessor :load_paths
self.load_paths = []
# The set of directories from which automatically loaded constants are loaded
# only once. All directories in this set must also be present in +load_paths+.
mattr_accessor :load_once_paths
self.load_once_paths = []
# An array of qualified constant names that have been loaded. Adding a name to
# this array will cause it to be unloaded the next time Dependencies are cleared.
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
mattr_accessor :explicitly_unloadable_constants
self.explicitly_unloadable_constants = []
# Set to true to enable logging of const_missing and file loads
mattr_accessor :log_activity
self.log_activity = false
# An internal stack used to record which constants are loaded by any block.
mattr_accessor :constant_watch_stack
self.constant_watch_stack = []
def load?
mechanism == :load
end
def depend_on(file_name, swallow_load_errors = false)
path = search_for_file(file_name)
require_or_load(path || file_name)
rescue LoadError
raise unless swallow_load_errors
end
def associate_with(file_name)
depend_on(file_name, true)
end
def clear
log_call
loaded.clear
remove_unloadable_constants!
end
def require_or_load(file_name, const_path = nil)
log_call file_name, const_path
file_name = $1 if file_name =~ /^(.*)\.rb$/
expanded = File.expand_path(file_name)
return if loaded.include?(expanded)
# Record that we've seen this file *before* loading it to avoid an
# infinite loop with mutual dependencies.
loaded << expanded
begin
if load?
log "loading #{file_name}"
# Enable warnings iff this file has not been loaded before and
# warnings_on_first_load is set.
load_args = ["#{file_name}.rb"]
load_args << const_path unless const_path.nil?
if !warnings_on_first_load or history.include?(expanded)
result = load_file(*load_args)
else
enable_warnings { result = load_file(*load_args) }
end
else
log "requiring #{file_name}"
result = require file_name
end
rescue Exception
loaded.delete expanded
raise
end
# Record history *after* loading so first load gets warnings.
history << expanded
return result
end
# Is the provided constant path defined?
def qualified_const_defined?(path)
raise NameError, "#{path.inspect} is not a valid constant name!" unless
/^(::)?([A-Z]\w*)(::[A-Z]\w*)*$/ =~ path
names = path.to_s.split('::')
names.shift if names.first.empty?
# We can't use defined? because it will invoke const_missing for the parent
# of the name we are checking.
names.inject(Object) do |mod, name|
return false unless uninherited_const_defined?(mod, name)
mod.const_get name
end
return true
end
if Module.method(:const_defined?).arity == 1
# Does this module define this constant?
# Wrapper to accomodate changing Module#const_defined? in Ruby 1.9
def uninherited_const_defined?(mod, const)
mod.const_defined?(const)
end
else
def uninherited_const_defined?(mod, const) #:nodoc:
mod.const_defined?(const, false)
end
end
# Given +path+, a filesystem path to a ruby file, return an array of constant
# paths which would cause Dependencies to attempt to load this file.
def loadable_constants_for_path(path, bases = load_paths)
path = $1 if path =~ /\A(.*)\.rb\Z/
expanded_path = File.expand_path(path)
bases.collect do |root|
expanded_root = File.expand_path(root)
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
nesting = expanded_path[(expanded_root.size)..-1]
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
next if nesting.blank?
[
nesting.camelize,
# Special case: application.rb might define ApplicationControlller.
('ApplicationController' if nesting == 'application')
]
end.flatten.compact.uniq
end
# Search for a file in load_paths matching the provided suffix.
def search_for_file(path_suffix)
path_suffix = path_suffix + '.rb' unless path_suffix.ends_with? '.rb'
load_paths.each do |root|
path = File.join(root, path_suffix)
return path if File.file? path
end
nil # Gee, I sure wish we had first_match ;-)
end
# Does the provided path_suffix correspond to an autoloadable module?
# Instead of returning a boolean, the autoload base for this module is returned.
def autoloadable_module?(path_suffix)
load_paths.each do |load_path|
return load_path if File.directory? File.join(load_path, path_suffix)
end
nil
end
def load_once_path?(path)
load_once_paths.any? { |base| path.starts_with? base }
end
# Attempt to autoload the provided module name by searching for a directory
# matching the expect path suffix. If found, the module is created and assigned
# to +into+'s constants with the name +const_name+. Provided that the directory
# was loaded from a reloadable base path, it is added to the set of constants
# that are to be unloaded.
def autoload_module!(into, const_name, qualified_name, path_suffix)
return nil unless base_path = autoloadable_module?(path_suffix)
mod = Module.new
into.const_set const_name, mod
autoloaded_constants << qualified_name unless load_once_paths.include?(base_path)
return mod
end
# Load the file at the provided path. +const_paths+ is a set of qualified
# constant names. When loading the file, Dependencies will watch for the
# addition of these constants. Each that is defined will be marked as
# autoloaded, and will be removed when Dependencies.clear is next called.
#
# If the second parameter is left off, then Dependencies will construct a set
# of names that the file at +path+ may define. See
# +loadable_constants_for_path+ for more details.
def load_file(path, const_paths = loadable_constants_for_path(path))
log_call path, const_paths
const_paths = [const_paths].compact unless const_paths.is_a? Array
parent_paths = const_paths.collect { |const_path| /(.*)::[^:]+\Z/ =~ const_path ? $1 : :Object }
result = nil
newly_defined_paths = new_constants_in(*parent_paths) do
result = load_without_new_constant_marking path
end
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
autoloaded_constants.uniq!
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
return result
end
# Return the constant path for the provided parent and constant name.
def qualified_name_for(mod, name)
mod_name = to_constant_name mod
(%w(Object Kernel).include? mod_name) ? name.to_s : "#{mod_name}::#{name}"
end
# Load the constant named +const_name+ which is missing from +from_mod+. If
# it is not possible to load the constant into from_mod, try its parent module
# using const_missing.
def load_missing_constant(from_mod, const_name)
log_call from_mod, const_name
if from_mod == Kernel
if ::Object.const_defined?(const_name)
log "Returning Object::#{const_name} for Kernel::#{const_name}"
return ::Object.const_get(const_name)
else
log "Substituting Object for Kernel"
from_mod = Object
end
end
# If we have an anonymous module, all we can do is attempt to load from Object.
from_mod = Object if from_mod.name.blank?
unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
end
raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name)
qualified_name = qualified_name_for from_mod, const_name
path_suffix = qualified_name.underscore
name_error = NameError.new("uninitialized constant #{qualified_name}")
file_path = search_for_file(path_suffix)
if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
require_or_load file_path
raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name)
return from_mod.const_get(const_name)
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
return mod
elsif (parent = from_mod.parent) && parent != from_mod &&
! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) }
# If our parents do not have a constant named +const_name+ then we are free
# to attempt to load upwards. If they do have such a constant, then this
# const_missing must be due to from_mod::const_name, which should not
# return constants from from_mod's parents.
begin
return parent.const_missing(const_name)
rescue NameError => e
raise unless e.missing_name? qualified_name_for(parent, const_name)
raise name_error
end
else
raise name_error
end
end
# Remove the constants that have been autoloaded, and those that have been
# marked for unloading.
def remove_unloadable_constants!
autoloaded_constants.each { |const| remove_constant const }
autoloaded_constants.clear
explicitly_unloadable_constants.each { |const| remove_constant const }
end
# Determine if the given constant has been automatically loaded.
def autoloaded?(desc)
# No name => anonymous module.
return false if desc.is_a?(Module) && desc.name.blank?
name = to_constant_name desc
return false unless qualified_const_defined? name
return autoloaded_constants.include?(name)
end
# Will the provided constant descriptor be unloaded?
def will_unload?(const_desc)
autoloaded?(desc) ||
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
end
# Mark the provided constant name for unloading. This constant will be
# unloaded on each request, not just the next one.
def mark_for_unload(const_desc)
name = to_constant_name const_desc
if explicitly_unloadable_constants.include? name
return false
else
explicitly_unloadable_constants << name
return true
end
end
# Run the provided block and detect the new constants that were loaded during
# its execution. Constants may only be regarded as 'new' once -- so if the
# block calls +new_constants_in+ again, then the constants defined within the
# inner call will not be reported in this one.
#
# If the provided block does not run to completion, and instead raises an
# exception, any new constants are regarded as being only partially defined
# and will be removed immediately.
def new_constants_in(*descs)
log_call(*descs)
# Build the watch frames. Each frame is a tuple of
# [module_name_as_string, constants_defined_elsewhere]
watch_frames = descs.collect do |desc|
if desc.is_a? Module
mod_name = desc.name
initial_constants = desc.local_constant_names
elsif desc.is_a?(String) || desc.is_a?(Symbol)
mod_name = desc.to_s
# Handle the case where the module has yet to be defined.
initial_constants = if qualified_const_defined?(mod_name)
mod_name.constantize.local_constant_names
else
[]
end
else
raise Argument, "#{desc.inspect} does not describe a module!"
end
[mod_name, initial_constants]
end
constant_watch_stack.concat watch_frames
aborting = true
begin
yield # Now yield to the code that is to define new constants.
aborting = false
ensure
# Find the new constants.
new_constants = watch_frames.collect do |mod_name, prior_constants|
# Module still doesn't exist? Treat it as if it has no constants.
next [] unless qualified_const_defined?(mod_name)
mod = mod_name.constantize
next [] unless mod.is_a? Module
new_constants = mod.local_constant_names - prior_constants
# Make sure no other frames takes credit for these constants.
constant_watch_stack.each do |frame_name, constants|
constants.concat new_constants if frame_name == mod_name
end
new_constants.collect do |suffix|
mod_name == "Object" ? suffix : "#{mod_name}::#{suffix}"
end
end.flatten
log "New constants: #{new_constants * ', '}"
if aborting
log "Error during loading, removing partially loaded constants "
new_constants.each { |name| remove_constant name }
new_constants.clear
end
end
return new_constants
ensure
# Remove the stack frames that we added.
if defined?(watch_frames) && ! watch_frames.blank?
frame_ids = watch_frames.collect(&:object_id)
constant_watch_stack.delete_if do |watch_frame|
frame_ids.include? watch_frame.object_id
end
end
end
class LoadingModule #:nodoc:
# Old style environment.rb referenced this method directly. Please note, it doesn't
# actually *do* anything any more.
def self.root(*args)
if defined?(RAILS_DEFAULT_LOGGER)
RAILS_DEFAULT_LOGGER.warn "Your environment.rb uses the old syntax, it may not continue to work in future releases."
RAILS_DEFAULT_LOGGER.warn "For upgrade instructions please see: http://manuals.rubyonrails.com/read/book/19"
end
end
end
# Convert the provided const desc to a qualified constant name (as a string).
# A module, class, symbol, or string may be provided.
def to_constant_name(desc) #:nodoc:
name = case desc
when String then desc.starts_with?('::') ? desc[2..-1] : desc
when Symbol then desc.to_s
when Module
raise ArgumentError, "Anonymous modules have no name to be referenced by" if desc.name.blank?
desc.name
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
end
end
def remove_constant(const) #:nodoc:
return false unless qualified_const_defined? const
const = $1 if /\A::(.*)\Z/ =~ const.to_s
names = const.to_s.split('::')
if names.size == 1 # It's under Object
parent = Object
else
parent = (names[0..-2] * '::').constantize
end
log "removing constant #{const}"
parent.instance_eval { remove_const names.last }
return true
end
protected
def log_call(*args)
if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
arg_str = args.collect(&:inspect) * ', '
/in `([a-z_\?\!]+)'/ =~ caller(1).first
selector = $1 || '<unknown>'
log "called #{selector}(#{arg_str})"
end
end
def log(msg)
if defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER && log_activity
RAILS_DEFAULT_LOGGER.debug "Dependencies: #{msg}"
end
end
end
Object.instance_eval do
define_method(:require_or_load) { |file_name| Dependencies.require_or_load(file_name) } unless Object.respond_to?(:require_or_load)
define_method(:require_dependency) { |file_name| Dependencies.depend_on(file_name) } unless Object.respond_to?(:require_dependency)
define_method(:require_association) { |file_name| Dependencies.associate_with(file_name) } unless Object.respond_to?(:require_association)
end
class Module #:nodoc:
# Rename the original handler so we can chain it to the new one
alias :rails_original_const_missing :const_missing
# Use const_missing to autoload associations so we don't have to
# require_association when using single-table inheritance.
def const_missing(class_id)
Dependencies.load_missing_constant self, class_id
end
def unloadable(const_desc = self)
super(const_desc)
end
end
class Class
def const_missing(const_name)
if [Object, Kernel].include?(self) || parent == self
super
else
begin
begin
Dependencies.load_missing_constant self, const_name
rescue NameError
parent.send :const_missing, const_name
end
rescue NameError => e
# Make sure that the name we are missing is the one that caused the error
parent_qualified_name = Dependencies.qualified_name_for parent, const_name
raise unless e.missing_name? parent_qualified_name
qualified_name = Dependencies.qualified_name_for self, const_name
raise NameError.new("uninitialized constant #{qualified_name}").copy_blame!(e)
end
end
end
end
class Object
alias_method :load_without_new_constant_marking, :load
def load(file, *extras) #:nodoc:
Dependencies.new_constants_in(Object) { super }
rescue Exception => exception # errors from loading file
exception.blame_file! file
raise
end
def require(file, *extras) #:nodoc:
Dependencies.new_constants_in(Object) { super }
rescue Exception => exception # errors from required file
exception.blame_file! file
raise
end
# Mark the given constant as unloadable. Unloadable constants are removed each
# time dependencies are cleared.
#
# Note that marking a constant for unloading need only be done once. Setup
# or init scripts may list each unloadable constant that may need unloading;
# each constant will be removed for every subsequent clear, as opposed to for
# the first clear.
#
# The provided constant descriptor may be a (non-anonymous) module or class,
# or a qualified constant name as a string or symbol.
#
# Returns true if the constant was not previously marked for unloading, false
# otherwise.
def unloadable(const_desc)
Dependencies.mark_for_unload const_desc
end
end
# Add file-blaming to exceptions
class Exception #:nodoc:
def blame_file!(file)
(@blamed_files ||= []).unshift file
end
def blamed_files
@blamed_files ||= []
end
def describe_blame
return nil if blamed_files.empty?
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
end
def copy_blame!(exc)
@blamed_files = exc.blamed_files.clone
self
end
end
Jump to Line
Something went wrong with that request. Please try again.
|
__label__pos
| 0.991884 |
Chapter 3 Jan 20–26: Hypothesis Tests and T-Tests
Important Request: As you read through this week’s chapter, please note down anything that you have questions about. Then we will address these questions when we have our video calls.
Possibly useful as you read:
• On a Windows or Linux computer, to open a link in a new browser tab, hold down the control key and then click on the link.
• On a Mac computer, to open a link in a new browser tab, hold down the command key and then click on the link.
3.2 Hypothesis Tests
Read the following:
3.2.1 One-Sample Hypothesis Tests
Watch/read the following:
Optional (might be useful later):
3.2.2 Two-Sample Hypothesis Tests (T-Test)
Look through the following about t-tests:
T-tests are used when we want to evaluate the difference between means from two independent groups. If you want to compare more than two means, you would use a different statistical test (ANOVA, which we will cover soon). We will focus on two forms of the t-test: independent samples and dependent samples t-tests.
3.2.3 Independent Samples T-Test
An independent samples t-test is used when you have means from two separate groups that you want to compare. For example, you might have math exam scores from some men and some women, and you want to see if there is a gender difference. Because you have two independent groups—men and women—an independent samples t-test would be appropriate. This is considered a between-subjects design.
The null hypothesis for a t-test is that the difference between means (of the women’s scores and men’s scores) is 0:
\[H_0 = \mu_1 - \mu_2 = 0\]
In other words, we start with the assumption that there is no difference between men and women. If we find evidence that there is a difference, we will reject the null hypothesis (which is the assumption that they’re the same). If we do not find any evidence that the math scores of the sampled men and the sampled women are different, we fail to reject the null hypothesis.
Why don’t we just say that we “accept the null hypothesis”? Because we don’t know for sure if the null hypothesis is true or not. All we know is that we didn’t find any evidence to say otherwise. So the null hypothesis might be true, but maybe there is truly a difference between the two groups and we just didn’t have enough data to detect it. This is tricky stuff to get used to at first. We can talk more about this and go through more examples together on our video calls.
If two samples come from the same population, we expect them to have equal means (although with sampling variation, they may not be exactly equal). Under the null hypothesis, we expect that the there are no differences between the groups (the experimental manipulation didn’t have an effect).
There are three assumptions of the independent samples t-tests that must be met in order to for the results to be valid and interpretable:
1. Homogeneity of variances: We assume that the two groups have the same variance.
2. Population is normally distributed.
3. Independence of scores: Each individual (or observation) contributes only one score (data point). If they submit more than one score, then those responses (scores) are correlated with each other and therefore not independent.
3.2.4 Dependent Samples T-test
A dependent samples t-test is used when the two means you want to compare come from the same person. For example, you might have pre-test and post-test scores for individuals after they have undergone some sort of intervention. You want to know if their scores increased (or decreased) between from pre-test to post-test. This is a within-subjects design.
3.2.5 Errors in Hypothesis Testing
There are two types of errors that occur in hypothesis testing:
• Type I error: rejecting the null hypothesis when it’s actually true.
• Type II error: failing to reject the null hypothesis when it’s actually false.
Look through the following resources on these types of errors:
3.3 Assignment
3.3.1 Dance of the Means
For the first part of the homework this week, you will complete the Dance of the Means activity. Please download the ESCI Dance of the Means NITOP.xlsm Excel file and Guided Activity Word file.14 This PowerPoint file may also help you get the activity up and running.
You may have to click on Enable Content or Enable Macros in the Excel file to get it to work.
Please follow along in the activity guide and then answer the following questions:
Task 1: What is the sampling distribution of the mean?
Task 2: Are sample means from random samples always normally distributed around the population mean? Why or why not?
Task 3: What factors influence the MoE and why?
Task 4: When will the sampling distribution of means be “normal”?
Task 5: Why is the central limit theorem important?
3.3.2 Comparing Distributions With a T-Test
For this part of the assignment, we will use the 2 Sample T-Test tool, which I will call the tool throughout this section of the assignment.
Imagine that we, some researchers, are trying to answer the following research question: How does fertilizer affect plant growth?
We conduct a randomized controlled trial in which some plants are given a fixed amount of fertilizer (treatment group) and other plants are given no fertilizer (control group). Then we measure how much each plant grows over the course of a month. Let’s say we have ten plants in each group and we find the following amounts of growth.
The 10 plants in the control group each grew this much (each number corresponds to one plant’s growth):
3.8641111
4.1185322
2.6598828
0.3559656
2.8639095
0.9020122
5.0527020
2.3293899
3.5117162
4.3417785
The 10 plants in the treatment group each grew this much:
7.532292
1.445972
6.875600
6.518691
1.193905
4.659153
3.512655
4.578366
8.791810
4.891557
Delete the numbers that are pre-populated in the tool. Copy and paste our control data in as Sample 1 and our treatment data in as Sample 2.
Task 6: What is the mean and standard deviation of the control data? What is the mean and standard deviation of the treatment data? Do not calculate these by hand. The tool will tell these to you in the sample summary section.
You’ll see that the tool has drawn the distributions of the data for our treatment and control groups. That’s how you can visualize the effect size (impact) of an RCT. It has also given us a verdict at the bottom that the “Sample 2 mean is greater.” This means that this particular statistical test (a t-test) concludes that we are more than 95% certain that sample 1 (the control group) and sample 2 (the treatment group) are drawn from separate populations. In this case, the control group is sampled from the “population” of plants that didn’t get fertilizer and the treatment group is sampled from the “population” of those that did.
This process is called inference. We are making the inference, based on our 20-plant study, that in the broader population of plants, fertilizer is associated with more growth. The typical statistical threshold for inference is 95% certainty. In the difference of means section of the tool, you’ll see p = 0.0468 written. This is called a p-value. The following formula gives us the percentage of certainty we have in a statistical estimate, based on the p-value (which is written as p): \(\text{Level of Certainty} = (1-p)*100\). To be 95% certain or higher, the p-value must be equal to 0.05 or lower. That’s why you will often see p<0.05 written in studies and/or results tables.
With these particular results, our experiment found statistically significant evidence that fertilizer is associated with plant growth.
Task 7: What was the null hypothesis in this t-test that we conducted?
Task 8: What was the alternate hypothesis in this t-test that we conducted?
Now, click on the radio buttons next to ‘Sample 1 summary’ and ‘Sample 2 summary.’ This will allow you to compare different distributions to each other quickly, without having to change the numbers (raw data) above. Let’s imagine that the control group had not had as much growth as it did. Change the Sample 2 mean from 5 to 4.5.
Task 9: What is the new p-value of this t-test, with the new mean for Sample 2? What is the conclusion of our experiment, with these new numbers? Use the proper statistical language to write your answer.
Task 10: Gradually reduce the standard deviation of Sample 2 until the results are statistically significant at the 95% certainty level. What is the relationship between the standard deviation of your samples and our ability to distinguish them from each other statistically?15
3.3.3 Logistical Tasks
Task 11: At the start of this chapter, I requested that you write down any questions you have. Please include them with your submitted assignment. If you don’t have any, just state this in your answer.
Task 12: Please upload your Week 1 assignment (from last week) to the D2L Dropbox. I learned that we are required to use D2L for this, contrary to my instructions from last week. Sorry about any confusion! We will not be using the system I described last week. The dropbox is located at Assessments -> Assignments -> Dropbox for all assignments in D2L.
Task 13: Please upload this assignment that you just finished today to the very same D2L Dropbox used in the previous task. Please follow the same file naming convention that we used last week.
Task 14: Also e-mail your new completed assignment to me at .
1. The source of both files is https://thenewstatistics.com/itns/esci/dance-of-the-means/.
2. Remember, when we are analyzing the data in an RCT, we are trying to figure out if the treatment and control groups had different or similar results. We are seeing if we can distinguish the two groups from each other in any way. The mean and standard deviation of the data in the two groups are the key parameters that help us tell the treatment and control groups apart, which is why you need to play around with the t-test tool to understand these relationships.
|
__label__pos
| 0.998691 |
nba交易新闻:编码规范 by @mdo
编写灵活、稳定、高质量的 HTML 和 CSS 代码的规范。
目录
HTML
CSS
黄金定律
永远遵循同一套编码规范 -- 可以是这里列出的,也可以是你自己总结的。如果你发现本规范中有任何错误,敬请指正。通过 open an issue on GitHub为本规范添加或贡献内容。
不管有多少人共同参与同一项目,一定要确保每一行代码都像是同一个人编写的。
HTML
语法
<!DOCTYPE html>
<html>
<head>
<title>Page title</title>
</head>
<body>
<img src="images/company-logo.png" alt="Company">
<h1 class="hello-world">Hello, world!</h1>
</body>
</html>
HTML5 doctype
为每个 HTML 页面的第一行添加标准模式(standard mode)的声明,这样能够确保在每个浏览器中拥有一致的展现。
<!DOCTYPE html>
<html>
<head>
</head>
</html>
语言属性
根据 HTML5 规范:
强烈建议为 html 根元素指定 lang 属性,从而为文档设置正确的语言。这将有助于语音合成工具确定其所应该采用的发音,有助于翻译工具确定其翻译时所应遵守的规则等等。
更多关于 lang 属性的知识可以从 此规范 中了解。
这里列出了语言代码表。
<html lang="zh-CN">
<!-- ... -->
</html>
IE 兼容模式
IE 支持通过特定的 <meta> 标签来确定绘制当前页面所应该采用的 IE 版本。除非有强烈的特殊需求,否则最好是设置为 edge mode,从而通知 IE 采用其所支持的最新的模式。
阅读这篇 stack overflow 上的文章可以获得更多有用的信息。
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
字符编码
通过明确声明字符编码,能够确保浏览器快速并容易的判断页面内容的渲染方式。这样做的好处是,可以避免在 HTML 中使用字符实体标记(character entity),从而全部与文档编码一致(一般采用 UTF-8 编码)。
<head>
<meta charset="UTF-8">
</head>
引入 CSS 和 JavaScript 文件
根据 HTML5 规范,在引入 CSS 和 JavaScript 文件时一般不需要指定 type 属性,因为 text/csstext/javascript 分别是它们的默认值。
HTML5 spec links
<!-- External CSS -->
<link rel="stylesheet" href="css/code-guide.css">
<!-- In-document CSS -->
<style>
/* ... */
</style>
<!-- JavaScript -->
<script src="code-guide.js"></script>
实用为王
尽量遵循 HTML 标准和语义,但是不要以牺牲实用性为代价。任何时候都要尽量使用最少的标签并保持最小的复杂度。
属性顺序
HTML 属性应当按照以下给出的顺序依次排列,确保代码的易读性。
class 用于标识高度可复用组件,因此应该排在首位。id 用于标识具体组件,应当谨慎使用(例如,页面内的书签),因此排在第二位。
<a class="..." id="..." data-modal="toggle" href="#">
Example link
</a>
<input class="form-control" type="text">
<img src="..." alt="...">
布尔(boolean)型属性
布尔型属性可以在声明时不赋值。XHTML 规范要求为其赋值,但是 HTML5 规范不需要。
更多信息请参考 WhatWG section on boolean attributes
元素的布尔型属性如果有值,就是 true,如果没有值,就是 false。
如果一定要为其赋值的话,请参考 WhatWG 规范:
如果属性存在,其值必须是空字符串或 [...] 属性的规范名称,并且不要再收尾添加空白符。
简单来说,就是不用赋值。
<input type="text" disabled>
<input type="checkbox" value="1" checked>
<select>
<option value="1" selected>1</option>
</select>
减少标签的数量
编写 HTML 代码时,尽量避免多余的父元素。很多时候,这需要迭代和重构来实现。请看下面的案例:
<!-- Not so great -->
<span class="avatar">
<img src="...">
</span>
<!-- Better -->
<img class="avatar" src="...">
JavaScript 生成的标签
通过 JavaScript 生成的标签让内容变得不易查找、编辑,并且降低性能。能避免时尽量避免。
CSS
语法
对于这里用到的术语有疑问吗?请参考 Wikipedia 上的 syntax section of the Cascading Style Sheets article。
/* Bad CSS */
.selector, .selector-secondary, .selector[type=text] {
padding:15px;
margin:0px 0px 15px;
background-color:rgba(0, 0, 0, 0.5);
box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}
/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
padding: 15px;
margin-bottom: 15px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
声明顺序
相关的属性声明应当归为一组,并按照下面的顺序排列:
1. Positioning
2. Box model
3. Typographic
4. Visual
由于定位(positioning)可以从正常的文档流中移除元素,并且还能覆盖盒模型(box model)相关的样式,因此排在首位。盒模型排在第二位,因为它决定了组件的尺寸和位置。
其他属性只是影响组件的内部(inside)或者是不影响前两组属性,因此排在后面。
完整的属性列表及其排列顺序请参考 Recess。
.declaration-order {
/* Positioning */
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 100;
/* Box-model */
display: block;
float: right;
width: 100px;
height: 100px;
/* Typography */
font: normal 13px "Helvetica Neue", sans-serif;
line-height: 1.5;
color: #333;
text-align: center;
/* Visual */
background-color: #f5f5f5;
border: 1px solid #e5e5e5;
border-radius: 3px;
/* Misc */
opacity: 1;
}
不要使用 @import
<link> 标签相比,@import 指令要慢很多,不光增加了额外的请求次数,还会导致不可预料的问题。替代办法有以下几种:
请参考 Steve Souders 的文章了解更多知识。
<!-- Use link elements -->
<link rel="stylesheet" href="core.css">
<!-- Avoid @imports -->
<style>
@import url("more.css");
</style>
媒体查询(Media query)的位置
将媒体查询放在尽可能相关规则的附近。不要将他们打包放在一个单一样式文件中或者放在文档底部。如果你把他们分开了,将来只会被大家遗忘。下面给出一个典型的实例。
.element { ... }
.element-avatar { ... }
.element-selected { ... }
@media (min-width: 480px) {
.element { ...}
.element-avatar { ... }
.element-selected { ... }
}
带前缀的属性
当使用特定厂商的带有前缀的属性时,通过缩进的方式,让每个属性的值在垂直方向对齐,这样便于多行编辑。
在 Textmate 中,使用 Text → Edit Each Line in Selection (⌃⌘A)。在 Sublime Text 2 中,使用 Selection → Add Previous Line (⌃⇧↑) 和 Selection → Add Next Line (⌃⇧↓)。
/* Prefixed properties */
.selector {
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
box-shadow: 0 1px 2px rgba(0,0,0,.15);
}
单行规则声明
对于只包含一条声明的样式,为了易读性和便于快速编辑,建议将语句放在同一行。对于带有多条声明的样式,还是应当将声明分为多行。
这样做的关键因素是为了错误检测 -- 例如,CSS 校验器指出在 183 行有语法错误。如果是单行单条声明,你就不会忽略这个错误;如果是单行多条声明的话,你就要仔细分析避免漏掉错误了。
/* Single declarations on one line */
.span1 { width: 60px; }
.span2 { width: 140px; }
.span3 { width: 220px; }
/* Multiple declarations, one per line */
.sprite {
display: inline-block;
width: 16px;
height: 15px;
background-image: url(images/sprite.png);
}
.icon { background-position: 0 0; }
.icon-home { background-position: 0 -20px; }
.icon-account { background-position: 0 -40px; }
简写形式的属性声明
在需要显示地设置所有值的情况下,应当尽量限制使用简写形式的属性声明。常见的滥用简写属性声明的情况如下:
大部分情况下,我们不需要为简写形式的属性声明指定所有值。例如,HTML 的 heading 元素只需要设置上、下边距(margin)的值,因此,在必要的时候,只需覆盖这两个值就可以。过度使用简写形式的属性声明会导致代码混乱,并且会对属性值带来不必要的覆盖从而引起意外的副作用。
MDN(Mozilla Developer Network)上一片非常好的关于shorthand properties 的文章,对于不太熟悉简写属性声明及其行为的用户很有用。
/* Bad example */
.element {
margin: 0 0 10px;
background: red;
background: url(images/"image.jpg");
border-radius: 3px 3px 0 0;
}
/* Good example */
.element {
margin-bottom: 10px;
background-color: red;
background-image: url(images/"image.jpg");
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
Less 和 Sass 中的嵌套
避免非必要的嵌套。这是因为虽然你可以使用嵌套,但是并不意味着应该使用嵌套。只有在必须将样式限制在父元素内(也就是后代选择器),并且存在多个需要嵌套的元素时才使用嵌套。
// Without nesting
.table > thead > tr > th { }
.table > thead > tr > td { }
// With nesting
.table > thead > tr {
> th { }
> td { }
}
注释
代码是由人编写并维护的。请确保你的代码能够自描述、注释良好并且易于他人理解。好的代码注释能够传达上下文关系和代码目的。不要简单地重申组件或 class 名称。
对于较长的注释,务必书写完整的句子;对于一般性注解,可以书写简洁的短语。
/* Bad example */
/* Modal header */
.modal-header {
...
}
/* Good example */
/* Wrapping element for .modal-title and .modal-close */
.modal-header {
...
}
class 命名
在为 Sass 和 Less 变量命名是也可以参考上面列出的各项规范。
/* Bad example */
.t { ... }
.red { ... }
.header { ... }
/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }
选择器
扩展阅读:
/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }
/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }
代码组织
/*
* Component section heading
*/
.element { ... }
/*
* Component section heading
*
* Sometimes you need to include optional context for the entire component. Do that up here if it's important enough.
*/
.element { ... }
/* Contextual sub-component or modifer */
.element-heading { ... }
编辑器配置
将你的编辑器按照下面的配置进行设置,以避免常见的代码不一致和差异:
参照文档并将这些配置信息添加到项目的 .editorconfig 文件中。例如:Bootstrap 中的 .editorconfig 实例。更多信息请参考 about EditorConfig。
• 会计侵占930万公款打赏“冯提莫” 被判刑7年 2019-04-26
• 违规售房!海南五指山3家房地产中介公司被通报 ——凤凰网房产北京 2019-04-26
• 端午小长假 我省北中部有雨 2019-04-26
• 进不了朋友圈,身份认同难。 2019-04-25
• 全省首条民国风情旅游专线湖州德清“开跑” 2019-04-25
• 人民日报评论员:中国梦归根到底是人民的梦 2019-04-25
• 回复@无名小卒也:我只是针对过去的“计划供应”不能很好的满足人们的需求来谈问题,并未否认计划经济,计划经济在市场经济时代,已经转化为政府职能 2019-04-24
• 人人都能享用绿豆汤吗 关于绿豆汤的禁忌你得知道 2019-04-24
• 你总是肆意歪曲客观事实及其规律而满脑胡思乱想,所以才死抱着相对论旧谬误不放,肆意诋毁科学新真理,这才真是“蚍蜉撼树也”! 2019-04-24
• 开训即开战!新疆万名官兵练兵备战 场面震撼! 2019-04-23
• 同里水乡有名园文章中国国家地理网 2019-04-23
• 内蒙古蒙草生态环境(集团)股份有限公司获第十二届人民企业社会责任奖年度环保奖 2019-04-23
• 厉害!国内首个“光伏停车位”亮相重庆 黑天儿倒车也不怕 2019-04-22
• 河北巨鹿38万人参保长期护理险 2019-04-22
• 邯郸“廉政诊所”筑起基层首道廉政防线 2019-04-22
• 166| 343| 260| 425| 584| 894| 900| 840| 18| 767|
|
__label__pos
| 0.556714 |
Scenarios Methods
Name
Returns
Description
Add
Scenario
Method. Parameters: Name As String, ChangingCells, [Values], [Comment], [Locked], [Hidden]. Adds a scenario to the collection. The Name parameter specifies the name of the scenario. See the Scenario object for a description of the parameters
CreateSummary
Variant
Method. Parameters: ReportType As XlSummaryReport-Type, [ResultCells]. Creates a worksheet containing a summary of all the scenarios of the parent worksheet. The ReportType parameter can specify the report type. The ResultCells parameter can be a range of cells containing the formulas related to the changing cells
Merge
Variant
Method. Parameters: Source. Merges the scenarios in the Source parameter into the current worksheet
0 0
Post a comment
|
__label__pos
| 0.640882 |
If the 5th and 12th terms of an A.P. are 30 and 65 respectively,
Question:
If the 5th and 12th terms of an A.P. are 30 and 65 respectively, what is the sum of first 20 terms?
Solution:
We have;
$a_{5}=30$
$\Rightarrow a+(5-1) d=30$
$\Rightarrow a+4 d=30 \quad \ldots(\mathrm{i})$
Also, $a_{12}=65$
$\Rightarrow a+(12-1) d=65$
$\Rightarrow a+11 d=65 \quad \ldots \ldots($ ii $)$
Solving (i) and (ii), we get:
$7 d=35$
$\Rightarrow d=5$
Putting the value of $d$ in (i), we get:
$a+4 \times 5=30$
$\Rightarrow a=10$
$\therefore S_{20}=\frac{20}{2}[2 \times 10+(20-1) \times 5]$
$\Rightarrow S_{20}=10[2 \times 10+(20-1) \times 5]$
$\Rightarrow S_{20}=1150$
Leave a comment
Close
faculty
Click here to get exam-ready with eSaral
For making your preparation journey smoother of JEE, NEET and Class 8 to 10, grab our app now.
Download Now
|
__label__pos
| 0.95001 |
(* ========================================================================= *) (* Part 2: Transcription of Tobias's paper. *) (* ========================================================================= *) parse_as_infix("<<",(12,"right"));; (* ------------------------------------------------------------------------- *) (* Wellfounded part of a relation. *) (* ------------------------------------------------------------------------- *) let WFP_RULES,WFP_INDUCT,WFP_CASES = new_inductive_definition `!x. (!y. y << x ==> WFP(<<) y) ==> WFP(<<) x`;; (* ------------------------------------------------------------------------- *) (* Wellfounded part induction. *) (* ------------------------------------------------------------------------- *) let WFP_PART_INDUCT = prove (`!P. (!x. x IN WFP(<<) /\ (!y. y << x ==> P(y)) ==> P(x)) ==> !x:A. x IN WFP(<<) ==> P(x)`, GEN_TAC THEN REWRITE_TAC[IN] THEN STRIP_TAC THEN ONCE_REWRITE_TAC[TAUT `a ==> b = a ==> a /\ b`] THEN MATCH_MP_TAC WFP_INDUCT THEN ASM_MESON_TAC[WFP_RULES]);; (* ------------------------------------------------------------------------- *) (* A relation is wellfounded iff WFP is the whole universe. *) (* ------------------------------------------------------------------------- *) let WFP_WF = prove (`WF(<<) = (WFP(<<) = UNIV:A->bool)`, EQ_TAC THENL [REWRITE_TAC[WF_IND; EXTENSION; IN; UNIV] THEN MESON_TAC[WFP_RULES]; DISCH_TAC THEN MP_TAC WFP_PART_INDUCT THEN ASM_REWRITE_TAC[IN; UNIV; WF_IND]]);; (* ------------------------------------------------------------------------- *) (* The multiset order. *) (* ------------------------------------------------------------------------- *) let morder = new_definition `morder(<<) N M = ?M0 a K. (M = M0 munion (msing a)) /\ (N = M0 munion K) /\ (!b. b min K ==> b << a)`;; (* ------------------------------------------------------------------------- *) (* We separate off this part from the proof of LEMMA_2_1. *) (* ------------------------------------------------------------------------- *) let LEMMA_2_0 = prove (`morder(<<) N (M0 munion (msing a)) ==> (?M. morder(<<) M M0 /\ (N = M munion (msing a))) \/ (?K. (N = M0 munion K) /\ (!b:A. b min K ==> b << a))`, GEN_REWRITE_TAC LAND_CONV [morder] THEN DISCH_THEN(EVERY_TCL (map X_CHOOSE_THEN [`M1:(A)multiset`; `b:A`; `K:(A)multiset`]) STRIP_ASSUME_TAC) THEN ASM_CASES_TAC `b:A = a` THENL [DISJ2_TAC THEN UNDISCH_THEN `b:A = a` SUBST_ALL_TAC THEN EXISTS_TAC `K:(A)multiset` THEN ASM_MESON_TAC[MUNION_11]; DISJ1_TAC] THEN SUBGOAL_THEN `?M2. M1 = M2 munion (msing(a:A))` STRIP_ASSUME_TAC THENL [EXISTS_TAC `M1 mdiff (msing(a:A))` THEN MAP_EVERY MATCH_MP_TAC [MIN_MDIFF; MUNION_INUNION] THEN UNDISCH_TAC `M0 munion (msing a) = M1 munion (msing(b:A))` THEN ASM_REWRITE_TAC[MEXTENSION; MUNION; MSING; min] THEN DISCH_THEN(MP_TAC o SPEC `a:A`) THEN ASM_REWRITE_TAC[] THEN ARITH_TAC; ALL_TAC] THEN EXISTS_TAC `M2 munion K:(A)multiset` THEN ASM_REWRITE_TAC[MUNION_AC] THEN REWRITE_TAC[morder] THEN MAP_EVERY EXISTS_TAC [`M2:(A)multiset`; `b:A`; `K:(A)multiset`] THEN UNDISCH_TAC `M0 munion msing (a:A) = M1 munion msing b` THEN ASM_REWRITE_TAC[MUNION_AC] THEN MESON_TAC[MUNION_AC; MUNION_11]);; (* ------------------------------------------------------------------------- *) (* The sequence of lemmas from Tobias's paper. *) (* ------------------------------------------------------------------------- *) let LEMMA_2_1 = prove (`(!M b:A. b << a /\ M IN WFP(morder(<<)) ==> (M munion (msing b)) IN WFP(morder(<<))) /\ M0 IN WFP(morder(<<)) /\ (!M. morder(<<) M M0 ==> (M munion (msing a)) IN WFP(morder(<<))) ==> (M0 munion (msing a)) IN WFP(morder(<<))`, STRIP_TAC THEN REWRITE_TAC[IN] THEN MATCH_MP_TAC WFP_RULES THEN X_GEN_TAC `N:(A)multiset` THEN DISCH_THEN(DISJ_CASES_THEN MP_TAC o MATCH_MP LEMMA_2_0) THENL [ASM_MESON_TAC[IN]; REWRITE_TAC[LEFT_IMP_EXISTS_THM]] THEN SPEC_TAC(`N:(A)multiset`,`N:(A)multiset`) THEN ONCE_REWRITE_TAC[SWAP_FORALL_THM] THEN MATCH_MP_TAC MULTISET_INDUCT THEN REPEAT STRIP_TAC THEN RULE_ASSUM_TAC(REWRITE_RULE[MUNION_ASSOC; MIN_MUNION; MIN_MSING]) THEN ASM_MESON_TAC[IN; MUNION_EMPTY]);; let LEMMA_2_2 = prove (`(!M b. b << a /\ M IN WFP(morder(<<)) ==> (M munion (msing b)) IN WFP(morder(<<))) ==> !M. M IN WFP(morder(<<)) ==> (M munion (msing a)) IN WFP(morder(<<))`, STRIP_TAC THEN MATCH_MP_TAC WFP_PART_INDUCT THEN REPEAT STRIP_TAC THEN MATCH_MP_TAC LEMMA_2_1 THEN ASM_REWRITE_TAC[]);; let LEMMA_2_3 = prove (`WF(<<) ==> !a M. M IN WFP(morder(<<)) ==> (M munion (msing a)) IN WFP(morder(<<))`, REWRITE_TAC[WF_IND] THEN DISCH_THEN MATCH_MP_TAC THEN MESON_TAC[LEMMA_2_2]);; let LEMMA_2_4 = prove (`WF(<<) ==> !M. M IN WFP(morder(<<))`, DISCH_TAC THEN MATCH_MP_TAC MULTISET_INDUCT THEN CONJ_TAC THENL [REWRITE_TAC[IN] THEN MATCH_MP_TAC WFP_RULES THEN REWRITE_TAC[morder; MUNION_MEMPTY]; ASM_SIMP_TAC[LEMMA_2_3]]);; (* ------------------------------------------------------------------------- *) (* Hence the final result. *) (* ------------------------------------------------------------------------- *) let MORDER_WF = prove (`WF(<<) ==> WF(morder(<<))`, SIMP_TAC[WFP_WF; EXTENSION; IN_UNIV; LEMMA_2_4]);;
|
__label__pos
| 0.999907 |
enum (C# Reference)
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.
enum Day {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Enumerators can use initializers to override the default values, as shown in the following example.
enum Day {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
In this enumeration, the sequence of elements is forced to start from 1 instead of 0. However, including a constant that has the value of 0 is recommended. For more information, see Enumeration Types.
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.
enum Day : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
A variable of an enumeration type can be assigned any value in the range of the underlying type; the values are not limited to the named constants.
The default value of an enum E is the value produced by the expression (E)0.
Note
An enumerator cannot contain white space in its name.
The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is necessary to convert from enum type to an integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int by using a cast to convert from enum to int.
int x = (int)Day.Sun;
When you apply System.FlagsAttribute to an enumeration that contains elements that can be combined with a bitwise OR operation, the attribute affects the behavior of the enum when it is used with some tools. You can notice these changes when you use tools such as the Console class methods and the Expression Evaluator. (See the third example.)
Robust programming
Just as with any constant, all references to the individual values of an enum are converted to numeric literals at compile time. This can create potential versioning issues as described in Constants.
Assigning additional values to new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependent source code. Enum values often are used in switch statements. If additional elements have been added to the enum type, the default section of the switch statement can be selected unexpectedly.
If other developers use your code, you should provide guidelines about how their code should react if new elements are added to any enum types.
Example
In the following example, an enumeration, Day, is declared. Two enumerators are explicitly converted to integer and assigned to integer variables.
public class EnumTest
{
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int x = (int)Day.Sun;
int y = (int)Day.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
/* Output:
Sun = 0
Fri = 5
*/
Example
In the following example, the base-type option is used to declare an enum whose members are of type long. Notice that even though the underlying type of the enumeration is long, the enumeration members still must be explicitly converted to type long by using a cast.
public class EnumTest2
{
enum Range : long { Max = 2147483648L, Min = 255L };
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
/* Output:
Max = 2147483648
Min = 255
*/
Example
The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration.
// Add the attribute Flags or FlagsAttribute.
[Flags]
public enum CarOptions
{
// The flag for SunRoof is 0001.
SunRoof = 0x01,
// The flag for Spoiler is 0010.
Spoiler = 0x02,
// The flag for FogLights is 0100.
FogLights = 0x04,
// The flag for TintedWindows is 1000.
TintedWindows = 0x08,
}
class FlagTest
{
static void Main()
{
// The bitwise OR of 0001 and 0100 is 0101.
CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
// Because the Flags attribute is specified, Console.WriteLine displays
// the name of each enum element that corresponds to a flag that has
// the value 1 in variable options.
Console.WriteLine(options);
// The integer value of 0101 is 5.
Console.WriteLine((int)options);
}
}
/* Output:
SunRoof, FogLights
5
*/
Comments
If you remove Flags, the example displays the following values:
5
5
C# language specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
See also
|
__label__pos
| 0.996342 |
DEV Community
loading...
Demystifying Tail Call Optimization
Rohit Awate
Microsoft Student Partner | Developer | CS Undergrad
・8 min read
main
Originally published on my personal blog.
Tail call optimization (a.k.a. tail call elimination) is a technique used by language implementers to improve the recursive performance of your programs. It is a clever little trick that eliminates the memory overhead of recursion. In this post, we'll talk about how recursion is implemented under the hood, what tail recursion is and how it provides a chance for some serious optimization.
Recursion 101
If you're familiar with function call stacks and recursion, feel free to skip this section.
Most languages use a stack to keep track of function calls. Let's take a very simple example: a "hello, world" program in C.
#include <stdio.h>
int main()
{
printf("hello, world!\n");
return 0;
}
Every function call in your program gets its own frame pushed onto the stack. This frame contains the local data of that call. When you execute the above program, the main function would be the first frame on the stack, since that's where your program begins execution. The topmost frame in the stack is the one currently being executed. After it completes execution, it is popped from the stack and the bottom frame resumes execution.
main
In our example, main in turn calls printf, another function, thereby pushing a new frame onto the stack. This frame will contain printf's local data. Once printf completes execution, its frame is popped and control returns to the main frame.
printf
Recursive functions do the same. Every recursive call gets its own frame on the stack. Here's a horrible example of a recursive function which prints "hello" n times:
// hello_recursive.c
void hello(int n)
{
if (n == 0) return;
printf("hello\n");
hello(n - 1);
}
int main()
{
hello(2);
return 0;
}
The above code gives the following output:
hello
hello
The function call stack will be something like this:
hello
The first two calls will print out "hello" and make recursive calls with n - 1. Once we hit the last call with n = 0, we begin unwinding the stack.
Now imagine that we wish to print "hello" a million times. We'll need a million stack frames! I tried this out and my program ran out of memory and crashed. Thus, recursion requires O(n) space complexity, n being the number of recursive calls. This is bad news, since recursion is usually a natural, elegant solution for many algorithms and data structures. However, memory poses a physical limit on how tall (or deep, depending on how you look at it) your stack grows. Iterative algorithms are usually far more efficient, since they eliminate the overhead of multiple stack frames. But they can grow unwieldy and complex.
Tail Recursion
Now that we've understood what recursion is and what its limitations are, let's look at an interesting type of recursion: tail recursion.
Whenever the recursive call is the last statement in a function, we call it tail recursion. However, there's a catch: there cannot be any computation after the recursive call. Our hello_recursive.c example is tail recursive, since the recursive call is made at the very end i.e. tail of the function, with no computation performed after it.
...
hello(n - 1);
}
Since this example is plain silly, let's take a look at something serious: Fibonacci numbers. Here's a non tail-recursive variant:
// Returns the nth Fibonacci number.
// 1 1 2 3 5 8 13 21 34 ...
int fib(int n)
{
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
You might argue that this is tail recursive, since the recursive calls appear at the end of the function. However, the results of the calls are added after they return. Thus, fib is not tail recursive.
Here's the tail-recursive variant:
int fib_tail(int n, int a, int b)
{
if (n == 0)
return a;
if (n == 1)
return b;
return fib_tail(n - 1, b, a + b);
}
The recursive call appears last and there are no computations following it. Cool.
You may be thinking, "Hmm, tail recursion is interesting, but what is the point of this?". Turns out, it is more than just a way of writing recursive functions. It opens up the possibility for some clever optimization.
Tail Call Optimization
Tail call optimization reduces the space complexity of recursion from O(n) to O(1). Our function would require constant memory for execution. It does so by eliminating the need for having a separate stack frame for every call.
If a function is tail recursive, it's either making a simple recursive call or returning the value from that call. No computation is performed on the returned value. Thus, there is no real need to preserve the stack frame for that call. We won't need any of the local data once the tail recursive call is made: we don't have any more statements or computations left. We can simply modify the state of the frame as per the call arguments and jump back to the first statement of the function. No need to push a new stack frame! We can do this over and over again with just one stack frame!
Let's look at our example with the non tail-recursive fib function. To find out the 3rd Fibonacci number, we'd do:
...
int third_fib = fib(3);
...
Assuming right-to-left precedence (i.e. the direction in which an expression is evaluated), the call stack would look something like this:
fib
Quite large, isn't it? Imagine the size of the stack for finding out a later Fibonacci number! The problem here is that all the stack frames need to be preserved. You may use one of the local variables in the addition and hence the compiler needs to keep the frames around. If you look at the assembled output of this program, you'll see a call instruction for the fib function.
You can use the -S flag on GCC to output the assembly code. I've deliberately used the -O2 flag which uses the 2nd level of optimization among GCC's 0-3 levels. O2 enables tail call optimization. If you're not familiar with assembly, use GCC's -fverbose-asm flag while compiling. It adds your C code as comments before its corresponding assembled output. Here's the final command, which will produce a .s file:
gcc fib.c -S -O2 -fverbose-asm
This is what our tail call translates to:
# Snippet extracted from: fib.s
# fib.c:7: return fib(n - 1) + fib(n - 2);
movl %ecx, %edi # ivtmp.22,
call fib #
subl $2, %ecx #, ivtmp.22
addl %eax, %edx # _4, add_acc_7
Now, I'm not going to pretend that I understand this completely, because I don't. We only care about the instructions, none of the operand details. Notice the call fib instruction? That's the recursive call. It pushes a new frame onto the stack. Once that completes and pops, we have our addition instruction. Thus, we conclude that even at the 2nd level of optimization, the recursive calls cannot be eliminated, thanks to the addition.
...
return fib_tail(n - 1, b, a + b);
}
Let's take a look at our tail recursive Fibonacci function, fib_tail. Once the above recursive call is made, there's no need to keep the local data around. There's no computation following the statement and it's simply returning the value returned by the recursive call; we could do that straight from the recursive call.
This presents an opportunity to simply replace the values of the local n, a and b variables with the ones used in the recursive call. Instead of a call instruction like before, the compiler can simply redirect the flow of execution to the first instruction in the function, effectively emulating a recursive call. But, without the overhead of one! Basically, the compiler goes:
gif
This is how the call stack would look like:
fib_tail
You don't have to take my word for it, let's look at the assembler output for fib_tail. We compile the same way as before:
gcc fib_tail.c -S -O2 -fverbose-asm
For our tail recursive call, I see the following snippets of assembly:
# fib_tail.c:11: return fib(n - 1, b, a + b);
movl %eax, %edx # <retval>, b
# fib_tail.c:11: return fib(n - 1, b, a + b);
leal (%rsi,%rdx), %eax #, <retval>
# fib_tail.c:11: return fib(n - 1, b, a + b);
leal (%rcx,%rdx), %esi #, _5
# fib_tail.c:11: return fib(n - 1, b, a + b);
movl %esi, %edx # _5, b
As I said, I don't really understand assembly, but we're just checking if we've eliminated the call fib recursive calls. I'm not really sure how GCC is redirecting the control flow. What matters, however, is that there are no call fib instructions in the code. That means there are no recursive calls. The tail call has been eliminated. Feel free to dive into the assembly and verify for yourself.
chandler dancing gif
Support
• We've been using C in this post since GCC and Clang both support tail call optimization (TCO).
• For C++, the case holds with Microsoft's Visual C++ also offering support.
• Java and Python do not support TCO with the intention of preserving the stack trace for debugging. Some internal Java classes also rely on the number of stack frames. Python's BDFL, Guido van Rossum, has explicitly stated that no Python implementations should support TCO.
• Kotlin even comes with a dedicated tailrec keyword which converts recursive functions to iterative ones, since the JVM (Kotlin compiles to JVM bytecode) doesn't support TCO.
• TCO is part of ECMAScript 6 i.e. the JavaScript specification, however, only Safari's JavaScriptCore engine supports TCO. Chrome's V8 retracted support for TCO.
• C# does not support TCO, however, the VM it runs within, Common Language Runtime (CLR) supports TCO.
• Functional languages such as Haskell, F#, Scala and Elixir support TCO.
It appears that support for TCO is more of an ideological choice for language implementers, rather than a technical one. It does manipulate the stack in ways the programmer would not expect and hence makes debugging harder. Refer the documentation of the specific implementation of your favorite language to check if it supports tail call optimization.
Conclusion
I hope you understood the idea and techniques behind TCO. I guess the takeaway here is to prefer iterative solutions over recursive ones (that is almost always a good idea, performance-wise). If you absolutely need to use recursion, try to analyze how big your stack would grow with a non-tail call.
If both of these conditions don't work for you and your language implementation supports tail call optimization, go for it. Keep in mind that debugging will get harder so you might want to turn off TCO in development and only enable it for production builds which are thoroughly tested.
That's it for today, see you in the next post!
Discussion (2)
Collapse
stefanct profile image
s.t.
Little nitpick: "Assuming right-to-left precedence (i.e. the direction in which an expression is evaluated)" does not specify the order in which the functions are called. This is often stated (even in books) but wrong. The chosen order is implementation (aka compiler) specific and independent from the order their results are then used in the caller.
Collapse
anshulnegitc profile image
Anshul Negi
well written
keep it up...
One question, if I add a local variable to a tail recursive function then will it allocate separate stack frame for every call?
|
__label__pos
| 0.532552 |
Threaded View
1. #1
Ext JS Premium Member
Join Date
Dec 2010
Location
Hamburg, Germany
Posts
191
Answers
1
Vote Rating
6
winkelmann is on a distinguished road
0
Default Unanswered: Collapsing panel breaks in hbox layout?
Unanswered: Collapsing panel breaks in hbox layout?
Hi there,
I'm having some strange problem with collapsing panels within hbox layout, I'm not sure if it's a but or if I'm simply doing something wrong. In the following example, I can't seem to get the collapsible panel to uncollapse, the header seems to stay the height it was before collapsing.
Code:
Ext.widget('window',{
title: 'test collapse',
width: 500,
height: 300,
layout: {
type: 'hbox',
align: 'stretch'
},
items: [{
title: 'should not collapse',
collapsible: true,
collapseDirection: 'left',
flex: 1
},{
title: 'test',
flex: 1
}]
}).show();
Any help is appreciated
Attached Images
film izle
hd film izle
film sitesi
takipci kazanma sitesi
takipci kazanma sitesi
güzel olan herşey
takipci alma sitesi
komik eğlenceli videolar
|
__label__pos
| 0.976471 |
Hi,
Having joined the KS scenario for the first time, I find it annoying having to maintain a separate excel sheet with artifacts numbers and secondary powers and constantly synchronizing with the artifact sheet in jOverseer, for new artifacts picked up or lost.
Also its annoying that I have to go through all turns to collect the data from "Research artifacts", this should easily be collected by jOverseer just like all the other data being imported.
I dont understand why this is needed when jOverseer has its own artifact list which is updated from turn import. The only problem is that the fields for artifact number and secondary powers are locked ??? Why is that ?
So I have a request for the next update to jOverseer:
* Open op fields for artifact number and secondary power, so that they can be edited each game
* Create a new functionality that import the data for "Reseacch Artifact", so you can see it it one tab or just import it directly into the artifact list, so its also updated with secondary powers !
BR
Kim A
|
__label__pos
| 0.950886 |
Solved
Manual Reset Users Password
Posted on 2013-11-19
3
378 Views
Last Modified: 2013-11-25
I currently have a site where I administer users and their account. On my Admin dashboard I want to be able to reset their user's password to whatever I type without knowing the users current password. Below is my coding, I want to either be able to get the user's current password and then change it to whatever I enter in the tb_PWOverride textbox or if that isn't possible I want to reset their password, and get the hashed password and change it to whatever I type in the tb_PWOverride textbox.
the textbox's tb_SecQuest, and tb_SecAns are text boxs I am using to update the security question and answer. That part of the procedure is at least working right now.
protected void btn_profile_Update_Click(object sender, EventArgs args)
{
try
{
MembershipUser u = Membership.GetUser(ddl_AllUsers.SelectedValue);
//string tempPswd = u.ResetPassword(); ------I would use this line only if I reset
string oldPswd = u.GetPassword();
u.ChangePassword(oldPswd, tb_PWOverride.Text);
Boolean result = u.ChangePasswordQuestionAndAnswer(tb_PWOverride.Text, tb_SecQuest.Text, tb_SecAns.Text);
if (result)
Msg.Text = "Password Question and Answer has been updated.";
else
Msg.Text = "Password Question and Answer was not updated.";
}
catch (Exception )
{
Msg.Text = "Change Failed. Please re-enter your values and try again.";
}
}
}
}
Open in new window
0
Comment
Question by:Shade22
• 2
3 Comments
LVL 52
Expert Comment
by:Carl Tawn
ID: 39660365
If you call ResetPassword() on the User object it should generate a new password and return it to you. You can then feed that into the ChangePassword() method to change it.
0
Accepted Solution
by:
Shade22 earned 0 total points
ID: 39662283
Sorry, I forgot to close this since I found my own solution. The main issue was changing the user's password, secret question, and answer in one procedure. With the need of current password to change the secret question and answer and the need of current password to reset or change the current password I had to use 2 providers. Provider#1 is set to requiresQuestionAndAnswer="true" and provider#2 is set to requiresQuestionAndAnswer="false". I use provider#2 to reset the password, and then provider#1 to change the secret question and answer.
protected void btn_profile_Update_Click(object sender, EventArgs args)
{
try
{
MembershipUser u = Membership.GetUser(ddl_AllUsers.SelectedValue);
MembershipUser mu = Membership.Providers["Provider#2"].GetUser(ddl_AllUsers.SelectedValue, true);
string tempPswd = mu.ResetPassword();
u.ChangePassword(tempPswd, tb_PWOverride.Text);
Boolean result = u.ChangePasswordQuestionAndAnswer(tb_PWOverride.Text, tb_SecQuest.Text, tb_SecAns.Text);
if (result)
Msg.Text = "Password Quesiton and Answer has been updated.";
else
Msg.Text = "Password Question and Answer was not updated.";
}
catch (Exception )
{
Msg.Text = "Change Failed. Please re-enter your values and try again.";
}
}
Open in new window
0
Author Closing Comment
by:Shade22
ID: 39674047
It works.
0
Featured Post
Space-Age Communications Transitions to DevOps
ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.
Question has a verified solution.
If you are experiencing a similar issue, please ask a related question
Suggested Solutions
Title # Comments Views Activity
ASP.NET MVC - Views 3 38
C# XML Get Values 4 33
C# Windows Form Navigation - Total Beginner 9 34
Multi-Column Repeater 3 22
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
679 members asked questions and received personalized solutions in the past 7 days.
Join the community of 500,000 technology professionals and ask your questions.
Join & Ask a Question
|
__label__pos
| 0.547601 |
Code example for SimpleDateFormat
Methods: parsesetTimeZone
0
* @author Nils Preusker - [email protected]
*
*/
public class OrderUtil {
public static Order createOrderObject() {
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date;
try {
date = formatter.parse("01-01-1970");
} catch (ParseException e) {
// this won't happen, unfortunately we are forced to catch the
// and handle exception though...
date = null;
}
Person person = new Person("John", "Doe", "Mr.", date, "Some Place",
"male", "123456", "[email protected]");
Address address = new Address("The Street", 1, "1234", "The City",
"The State", "The Country");
Order order = new Order("0001", person, address, "debit");
Stop searching for code, let great code find you! Add Codota to your java IDE
|
__label__pos
| 0.951559 |
Jump to: navigation, search
EclipseLink/Examples/JPA/ORMQueries
< EclipseLink | Examples | JPA
Revision as of 15:20, 23 June 2008 by James.sutherland.oracle.com (Talk | contribs) (Combining Query by Example with Expressions)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Queries are the cornerstone of EclipseLink applications. Queries enable you to retrieve information or objects from the database, modify or delete those objects, and create new objects on the database.
Expressions
EclipseLink expressions enable you to specify query search criteria based on the object model. EclipseLink translates the resulting query into SQL and converts the results of the query into objects. EclipseLink provides two public classes to support expression:
• The org.eclipse.persistence.expressions.Expression class represents an expression, which can be anything from a
simple constant to a complex clause with boolean logic. The developer can manipulate, group, and integrate expressions in several ways.
• The org.eclipse.persistence.expressions.ExpressionBuilder class is the factory for constructing new expressions.
A Simple Expression Builder Expression
This example uses the query key lastName to reference the field name L_NAME.
Expression expression = new ExpressionBuilder().get("lastName").equal("Young");
An Expression Using the and() Method
ExpressionBuilder emp = new ExpressionBuilder();
Expression exp1, exp2;
exp1 = emp.get("firstName").equal("Ken");
exp2 = emp.get("lastName").equal("Young");
return exp1.and(exp2);
Custom SQL
The expression framework enables you to define complex queries at the object level. If your application requires a more complex query, use SQL or stored procedure calls to create custom database operations.
SQL Queries
You can provide a SQL string to any query instead of an expression, but the SQL string must return all data required to build an instance of the queried class. The SQL string can be a complex SQL query or a stored procedure call. You can invoke SQL queries through the session read methods or through a read query instance.
A Session Read Object Call Query With Custom SQL
Employee employee = (Employee) session.readObject(Employee.class, new SQLCall("SELECT * FROM EMPLOYEE WHERE EMP_ID = 44"));
A Session Method with Custom SQL
This example queries user and time information.
List rows = session.executeSelectingCall(new SQLCall("SELECT USER, SYSDATE FROM DUAL"));
SQL Data Queries
EclipseLink offers the following data-level queries to read or modify data (but not objects) in the database.
• org.eclipse.persistence.queries.DataReadQuery: for reading rows of data
• org.eclipse.persistence.queries.DirectReadQuery: for reading a single column
• org.eclipse.persistence.queries.ValueReadQuery: for reading a single value
• org.eclipse.persistence.queries.DataModifyQuery: for modifying data
DataReadQuery Example
DataModifyQuery query = new DataModifyQuery();
query.setSQLString("USE SALESDATABASE");
session.executeQuery(query);
DirectReadQuery Example
DirectReadQuery query = new DirectReadQuery();
query.setSQLString("SELECT EMP_ID FROM EMPLOYEE");
List ids = (List) session.executeQuery(query);
Stored Procedure Calls
You can provide a StoredProcedureCall object to any query instead of an expression or SQL string, but the procedure must return all data required to build an instance of the class you query.
A Read All Query With a Stored Procedure
ReadAllQuery readAllQuery = new ReadAllQuery(Employee.class);
call = new StoredProcedureCall();
call.setProcedureName("Read_All_Employees");
readAllQuery.useNamedCursorOutputAsResultSet("RESULT_CURSOR");
readAllQuery.setCall(call);
List employees = (List) session.executeQuery(readAllQuery);
JPQL
JPQL (was EJBQL) is a query language that is similar to SQL, but differs because it presents queries from an object model perspective and includes path expressions that enable navigation over the relationships defined for entity beans and dependent objects. Although JPQL is usually associated with Enterprise JavaBeans (EJBs), EclipseLink enables you to use JPQL with regular Java objects as well. In EclipseLink, JPQL enables users to declare queries, using the attributes of each abstract entity bean in the object model. This offers the following advantages:
• You do not need to know the database structure (tables, fields).
• You can use relationships in a query to provide navigation from attribute to
attribute.
• You can construct queries using the attributes of the entity beans instead of
using database tables and fields.
• JPQL queries are portable because they are database-independent.
• You can use SELECT to specify the query reference class (the class or entity
bean you are querying against).
A Simple ReadAllQuery Using JPQL
ReadAllQuery query = new ReadAllQuery(Employee.class);
query.setJPQLString("SELECT OBJECT(emp) FROM Employee emp");List employees = (List)session.executeQuery(query);
A Simple ReadAllQuery Using JPQL and Passing Arguments
This example defines the query similarly to above, but creates, fills, and passes a vector of arguments to the executeQuery method.
// First define the query
ReadAllQuery theQuery = new ReadAllQuery(Employee.class);
query.setJPQLString("SELECT OBJECT(emp) FROM Employee emp WHERE emp.firstName = ?1");
...
// Next define the Arguments
List arguments = new ArrayList();
arguments.add("Bob");
...
// Finally execute the query passing in the arguments
List employees = (List)session.executeQuery(query, arguments);
Query By Example
Query by example enables you to specify queries when you provide sample instances of the persistent objects to be queried. To define a query by example, provide a ReadObjectQuery or a ReadAllQuery with a sample persistent object instance and an optional query by example policy. The sample instance contains the data to query, and the query by example policy contains optional configuration settings, such as the operators to use and the attributes to consider or ignore.
Using Query by Example
This example queries the employee Bob Smith.
ReadObjectQuery query = new ReadObjectQuery();
Employee employee = new Employee();
employee.setFirstName("Bob");
employee.setLastName("Smith");
query.setExampleObject(employee);
Employee result = (Employee) session.executeQuery(query);
Using Query by Example
This example queries across the employee’s address.
ReadAllQuery query = new ReadAllQuery();
Employee employee = new Employee();
Address address = new Address();
address.setCity("Ottawa");
employee.setAddress(address);
query.setExampleObject(employee);
List results = (List) session.executeQuery(query);
Query by Example Policy Using Like
This example uses like for Strings and includes only objects whose salary is greater than zero.
ReadAllQuery query = new ReadAllQuery();
Employee employee = new Employee();
employee.setFirstName("B%");
employee.setLastName("S%");
employee.setSalary(0);
query.setExampleObject(employee);
/* Query by example policy section adds like and greaterThan */
QueryByExamplePolicy policy = new QueryByExamplePolicy();
policy.addSpecialOperation(String.class, "like");
policy.addSpecialOperation(Integer.class, "greaterThan");
policy.alwaysIncludeAttribute(Employee.class, "salary");
query.setQueryByExamplePolicy(policy);
List results = (List) session.executeQuery(query);
Query by Example Policy Using Key Words
This example uses key words for Strings and ignores -1.
ReadAllQuery query = new ReadAllQuery();
Employee employee = new Employee();
employee.setFirstName("bob joe fred");
employee.setLastName("smith mc mac");
employee.setSalary(-1);
query.setExampleObject(employee);
/* Query by example policy section */
QueryByExamplePolicy policy = new QueryByExamplePolicy();
policy.addSpecialOperation(String.class, "containsAnyKeyWords");
policy.excludeValue(-1);
query.setQueryByExamplePolicy(policy);
List results = (List) session.executeQuery(query);
Combining Query by Example with Expressions
ReadAllQuery query = new ReadAllQuery();
Employee employee = new Employee();
employee.setFirstName("Bob");
employee.setLastName("Smith");
query.setExampleObject(employee);
/* This section specifies the expression */
ExpressionBuilder builder = new ExpressionBuilder();
query.setSelectionCriteria(builder.get("salary").between(100000,200000);
List results = (List) session.executeQuery(query);
|
__label__pos
| 0.744173 |
0
I have a <section> tag in which there is <tfoot> tags and many <td> tags.
I want to store the 1st & 4th td elements of a in a Map, but i get index out of bounds exception.
Now, how can we use FindElement or FindElement method on a WebElement itself. Does this find all the child elements? Apologies as i have messed up all my code.
There are 14 tags on the page and i want to retrieve the text of td elements that are inside tfoot tag from each and every section, Product name and price, then store it in a String, String Map. Also, there is lot of whitespace in td element values.
<div>
<table class="right">
<tfoot>
<tr class="product">
<td>Product 1
</td>
<td class="rt">323.00</td>
<td class="rt">
6
</td>
<td class="rt">
6
</td>
<td class="rt">
</td>
</tr>
</tfoot>
</table>
</div>
enter image description here List sectionsList = driver.findElements(By.tagName("section"));
Iterator<WebElement> it = sectionsList.iterator();
while(it.hasnext())
{
System.out.println(itr.next().findElements(By.tagName("tfoot")).get(1).findElements(By.tagName("td")).get(0)
.getText());
Now, i want to store the td values in a Hashmap.
Map<String, String> map1 = new HashMap<String, String>();
for(int i=1; i<sections.size()+1; i++){ map1.put(sectionList.get(i).findElements(By.tagName("tfoot")).get(1).findElements(By.tagName("td")).get(0).getText() , sectionList.get(0).findElements(By.tagName("tfoot")).get(1).findElements(By.tagName("td")).get(3).getText()); }
4
• Post your HTML Dom code reference Jan 20, 2021 at 8:44
• hi, done. thanks.
– nick
Jan 20, 2021 at 9:47
• Please post it as code. Jan 20, 2021 at 10:19
• done. it would be helpful if you could review the code.
– nick
Jan 20, 2021 at 10:45
1 Answer 1
1
for(int i=1; i<sections.size()+1; i++)
Why are you adding 1 to sections size, remove 1
for(int i=1; i<sections.size(); i++)
and also why starting from i=1 ? index starts from 0 to size-1 , so it should be i=0 ?
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.749313 |
5
How All the The negative values which awes functiomh do you know this? 2 and Two I each The four functions positive statements defined two shown are by an negative ...
Question
How All the The negative values which awes functiomh do you know this? 2 and Two I each The four functions positive statements defined two shown are by an negative MUST graphed at right are be true? equation f the ofxherentia} (t)
How All the The negative values which awes functiomh do you know this? 2 and Two I each The four functions positive statements defined two shown are by an negative MUST graphed at right are be true? equation f the ofxherentia} (t)
Answers
HOW DO YOU SEE IT? Using the graph of $f,$
(a) determine whether $d y / d t$ is positive or negative given that $d x / d t$ is negative, and (b) determine whether $d x / d t$ is positive or negative given that $d y / d t$ is positive.
We have a whole sequence of problems. Um that are so some questions about this uh this graph here that I've tried to reproduce from the book, um it's obviously piecewise continuous. It's not smooth because it looks like we have a corner there. So linear here, linear here, but with a constant Y. And then some kind of probably more like a, like a cubic or cortical function. Um Over here. They don't give it, they don't tell us what these are. We could yeah, I think we have enough points. Let's see here, we have 12345 points. We could figure out a quartet polynomial. We probably want to find this slope here. So we could figure out a Quinton polynomial on that word. Have a zero slope here and go through all these points if we wanted to. But that's not what we were asked. So we're just asked a bunch of questions about this. So I'm just gonna go through all of them in this one video, because they're all very much related and there are, you know, I have to do with this this graph here. So the first question is fine. F zero and effort negative six. Well F zero, that's when X equals zero. So we come up here and we're at my at three and then at negative six we're out here and so they've labeled this point here, X is negative six, then why is minus three now they ask us is um is F of three positive or negative? So let's see here F of three is somewhere in this in this region here and so it's positive and it's probably, you know, just again, they didn't label the point but it looks like it's three for this whole region between zero and four. An f of minus minus four, so minus three were at zero minus five, we're at minus two. So if this is indeed a line then minus four were at minus one and then clearly f of my f one of X equals minus four is clearly negative. It's on it's to the left of here. No, they ask us, let's see here. Um for what values of X is F of X zero? Well f of X is why here? So we have zero here, A zero here and zero here. So there's three points. And they are when X is minus three, when X is six and when X is 10 to those three points, then they ask us for what values of X. F greater than zero. Well we can see here that it's greater than zero here and also here. And I should probably say that this should probably change this to just assume that this doesn't get extended. So we have it's greater than equal to 10. Less than equal to 11. So from here to here, right, we have X equals minus 3 to 6. So and they said greater than all. Right. So I should have I should just have greater than it's not equal to um And then from here to here, you know, it goes from 10 to 11 over this region. Little region here, we also have positive values. Then I asked for the what is the domain? Well, assuming that, you know, this doesn't continue on in any way that this is just, you know, it's only defined over this region. The domain goes from X equals minus 62 X equals 11. And they asked us for the range and the range is the span of y values. So it looks like the smallest Y value we have is minus three and the largest value we have is three. So that's the range. Then we'll ask for the X intercepts. The X intercepts are actually just the points where y equals zero. So we have the exact same points here minus three at six and 10. They ask us for what is the wiring rcep? Well, that's when X zero and we see that in X zero. They tell us that why is three? Yeah. And how often does the line why it was gonna have intersected graph? Well, Y equals one half. If we go down um you can see that it's gonna be down something like this. So it looks like about three. And so we know it intersects somewhere here as it this crosses it, we know what intersects somewhere here as that crosses it. And over here at this point this goes from um Y equals zero to Y equals one. So one half is right in between there. So we know what crosses it there too, So that crosses three points. How often does the line cross? Um The graph crossed the line X equals five and I thought why it was five, so this is wrong. And so let's do that, Y equals five. Um No X X equals five. So it just crosses at once. And in fact if it's a function, if it's a function then it can only cross any any constant value of X at one at one point. Otherwise it's not by definition of function. So yeah, process somewhere here if this, well I don't know what kind of curve this is. So I would speculate on what the Y value is there then how for what values of X does F equal three? Well, it looks like, again, assuming this is all horizontal here, it looks like it's F equals three for this entire span here from 0 to 4. Mhm. Than for what values does F equal minus two? Well we have we have a point over here minus five minus two. So we're given that one and we're told this goes through eight minus two. And again this just just never cross comes back down here. So if we look at um for why it goes minus two, we just touched this point here and I'm assuming that's a minimum it appears to be so it doesn't go beyond it somehow. Um you know, doesn't go below. And then over here, so those are the two points X equals minus five and eight. And then for and what interval is the function increasing? What intervals? So obviously it's increasing here, Right. And it's increasing here. So they have yeah. Um And so this region here is minus 6 to 0. It's not increasing here, nor is it decreasing? We'll come back to that later and it looks like from here from 8 to 11. It's also increasing. Did they ask about when there's a decreasing? Well it's decreasing from here to here. And that goes from 4 to 8. And they asked when is a constant? Well that is it's constant between zero and four. And then they asked, when is it non increasing? Okay, so that means constant or decreasing. So basically have the union of this set and this set which is 0 to 8. So from here, other way to here is non increasing. And then they ask if it when is it non decreasing? Well, again that's the intersection of the constant region and this region here, so that winds up being minus 6 to 4. So here to here, it's non decreasing. And then over here, 11 or 8 to 11 it's also increasing or non decreasing. So those are all the questions they ask us about this, this one graph. Um, so hopefully there should be pretty simple for you to do at this point, and hopefully none of this was kind of a surprise, um, to looking at this chart here and in asking all these questions.
In Problem 38. We have two graphs for the function. If the first graph here in the second graffiti for birdie, we want to determine whether D y by D. T is most of or negative. Given that the X by DT is negative, let's go for birthday. We can notice that from the graph given here as X increases why is decreases? This means here we have the oy by the X equals negative. But what is the relation between D. Y by D. X and D. Y by D. T From the general we have deRoy by DT equals de Roy by the X Multiply it by the X by DT the X Boy deity and we have here Dear boy by the X is negative given from the graph and the X by DT is negative given from the problem then negative by a negative which makes the oy. Why did he is posted for the second graph? We cannot desert as X increases. Why is increases which makes doi by the X equals most of value from the chin rule we have doi by DT equals newly by the X but applied by the x by DT from the graph devoid by the X is positive and from the given The X by DT is negative. Then boast of by negative gives a negative value for Bharti we want Do determine bar TV whether the XB GT is negative or busted. Given that doi boy DT equals a positive, we will do the same procedure from the chain rule we have new toy by DT equals divide by the X multiplied by the X by ditty given from the graph D y by D. X is negative and or we can change now because we have we want to get the X from the General The XB GT equals the X by deRoy Multiply it, boy the ex boy Dear boy, What the bloody boy D y by d? T The x by the boy will be also negative for the first graph here because as why increases as well increases exit decrease, then the boy by the X equals negative body. Then, from the graph, we have the x by device, Serie the ex boy deroy equals negative one. The X, by the way, is negative from the graph and d y by D. t s positive given from the problem, then it will be negative. The same concept applies here. The X by DT from the chin rule equals the X by D boy multiplied by D y by D. T. From the grave as y increases X increases, which makes the X by doi is boosted. Then this is boosted from the graph. This is most of from the given. Then the answer will be positive and this is the final answer off our problem.
So we're looking at the graph shown, we want to know um if the points at which points this is true. So we have that the first derivative and second derivatives are positive. Well considering our graph looks something like this, we see that the first derivative is going to be positive at point B. Because the slope is positive there at point C. The slope is positive too. Um at Point D it looks to be zero. The second derivative, though we see it can be concave down here so it can be negative. However, A and B are concave up, so those would both be positive A. And B. And then um they're gonna be negative the opposite one, so A is negative this one right here and E is going to be negative over the second derivative is negative only for both right here. So we would say E. Is our answer for that one. And for the first one our answer was B. So it's our final answer.
All right. See you of different relationship. Got a year? Thanks. Why? According to them, you have some function that looks like these. So here we're assuming that since Izzy the plane. Why does this mean? Why use equal to if I fix so we know. Well, if, uh, what happens with wide? Who is the white team? Positive or negative for but the every city. So how do you know that? How do you know that? So Well, we can, since we have this relationship. Come differentiate both sides equations. We have that divided. We even buy. It's prime on them. But the chill terms? Yeah, X, um said at the y Begin my exit. Them's then the office. But as you can see here in this drawing, they take his thing. Stop off the time line in each point. But he's always Hey, if you said the Chrissy function, so if prime music here. So that, uh, well, already so that if Bryant changes the sign. So for the x City get you, Um oh. If prime changes the side there, it's the the ex. Why? What's this from, uh or? Yeah, 40 years of the what city damn it. Why do people you nearly with you? I know that. No, if, uh, you know why it's positive we start from this being positive. So that means that prosthetic is going to be able to negative to that school. You can vote. See that if Brian is never zero this time for T Rex city Well, well, I want a renegade number. It's a negative number. So positive times negative. It's you. Why did this positive then? Extinct? No, it seemed that we had a something this form. So your help here, X exes? Why Exes? I'm asking that you had something like this. Why she ableto ever fix where oh is? He said So in that case, upon initiation, why we even buy Brian the ex with you? But you know well, if Brian from that drawing if it's always increasing, it's about me is low. But each point it's positive. So if Brian So it's positive. So this sign for Turgut beside for G X city, you'll always be the same. So then if you had the exiting said I work for years. DX city is negative. The negative is a positive number. It's so why keep this thing. Why is that? You know if, uh if possibly why the velocity? Well again, it seems here, toe if crime is there were zero. So we can have that we can divide. Yeah. So if you promise it was the number one of her friends, it's always also posted also was it so Why did he is positive? Positive? Positive. So exit e b. Well, he was so because, all right.
Similar Solved Questions
5 answers
Detemmine the formal charge on each atom in the HSNBF3 following species:b) CH:NHs*SO42
Detemmine the formal charge on each atom in the HSNBF3 following species: b) CH:NHs* SO42...
5 answers
Pant AExpress YOUI answor Js chernical equalion. Enier noreaction lheteteaclon: Idantilyphase5 VourI3co(s) + ZNO; (aq) SH(aq)-3C0 (aq) 2NO(g) + 4H,O() OAchemical leacbon dous nol OCCUI Iox Uds QuestoqSubrntt ,EqnuAnto BrualanyIncorrect; Try Agaln; - attcmpts remaining
Pant A Express YOUI answor Js chernical equalion. Enier noreaction lhete teaclon: Idantily phase5 Vour I3co(s) + ZNO; (aq) SH(aq)-3C0 (aq) 2NO(g) + 4H,O() OAchemical leacbon dous nol OCCUI Iox Uds Questoq Subrntt , EqnuAnto Brualany Incorrect; Try Agaln; - attcmpts remaining...
2 answers
UakatHrert rr'UKnEKnnMentantGntixor Eru tuttiniu1tm? Wt 0mn nor? I4 EEnienxdda marunsnou LAcaE Jhiam Euaramiz0 Dt WILuali30 ILB[ Cn JKre iane AnteenensenmbGkneeem Enou WIuuz0 MDB[ EIOnd ,eninivcmddbir iensuumLon nuiam uoural &ad uunnad Munc L ncueblial Gannoi Ceneeetinr tertu eLaennnfn Wune eorinen EITe cretnaan
Uakat Hrert rr'UKnE Knn Mentant Gntixor Eru tuttiniu1tm? Wt 0mn nor? I4 EEnienxdda marunsnou LAcaE Jhiam Euaramiz0 Dt WILuali30 ILB[ Cn JKre iane AnteenensenmbGkneeem Enou WIuuz0 MDB[ EIOnd ,eninivcmddbir iensuumLon nuiam uoural &ad uunnad Munc L ncueblial Gannoi Ceneeetinr tertu eLaennnfn...
5 answers
Proron encersuniform magnetic fiel ata 90-degree angle: Consldering the proton's motion Tensionmagnetic field; the magnetic force serves as thecentripetal Torcegravitational Corcefrictional forceQUESTION 2the previous question; tne proton $ speed is 7.9 X 10? m/s and the uniform magnetic field has strength 0,036 ` tne radius ofthe proton'$ pathExponent format wiith 3
proron encers uniform magnetic fiel ata 90-degree angle: Consldering the proton's motion Tension magnetic field; the magnetic force serves as the centripetal Torce gravitational Corce frictional force QUESTION 2 the previous question; tne proton $ speed is 7.9 X 10? m/s and the uniform magneti...
5 answers
Solve the given initial value problem for asa vector function of - dr (+j+k) 0 and r(o) 10i 10j 10k dt? t=0
Solve the given initial value problem for asa vector function of - dr (+j+k) 0 and r(o) 10i 10j 10k dt? t=0...
5 answers
3-VSEPR predicts that one of the following molecules has trigonal pyramidal geometry #hdkadral @ paie SO3[COz]?BrFzBFs721 P(CH3)a[NOs]'24
3-VSEPR predicts that one of the following molecules has trigonal pyramidal geometry #hdkadral @ paie SO3 [COz]? BrFz BFs 721 P(CH3)a [NOs]' 24...
5 answers
Question Using Newton's method with Xo 4 to approximate Vi2, find X;_ Round your wer t0 the nearest thousandth:Provide your answer below:
Question Using Newton's method with Xo 4 to approximate Vi2, find X;_ Round your wer t0 the nearest thousandth: Provide your answer below:...
5 answers
That show bacteria killing activities One agent binds to bacterial RNA polymerase and inhibits colli Is being Used study various agcnts transcription To which antibiotic(s) this agent Iikely related?chkrnphcnicolKtmak-lingsttcniouincirncrin Btte ansuttt
that show bacteria killing activities One agent binds to bacterial RNA polymerase and inhibits colli Is being Used study various agcnts transcription To which antibiotic(s) this agent Iikely related? chkrnphcnicol Ktmak-ling sttcniouincir ncrin B tte ansuttt...
5 answers
What was the heavy bombardment, and when did it occur?
What was the heavy bombardment, and when did it occur?...
1 answers
Use the Law of sines or the Law of cosines to solve the triangle. $$B=71^{\circ}, a=21, c=29$$
Use the Law of sines or the Law of cosines to solve the triangle. $$B=71^{\circ}, a=21, c=29$$...
5 answers
Given $f(x)=x^{2}+x(k-1)+k^{2}$, find the range of values of $k$ so that $f(x)>0$ for all real values of $x$.
Given $f(x)=x^{2}+x(k-1)+k^{2}$, find the range of values of $k$ so that $f(x)>0$ for all real values of $x$....
5 answers
Waler nas j nel force An object completely submerged apparent weight equal F t0 theequal t0 Ihe buoyant forcet0 tne real weight equalgreater than the real weightGo I6
waler nas j nel force An object completely submerged apparent weight equal F t0 the equal t0 Ihe buoyant force t0 tne real weight equal greater than the real weight Go I6...
5 answers
Question 7 (1 point) If Isaac is holding 100 kg barbell above his head for 5 s and Jason holds the same 100 kg barbell over his head for 10 $, then Jason has done twice the amount of work as Isaac_TrueFalseQuestion 8 (1 point) A 10 kg mass held 6 m above the Earth will have the same gravitational energy as a 5 kg mass held 12 m above the Earth:TrueFalseQuestion 9 (1 point) Kinetic energy can be negative_TrueFalse
Question 7 (1 point) If Isaac is holding 100 kg barbell above his head for 5 s and Jason holds the same 100 kg barbell over his head for 10 $, then Jason has done twice the amount of work as Isaac_ True False Question 8 (1 point) A 10 kg mass held 6 m above the Earth will have the same gravitational...
5 answers
Fuel Cost A car is driven 15,000 miles a year and gets miles per gallon. Assume that the average fuel cost is $3.48 per gallon. Find the annual cost of fuel as a function of and use this function to complete the table.Who would benefit more from a one-mile-per-gallon increase in fuel efficiency - the driver of a car that gets 15 miles per gallon, or the driver of a car that gets 35 miles per gallon? Explain.
Fuel Cost A car is driven 15,000 miles a year and gets miles per gallon. Assume that the average fuel cost is $3.48 per gallon. Find the annual cost of fuel as a function of and use this function to complete the table. Who would benefit more from a one-mile-per-gallon increase in fuel efficiency ...
1 answers
$2-22$ Differentiate the function. $f(x)=\sqrt[5]{\ln x}$
$2-22$ Differentiate the function. $f(x)=\sqrt[5]{\ln x}$...
5 answers
Q#}In thc following excrcise. delenine / '() fW)= Inlr' - 2x'+Sx) b) f6)-4'(CLO-J)fW
Q#} In thc following excrcise. delenine / '() fW)= Inlr' - 2x'+Sx) b) f6)-4' (CLO-J) fW...
-- 0.019313--
|
__label__pos
| 0.794577 |
14
$\begingroup$
Can we say that Eigenvalues of symmetric orthogonal matrix must be $+1$ and $-1$?
Since eigenvalues of symmetric matrices are real and eigenvalues of orthogonal matrix have unit modulus. Combining both result eigenvalues of symmetric orthogonal matrices must be $+1$ and $-1$.
Please clarify whether I am correct? Is there any other approach to solve this problem?
Thanks
$\endgroup$
0
3 Answers 3
26
$\begingroup$
Yes, you're right. Also note that if $A^\top A=I$ and $A=A^\top$, then $A^2=I$, and now it's immediate that $\pm 1$ are the only possible eigenvalues. (Indeed, applying the spectral theorem, you can now conclude that any such $A$ can only be an orthogonal reflection across some subspace.)
$\endgroup$
0
1
$\begingroup$
Suppose $A$ being symmetric and orthogonal, then we have $A = A^T$ and $A^T A = I$.
Let $\lambda$ be an eigenvalue of $A$. Then we can derive
\begin{align} Ax &= \lambda x \\ A^T A x &= A^T \lambda x \\ x &= A \lambda x \\ \frac{1}{\lambda} x &= Ax = \lambda x\\ \frac{1}{\lambda} &= \lambda \end{align}
So $\lambda$ has to be $\pm 1$.
$\endgroup$
0
$\begingroup$
A symmetric orthogonal matrix is involutory.
Involutory matrices have eigenvalues $\pm 1$ as proved here: Proof that an involutory matrix has eigenvalues 1,-1 and Proving an invertible matrix which is its own inverse has determinant $1$ or $-1$
$\endgroup$
You must log in to answer this question.
Not the answer you're looking for? Browse other questions tagged .
|
__label__pos
| 0.999548 |
GraphQL
graphql/validation
The graphql/validation module fulfills the Validation phase of fulfilling a GraphQL result. You can import either from the graphql/validation module, or from the root graphql module. For example:
import { validate } from 'graphql/validation'; // ES6
var { validate } = require('graphql/validation'); // CommonJS
Overview #
Validation #
validate #
function validate(
schema: GraphQLSchema,
ast: Document,
rules?: Array<any>
): Array<GraphQLError>
Implements the "Validation" section of the spec.
Validation runs synchronously, returning an array of encountered errors, or an empty array if no errors were encountered and the document is valid.
A list of specific validation rules may be provided. If not provided, the default list of rules defined by the GraphQL specification will be used.
Each validation rules is a function which returns a visitor (see the language/visitor API). Visitor methods are expected to return GraphQLErrors, or Arrays of GraphQLErrors when invalid.
Visitors can also supply visitSpreadFragments: true which will alter the behavior of the visitor to skip over top level defined fragments, and instead visit those fragments at every point a spread is encountered.
specifiedRules #
var specifiedRules: Array<(context: ValidationContext): any>
This set includes all validation rules defined by the GraphQL spec
|
__label__pos
| 0.989661 |
Using Mail Merge
In Word Mail Merge is a powerful feature. With Mail Merge Word documents can be used to produce letters, labels, envelopes, and more.
Introduction
By the end of this module, you should be able to:
Using Mail Merge
To use Mail Merge:
The Mail Merge task pane appears and will guide you through the six main steps to complete a mail merge. You will have several decisions to make during the process. The following is an example of how to create a form letter and merge the letter with a data list.
Steps 1-3
To edit a new address list:
Steps 4-6
To insert data from a data list:
Tip The Mail Merge Wizard allows you to complete the mail merge process in a variety of ways. The best way to learn how to use the different functions in Mail Merge is to try to develop several of the different documents—letters, labels, and envelopes—using the different types of data sources.
Challenge!
|
__label__pos
| 0.958155 |
Solving Equations with Variables on Both Sides
Download
1 / 25
10-3 - PowerPoint PPT Presentation
• 159 Views
• Uploaded on
Solving Equations with Variables on Both Sides. 10-3. Course 3. Warm Up. Problem of the Day. Lesson Presentation. Solving Equations with Variables on Both Sides. 10-3. 1. 1. 2 x. 7. 9 x. 8. 16. 4. x. 2. 7. 7. Course 3. Warm Up Solve.
loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation
PowerPoint Slideshow about ' 10-3' - fauve
An Image/Link below is provided (as is) to download presentation
Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.
- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Solving Equations with Variables on Both Sides
10-3
Course 3
Warm Up
Problem of the Day
Lesson Presentation
Solving Equations with Variables on Both Sides
10-3
1
1
2x
7
9x
8
16
4
x
2
7
7
Course 3
Warm Up
Solve.
1.2x + 9x – 3x + 8 = 16
2.–4 = 6x + 22 – 4x
3. + = 5
4. – = 3
x = 1
x = -13
x = 34
x = 50
Solving Equations with Variables on Both Sides
10-3
Course 3
Problem of the Day
An equilateral triangle and a regular pentagon have the same perimeter. Each side of the pentagon is 3 inches shorter than each side of the triangle. What is the perimeter of the triangle?
22.5 in.
Solving Equations with Variables on Both Sides
10-3
Course 3
Learn to solve equations with variables on both sides of the equal sign.
Solving Equations with Variables on Both Sides
10-3
Course 3
Some problems produce equations that have variables on both sides of the equal sign.
Solving an equation with variables on both sides is similar to solving an equation with a variable on only one side. You can add or subtract a term containing a variable on both sides of an equation.
Solving Equations with Variables on Both Sides
10-3
–3x
=
–3
6
–3
Course 3
Additional Example 1A: Solving Equations with Variables on Both Sides
Solve.
A. 4x + 6 = x
4x + 6 = x
– 4x– 4x
Subtract 4x from both sides.
6 = –3x
Divide both sides by –3.
–2 = x
Solving Equations with Variables on Both Sides
10-3
4b
24
=
4
4
Course 3
Additional Example 1B: Solving Equations with Variables on Both Sides
Solve.
B. 9b – 6 = 5b + 18
9b – 6 = 5b + 18
– 5b– 5b
Subtract 5b from both sides.
4b – 6 = 18
+ 6+ 6
Add 6 to both sides.
4b = 24
Divide both sides by 4.
b = 6
Solving Equations with Variables on Both Sides
10-3
9w + 3 = 9w + 7
Combine like terms.
– 9w– 9w
Subtract 9w from both sides.
Course 3
Additional Example 1C: Solving Equations with Variables on Both Sides
Solve.
C. 9w + 3 = 5w + 7 + 4w
9w + 3 = 5w + 7 + 4w
3 ≠ 7
No solution. There is no number that can be substituted for the variable w to make the equation true.
Solving Equations with Variables on Both Sides
10-3
–4x
=
–4
8
–4
Course 3
Try This: Example 1A
Solve.
A. 5x + 8 = x
5x + 8 = x
– 5x– 5x
Subtract 4x from both sides.
8 = –4x
Divide both sides by –4.
–2 = x
Solving Equations with Variables on Both Sides
10-3
Course 3
Try This: Example 1B
Solve.
B. 3b – 2 = 2b + 12
3b – 2 = 2b + 12
– 2b– 2b
Subtract 2b from both sides.
b – 2 = 12
+ 2+ 2
Add 2 to both sides.
b = 14
Solving Equations with Variables on Both Sides
10-3
3w + 1 = 3w + 8
Combine like terms.
– 3w– 3w
Subtract 3w from both sides.
Course 3
Try This: Example 1C
Solve.
C. 3w + 1 = 10w + 8 – 7w
3w + 1 = 10w + 8 – 7w
1 ≠ 8
No solution. There is no number that can be substituted for the variable w to make the equation true.
Solving Equations with Variables on Both Sides
10-3
Course 3
To solve multistep equations with variables on both sides, first combine like terms and clear fractions. Then add or subtract variable terms to both sides so that the variable occurs on only one side of the equation. Then use properties of equality to isolate the variable.
Solving Equations with Variables on Both Sides
10-3
8z8
=
8
8
Course 3
Additional Example 2A: Solving Multistep Equations with Variables on Both Sides
Solve.
A. 10z – 15 – 4z = 8 – 2z - 15
10z – 15 – 4z = 8 – 2z – 15
6z – 15 = –2z – 7
Combine like terms.
+ 2z+ 2z
Add 2z to both sides.
8z – 15 = – 7
+ 15+15
Add 15 to both sides.
8z = 8
Divide both sides by 8.
z = 1
Solving Equations with Variables on Both Sides
10-3
7
10
7
10
7
10
7
10
3y
5
3y
5
3y
5
3y
5
y
5
y
5
y
5
y
5
3
4
3
4
3
4
3
4
+ – = y –
20( ) = 20( )
+ – y –
20() + 20( ) – 20( )= 20(y) – 20( )
Course 3
Additional Example 2B: Solving Multistep Equations with Variables on Both Sides
B.
+ – = y –
Multiply by the LCD.
4y + 12y – 15 = 20y – 14
16y – 15 = 20y – 14
Combine like terms.
Solving Equations with Variables on Both Sides
10-3
4y
4
–1
-1
4
= y
=
4
Course 3
Additional Example 2B Continued
16y – 15 = 20y – 14
– 16y– 16y
Subtract 16y from both sides.
–15 = 4y – 14
+ 14+ 14
Add 14 to both sides.
–1 = 4y
Divide both sides by 4.
Solving Equations with Variables on Both Sides
10-3
10z50
=
10
10
Course 3
Try This: Example 2A
Solve.
A. 12z – 12 – 4z = 6 – 2z + 32
12z – 12 – 4z = 6 – 2z + 32
8z – 12 = –2z + 38
Combine like terms.
+ 2z+ 2z
Add 2z to both sides.
10z – 12 = + 38
+ 12+12
Add 12 to both sides.
10z = 50
Divide both sides by 10.
z = 5
Solving Equations with Variables on Both Sides
10-3
6
8
6
8
6
8
6
8
5y
6
5y
6
5y
6
5y
6
y
4
y
4
y
4
y
4
3
4
3
4
3
4
3
4
+ + = y –
24( ) = 24( )
+ + y –
24() + 24( )+ 24( )= 24(y) – 24( )
Course 3
Try This: Example 2B
B.
+ + = y –
Multiply by the LCD.
6y + 20y + 18 = 24y – 18
26y + 18 = 24y – 18
Combine like terms.
Solving Equations with Variables on Both Sides
10-3
2y
2
–36
2
=
Course 3
Try This: Example 2B Continued
26y + 18 = 24y – 18
– 24y– 24y
Subtract 24y from both sides.
2y + 18 = – 18
– 18– 18
Subtract 18 from both sides.
2y = –36
Divide both sides by 2.
y = –18
Solving Equations with Variables on Both Sides
10-3
Course 3
Additional Example 3: Consumer Application
Jamie spends the same amount of money each morning. On Sunday, he bought a newspaper for $1.25 and also bought two doughnuts. On Monday, he bought a newspaper for fifty cents and bought five doughnuts. On Tuesday, he spent the same amount of money and bought just doughnuts. How many doughnuts did he buy on Tuesday?
Solving Equations with Variables on Both Sides
10-3
=
3d
3
0.75
3
Course 3
Additional Example 3 Continued
First solve for the price of one doughnut.
Let d represent the price of one doughnut.
1.25 + 2d = 0.50 + 5d
– 2d– 2d
Subtract 2d from both sides.
1.25 = 0.50 + 3d
Subtract 0.50 from both sides.
– 0.50– 0.50
0.75 = 3d
Divide both sides by 3.
The price of one doughnut is $0.25.
0.25 = d
Solving Equations with Variables on Both Sides
10-3
1.75
0.25
=
0.25n
0.25
Course 3
Additional Example 3 Continued
Now find the amount of money Jamie spends each morning.
Choose one of the original expressions.
1.25 + 2d
1.25 + 2(0.25) = 1.75
Jamie spends $1.75 each morning.
Find the number of doughnuts Jamie buys on Tuesday.
Let n represent the number of doughnuts.
0.25n = 1.75
Divide both sides by 0.25.
n = 7; Jamie bought 7 doughnuts on Tuesday.
Solving Equations with Variables on Both Sides
10-3
Course 3
Try This: Example 3
Helene walks the same distance every day. On Tuesdays and Thursdays, she walks 2 laps on the track, and then walks 4 miles. On Mondays, Wednesdays, and Fridays, she walks 4 laps on the track and then walks 2 miles. On Saturdays, she just walks laps. How many laps does she walk on Saturdays?
Solving Equations with Variables on Both Sides
10-3
2
=
2
2x
2
Course 3
Try This: Example 3 Continued
First solve for distance around the track.
Let x represent the distance around the track.
2x + 4 = 4x + 2
– 2x– 2x
Subtract 2x from both sides.
4 = 2x + 2
– 2– 2
Subtract 2 from both sides.
2 = 2x
Divide both sides by 2.
The track is 1 mile around.
1 = x
Solving Equations with Variables on Both Sides
10-3
Course 3
Try This: Example 3 Continued
Now find the total distance Helene walks each day.
Choose one of the original expressions.
2x + 4
2(1) + 4 = 6
Helene walks 6 miles each day.
Find the number of laps Helene walks on Saturdays.
Let n represent the number of 1-mile laps.
1n = 6
n = 6
Helene walks 6 laps on Saturdays.
Solving Equations with Variables on Both Sides
10-3
1
1
2
4
Course 3
Insert Lesson Title Here
Lesson Quiz
Solve.
1. 4x + 16 = 2x
2. 8x – 3 = 15 + 5x
3. 2(3x + 11) = 6x + 4
4.x = x – 9
5. An apple has about 30 calories more than an orange. Five oranges have about as many calories as 3 apples. How many calories are in each?
x = –8
x = 6
no solution
x = 36
An orange has 45 calories. An apple has 75 calories.
ad
|
__label__pos
| 0.998471 |
Post a New Question
geometry
posted by on .
Find the area of a pentagon ABCDE with verticles A(0,4),B(3,2),C(3,-1), D(-3,-1) and E (-3,2)
• geometry - ,
If the pentagon's boundary does not cross itself, I would use the surveyor's formula:
1. lay out the coordinates in order, repeat the first at the end.
A(0,4)
B(3,2)
C(3,-1)
D(-3,-1)
E (-3,2)
A(0,4)
2. Cross multiply between each successive pair and sum.
For A and B, we get 0*2-3*4=-12
For B and C, we get 3*-1 - 3*2 = -9
Continue until the last pair.
The sum of all 5 products is twice the area. If the vertices have been named clockwise, the sum will be negative.
3. Divide the sum by 2. If the sum is negative, write down only the positive value.
For the example:
vertex sum
A -12
B -9
C -6
D -9
E -12
Sum -48
Area = 48/2=24
Check my calculations.
Answer This Question
First Name:
School Subject:
Answer:
Related Questions
More Related Questions
Post a New Question
|
__label__pos
| 0.974321 |
Design
What is UI Design and Why UI Designers are important
0
Min Read Time
What is UI Design and Why UI Designers are important
The importance of UI design in creating a positive user experience
UI design plays a crucial role in creating a positive user experience for a website or application. It refers to the way the user interface is designed and laid out, including elements such as buttons, links, and overall layout and organization. A well-designed UI can make a website or application easy to navigate and use, leading to a better experience for the user.
One of the key benefits of good UI design is that it can help to increase user engagement and retention. When a website or application is easy to use and navigate, users are more likely to stay on the site and continue using it. In contrast, a poorly designed UI can lead to frustration and confusion, causing users to leave the site and potentially never return.
One tool that can be helpful for designing a user-friendly UI is Webflow. Webflow is a design platform that allows users to create and design websites without needing to know how to code. It offers a drag-and-drop interface and a wide range of customizable elements, making it easy for designers to create a visually appealing and functional UI.
In addition to increasing user engagement and retention, a well-designed UI can also improve the overall brand image of a company. A professional and polished UI can give users confidence in the company and its products or services. It can also help to establish trust and credibility, as users will perceive the company as being reliable and trustworthy if the UI is well-designed and easy to use.
Overall, the importance of UI design in creating a positive user experience cannot be overstated. It plays a crucial role in determining how users perceive and interact with a website or application, and can have a significant impact on their overall satisfaction and engagement with the site. By utilizing tools like Webflow and prioritizing UI design, companies can create a better experience for their users and improve their brand image.
Tips for improving the usability of your website or application
Improving the usability of your website or application is essential for ensuring that your users have a positive experience. Here are some tips for improving the usability of your website or application with Webflow:
1. Keep your navigation simple and intuitive: Your navigation should be easy to understand and use. Use clear, descriptive labels for your navigation items and organize them in a logical hierarchy. Avoid using too many navigation items, as this can be overwhelming for users.
2. Use consistent design elements: Consistency in design elements such as fonts, colors, and layout helps create a cohesive user experience. Make sure to use the same design elements throughout your website or application to avoid confusing users.
3. Use clear and concise language: Use language that is easy to understand and avoid using jargon or technical terms that may be unfamiliar to your users. Be sure to also use headings and subheadings to break up your content and make it easier to scan.
4. Make your website or application mobile-friendly: With the increasing use of mobile devices, it's important to make sure your website or application is responsive and works well on smaller screens. Using Webflow's responsive design features can help you create a website or application that looks great on any device.
5. Test your website or application: Conduct user testing to see how people interact with your website or application and identify any areas that may be confusing or frustrating. Make changes based on the feedback you receive to improve the usability of your website or application.
By following these tips and utilizing the features of Webflow, you can create a website or application that is easy to use and provides a great user experience.
Common UI design mistakes to avoid
As a web designer, it's important to be mindful of common UI design mistakes in order to create a cohesive, intuitive, and visually appealing website for users. In this blog, we'll cover some common UI design mistakes to avoid and how Choquer Creative, a webflow agency, can help you avoid them.
1. Cluttered layout: A cluttered layout can make it difficult for users to navigate and find the information they need. Avoid using too many elements on a single page and make sure to use white space effectively to separate different sections.
2. Poor contrast: Low contrast between text and background colors can make it difficult for users to read your website. Make sure to use high contrast color combinations, especially for body text and headings.
3. Unclear calls to action: A call to action (CTA) is a button or link that prompts users to take a specific action, such as signing up for a newsletter or making a purchase. Make sure your CTAs are clearly visible and use actionable language to encourage users to take the desired action.
4. Unresponsive design: With the increasing use of mobile devices, it's essential to have a responsive design that looks and functions well on all screen sizes. Chooser Creative, a webflow agency, can help you create a responsive website that adapts to different screen sizes and devices.
5. Inconsistent design: Inconsistencies in design, such as using different font styles or button styles throughout the website, can be confusing and unappealing to users. Make sure to maintain consistency in your design elements to create a cohesive look and feel.
By avoiding these common UI design mistakes, you can create a user-friendly and visually appealing website. Chooser Creative, a webflow agency, can help you create a professional and effective website that meets the needs of your business and your users.
How to design for accessibility and inclusivity
Designing for accessibility and inclusivity is essential for creating a website that is usable and enjoyable for all users, regardless of their abilities or disabilities. In this blog, we'll cover some tips for designing for accessibility and inclusivity and how Choquer Creative, a webflow agency, can help you implement them.
1. Use alt text for images: Alt text is a short description of an image that is displayed when the image cannot be seen. Alt text is important for users who are blind or have low vision, as it allows them to understand the content of the image through screen reader software.
2. Choose clear and simple fonts: Using clear and simple fonts, such as sans serif fonts, can improve readability for users with dyslexia or low vision. Avoid using small or decorative fonts that may be difficult to read.
3. Use high contrast colors: High contrast color combinations, such as black text on a white background, can improve readability for users with low vision or color blindness. Avoid using low contrast color combinations, such as light grey text on a white background.
4. Make sure content is organized logically: Organizing content in a logical and easy-to-follow manner can make it easier for users with cognitive impairments to understand and navigate the website.
5. Use descriptive link text: Using descriptive link text, such as "Learn more about our products," instead of "click here," can make it easier for users who rely on screen reader software to understand the content of the link.
By following these tips and working with Choquer Creative, a webflow agency, you can design a website that is accessible and inclusive for all users.
The Role of Psychology in UI design
The role of psychology in UI design is crucial for creating a user-friendly and effective interface. At Choquer Creative, a webflow agency, we understand the importance of incorporating psychological principles into our design process. Here are some ways psychology plays a role in UI design:
1. First impressions: The first few seconds a user spends on your website or application are crucial for making a good impression. A well-designed interface that is visually appealing and easy to use can help establish trust and credibility with users.
2. User motivation: Understanding what motivates your users can help you design an interface that meets their needs and encourages them to take desired actions. For example, if your goal is to get users to make a purchase, you may want to highlight the benefits of your product and make the checkout process as seamless as possible.
3. Cognitive load: Cognitive load refers to the amount of mental effort required to process information. An interface with a high cognitive load can be overwhelming and frustrating for users. It's important to keep the amount of information presented to a minimum and use clear and concise language to reduce cognitive load.
4. Emotional design: The way an interface looks and feels can have a big impact on how users perceive it. Incorporating emotional design elements such as color, typography, and imagery can help create a more enjoyable and engaging user experience.
By understanding the role of psychology in UI design and utilizing the features of Webflow, Choquer Creative can help you create a website or application that effectively meets the needs and motivations of your users.
The impact of mobile devices on UI design
Mobile devices have had a significant impact on UI design, as more and more users are accessing the internet through their smartphones and tablets. In this blog, we'll cover the impact of mobile devices on UI design and how Choquer Creative, a webflow agency, can help you design a mobile-friendly website.
1. Responsive design: With the increasing use of mobile devices, it's essential to have a responsive design that looks and functions well on all screen sizes. A responsive design automatically adjusts to fit the screen size of the device being used, ensuring that users have a seamless experience regardless of the device they are using. Choquer Creative, a webflow agency, can help you create a responsive website using webflow.
2. Mobile-first design: Mobile-first design is a design approach that prioritizes the mobile experience and then adapts the design for larger screens. This approach is important because many users access the internet primarily through their smartphones. Choquer Creative can help you design a mobile-first website that provides a great user experience on all devices.
3. Touchscreen interfaces: Mobile devices often have touchscreen interfaces, which require a different design approach than traditional desktop interfaces. Designers must consider how users will interact with the website using their fingertips rather than a mouse or trackpad. Choquer Creative can help you design a website that is optimized for touchscreen interfaces.
4. Limited screen space: Mobile devices have smaller screens than desktop computers, which means that designers must be mindful of the amount of content and the layout of the website to ensure that it is easy to read and navigate on a small screen. Choquer Creative can help you design a mobile-friendly website that is easy to use on small screens.
By considering the impact of mobile devices on UI design and working with Choquer Creative, a webflow agency, you can create a website that is optimized for mobile devices and provides a great user experience on all devices.
The benefits of using design systems in UI design
Design systems are an important tool for creating consistent, cohesive, and scalable user interfaces. At Choquer Creative, a webflow agency, we understand the benefits of using design systems in UI design. Here are a few of the benefits:
1. Consistency: Design systems ensure that the design elements of your website or application are consistently used throughout. This helps create a cohesive user experience and makes it easier for users to navigate your site or app.
2. Efficiency: Design systems allow you to create a set of reusable design elements that can be easily implemented in new projects. This saves time and effort in the design process and allows you to focus on creating new and innovative features.
3. Scalability: As your website or application grows, a design system allows you to easily add new features and pages without compromising the overall design. This helps ensure that your site or app stays consistent and user-friendly as it evolves.
4. Collaboration: Design systems make it easier for teams to collaborate and work together on projects. By having a clear set of design guidelines, team members can easily understand and follow the design principles for the project.
By using design systems in UI design and utilizing the features of Webflow, Choquer Creative can help you create a website or application that is consistent, efficient, scalable, and easy to collaborate on.
Best practices for designing for different screen sizes and resolutions
Designing for different screen sizes and resolutions can be a challenging task for web designers, as they must ensure that the website looks and functions well on a wide range of devices. In this blog, we'll cover some best practices for designing for different screen sizes and resolutions and how Choquer Creative, a webflow agency, can help you implement them.
1. Use a responsive design: A responsive design automatically adjusts to fit the screen size of the device being used, ensuring that users have a seamless experience regardless of the device they are using. Choquer Creative, a webflow agency, can help you create a responsive website using webflow.
2. Consider different screen sizes: Different devices have different screen sizes, ranging from small smartphones to large desktop monitors. It's important to design a layout that looks good and is easy to use on all screen sizes. Choquer Creative can help you design a website that is optimized for different screen sizes.
3. Use flexible grid-based layouts: Grid-based layouts allow elements to adjust their size and position based on the screen size, ensuring that the layout looks good on all devices. Choquer Creative can help you design a grid-based layout that is flexible and responsive.
4. Optimize images for different resolutions: Different devices have different screen resolutions, which can affect how images are displayed. It's important to use high-resolution images that look good on all devices, and to consider how images will be resized on different screens. Choquer Creative can help you optimize images for different resolutions.
By following these best practices and working with Choquer Creative, a webflow agency, you can design a website that looks and functions well on all devices and screen sizes.
The role of data and analytics in informing UI design decisions
Data and analytics play a crucial role in informing UI design decisions. At Choquer Creative, a webflow agency, we understand the importance of using data to inform our design process. Here are a few ways data and analytics can inform UI design decisions:
1. User behavior: Analyzing data on how users interact with your website or application can provide valuable insights into their behavior and needs. For example, data on which pages are the most visited or which actions are the most frequently performed can help inform the design of those pages or actions.
2. User feedback: Gathering feedback from users through surveys or interviews can provide valuable insights into their experience with your website or application. This feedback can help identify areas for improvement and inform design decisions.
3. A/B testing: A/B testing allows you to compare the effectiveness of different design elements by presenting users with two versions of a page or feature and measuring their behavior. This can help identify the design elements that work best for your users.
By using data and analytics to inform UI design decisions and utilizing the features of Webflow, Choquer Creative can help you create a website or application that effectively meets the needs and preferences of your users.
The future of UI design: trends to watch for in the coming years
UI design is constantly evolving, and it's important for designers to stay up-to-date on the latest trends in order to create innovative and effective designs. In this blog, we'll cover some trends to watch for in the future of UI design and how Choquer Creative, a webflow agency, can help you stay ahead of the curve.
1. Artificial intelligence: AI is becoming increasingly prevalent in UI design, with features such as voice assistants and personalized recommendations becoming more common. Choquer Creative can help you incorporate AI into your UI design to enhance the user experience.
2. Virtual and augmented reality: VR and AR are becoming more mainstream, and they have the potential to revolutionize UI design by allowing users to interact with virtual environments in new and immersive ways. Choquer Creative can help you design UI elements for VR and AR applications.
3. Motion design: Motion design, or the use of animation and transitions in UI design, can add depth and personality to a website or app. Chooser Creative can help you incorporate motion design into your UI design to enhance the user experience.
4. Personalization: Personalization, or the use of data to tailor the user experience to individual users, is becoming increasingly popular in UI design. Choquer Creative can help you design personalized UI elements that provide a unique and engaging experience for each user.
5. Accessibility: As technology becomes more advanced, it's important to design UI elements that are accessible to users with disabilities. Choquer Creative can help you design accessible UI elements that are easy to use for all users.
By staying up-to-date on the latest trends in UI design and working with Choquer Creative, a webflow agency, you can create innovative and effective designs that meet the needs of your users.
In conclusion, Choquer Creative, a webflow agency, can help you design a website that is effective at converting visitors into customers, compliant with industry standards and regulations, and on brand for your business. With their expertise in webflow and UI design, Choquer Creative can help you create a professional and cohesive website that meets the needs of your business and your users. Whether you need a responsive design, personalized UI elements, or accessibility features, Choquer Creative has the skills and experience to help you create a website that converts, compliant, and on brand.
Related Stories
Sign Up For Our
Learning Hub Weekly Blog
Dive into one of our articles to learn more about web development, SEO tips & tricks, and how you can grow your business through your website.
Awesome! More content!
Oops! Something went wrong while submitting the form.
|
__label__pos
| 0.907542 |
Reflex angle
reflex angle
Definition
An angle of more than $180^\circ$ but less than $360^\circ$ is called a Reflex angle.
The region from more than $180^\circ$ to less than $360^\circ$ is called reflex. If the angle lies in this region, the angle is known as the reflex angle geometrically.
Case study
Geometrically, reflex angles are formed possibly in two different cases.
1
Reflex angle by a Line
reflex angle by the rotation of a line
The angle of a line is usually measured from $0^\circ$ angle. So, assume the ray $\overrightarrow{RS}$ is initially at zero degrees angle.
Later, the ray $\overrightarrow{RS}$ is rotated to $245^\circ$ angle in anticlockwise direction to reach new position where the ray $\overrightarrow{RS}$ is called as $\overrightarrow{RT}$.
In other words, the ray $\overrightarrow{RS}$ made an angle of $245^\circ$ to reach its final position from its initial position.
$\angle SRT = 245^\circ$
The angle $SRT$ is $245^\circ$ and it is greater than $180^\circ$ but less than $360^\circ$. Therefore, the $\angle SRT$ is called as a reflex angle.
If any straight line makes an angle of greater than $180^\circ$ and less than $360^\circ$ by the rotation, the angle is called as a reflex angle.
2
Reflex angle between two lines
reflex angle between two lines
$U$ is a point where two rays $\overrightarrow{UV}$ and $\overrightarrow{UW}$ are started.
In this case, the ray $\overrightarrow{UV}$ becomes reference line to ray $\overrightarrow{UW}$ and vice-versa to measure angle between them.
The angle between them is measured as $310^\circ$ and it is denoted by $\angle VUW$.
$\angle VUW = 310^\circ$
The angle $VUW$ is greater than $180^\circ$ and less than $360^\circ$. Therefore $\angle VUW$ is called as reflex angle.
As example here, if angle between any two lines is greater than 180 and less than 360, the angle between them is an example to the reflex angle.
Follow us
Email subscription
|
__label__pos
| 0.990509 |
alexander-fire alexander-fire - 2 months ago 18x
TypeScript Question
AngularJS: Failed to instantiate my own module
I´ve tried to start with TypeScript and AngularJS but after the first few lines based on a Tutorial I get this confusing error.
It seems that something is wrong with my
mydModule
?
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module mydModule due to:
Error: [$injector:nomod] Module 'mydModule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
index.html
<html ng-app="mydModule">
<body>
<script src="Scripts/angular.js"></script>
<script src="App_Scripts/start.js"></script>
<script src="App_Scripts/startController.js"></script>
<div class="wrapper container">
<div class="row" ng-controller="startController as vm">
<div id="content">
Tst:
<ul>
<li ng-repeat="label in vm.sequence">
<span ng-style="{'background-color':label.Color}">{{label.Text}}</span>
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
start.ts
/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
module DosierradApplication {
export class StartPage {
static mydModule = angular.module('startPage', ['ngResource']);
}
}
startController.ts
/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="start.ts" />
module DosierradApplication {
export class startController {
constructor(private $scope: ng.IScope) {
}
sequence = [
{
"Id": 0,
"Text": "all good",
"Color": "#0f0"
},
{
"Id": 1,
"Text": "not good",
"Color": "#ff0"
}
];
}
StartPage.mydModule.controller('startController', ["$scope", startController]);
}
Answer
You've called your module 'startPage' and trying to access it as 'mydModule'. So it should be
<html ng-app="startPage">
mydModule is variable name, not a module name in above sample.
Comments
|
__label__pos
| 0.997377 |
/[gentoo-x86]/x11-drivers/nvidia-drivers/nvidia-drivers-304.64.ebuild
Gentoo
Contents of /x11-drivers/nvidia-drivers/nvidia-drivers-304.64.ebuild
Parent Directory Parent Directory | Revision Log Revision Log
Revision 1.4 - (show annotations) (download)
Wed Dec 19 16:52:01 2012 UTC (4 years, 11 months ago) by tetromino
Branch: MAIN
Changes since 1.3: +2 -1 lines
Depend on pangox-compat if using pango-1.32.
(Portage version: 2.2.0_alpha149/cvs/Linux x86_64, signed Manifest commit with key CF0ADD61)
1 # Copyright 1999-2012 Gentoo Foundation
2 # Distributed under the terms of the GNU General Public License v2
3 # $Header: /var/cvsroot/gentoo-x86/x11-drivers/nvidia-drivers/nvidia-drivers-304.64.ebuild,v 1.3 2012/12/11 15:20:56 ssuominen Exp $
4
5 EAPI=4
6
7 inherit eutils flag-o-matic linux-info linux-mod multilib nvidia-driver \
8 portability toolchain-funcs unpacker user versionator udev
9
10 X86_NV_PACKAGE="NVIDIA-Linux-x86-${PV}"
11 AMD64_NV_PACKAGE="NVIDIA-Linux-x86_64-${PV}"
12 X86_FBSD_NV_PACKAGE="NVIDIA-FreeBSD-x86-${PV}"
13 AMD64_FBSD_NV_PACKAGE="NVIDIA-FreeBSD-x86_64-${PV}"
14
15 DESCRIPTION="NVIDIA X11 driver and GLX libraries"
16 HOMEPAGE="http://www.nvidia.com/"
17 SRC_URI="x86? ( ftp://download.nvidia.com/XFree86/Linux-x86/${PV}/${X86_NV_PACKAGE}.run )
18 amd64? ( ftp://download.nvidia.com/XFree86/Linux-x86_64/${PV}/${AMD64_NV_PACKAGE}.run )
19 amd64-fbsd? ( ftp://download.nvidia.com/XFree86/FreeBSD-x86_64/${PV}/${AMD64_FBSD_NV_PACKAGE}.tar.gz )
20 x86-fbsd? ( ftp://download.nvidia.com/XFree86/FreeBSD-x86/${PV}/${X86_FBSD_NV_PACKAGE}.tar.gz )"
21
22 LICENSE="NVIDIA"
23 SLOT="0"
24 KEYWORDS="-* amd64 x86 ~amd64-fbsd ~x86-fbsd"
25 IUSE="acpi multilib kernel_FreeBSD kernel_linux pax_kernel +tools +X"
26 RESTRICT="strip"
27 EMULTILIB_PKG="true"
28
29 COMMON="app-admin/eselect-opencl
30 kernel_linux? ( >=sys-libs/glibc-2.6.1 )
31 multilib? ( app-emulation/emul-linux-x86-xlibs )
32 X? (
33 <x11-base/xorg-server-1.13.99
34 >=app-admin/eselect-opengl-1.0.9
35 )"
36 DEPEND="${COMMON}
37 kernel_linux? (
38 virtual/linux-sources
39 virtual/pkgconfig
40 )"
41 RDEPEND="${COMMON}
42 acpi? ( sys-power/acpid )
43 tools? (
44 dev-libs/atk
45 dev-libs/glib
46 x11-libs/gdk-pixbuf
47 x11-libs/gtk+:2
48 x11-libs/libX11
49 x11-libs/libXext
50 x11-libs/pango[X]
51 || ( x11-libs/pangox-compat <x11-libs/pango-1.31[X] )
52 )
53 X? ( x11-libs/libXvMC )"
54 PDEPEND="X? ( >=x11-libs/libvdpau-0.3-r1 )"
55
56 REQUIRED_USE="tools? ( X )"
57
58 QA_PREBUILT="opt/* usr/lib*"
59
60 S=${WORKDIR}/
61
62 pkg_pretend() {
63
64 if use amd64 && has_multilib_profile && \
65 [ "${DEFAULT_ABI}" != "amd64" ]; then
66 eerror "This ebuild doesn't currently support changing your default ABI"
67 die "Unexpected \${DEFAULT_ABI} = ${DEFAULT_ABI}"
68 fi
69
70 # Kernel features/options to check for
71 CONFIG_CHECK="~ZONE_DMA ~MTRR ~SYSVIPC ~!LOCKDEP"
72 use x86 && CONFIG_CHECK+=" ~HIGHMEM"
73
74 # Now do the above checks
75 use kernel_linux && check_extra_config
76 }
77
78 pkg_setup() {
79 # try to turn off distcc and ccache for people that have a problem with it
80 export DISTCC_DISABLE=1
81 export CCACHE_DISABLE=1
82
83 if use kernel_linux; then
84 linux-mod_pkg_setup
85 MODULE_NAMES="nvidia(video:${S}/kernel)"
86 BUILD_PARAMS="IGNORE_CC_MISMATCH=yes V=1 SYSSRC=${KV_DIR} \
87 SYSOUT=${KV_OUT_DIR} CC=$(tc-getBUILD_CC)"
88 # linux-mod_src_compile calls set_arch_to_kernel, which
89 # sets the ARCH to x86 but NVIDIA's wrapping Makefile
90 # expects x86_64 or i386 and then converts it to x86
91 # later on in the build process
92 BUILD_FIXES="ARCH=$(uname -m | sed -e 's/i.86/i386/')"
93 fi
94
95 # Since Nvidia ships 3 different series of drivers, we need to give the user
96 # some kind of guidance as to what version they should install. This tries
97 # to point the user in the right direction but can't be perfect. check
98 # nvidia-driver.eclass
99 nvidia-driver-check-warning
100
101 # set variables to where files are in the package structure
102 if use kernel_FreeBSD; then
103 use x86-fbsd && S="${WORKDIR}/${X86_FBSD_NV_PACKAGE}"
104 use amd64-fbsd && S="${WORKDIR}/${AMD64_FBSD_NV_PACKAGE}"
105 NV_DOC="${S}/doc"
106 NV_OBJ="${S}/obj"
107 NV_SRC="${S}/src"
108 NV_MAN="${S}/x11/man"
109 NV_X11="${S}/obj"
110 NV_SOVER=1
111 elif use kernel_linux; then
112 NV_DOC="${S}"
113 NV_OBJ="${S}"
114 NV_SRC="${S}/kernel"
115 NV_MAN="${S}"
116 NV_X11="${S}"
117 NV_SOVER=${PV}
118 else
119 die "Could not determine proper NVIDIA package"
120 fi
121 }
122
123 src_unpack() {
124 if ! use kernel_FreeBSD; then
125 cd "${S}"
126 unpack_makeself
127 else
128 unpack ${A}
129 fi
130 }
131
132 src_prepare() {
133 # Please add a brief description for every added patch
134
135 if use kernel_linux; then
136 if kernel_is lt 2 6 9 ; then
137 eerror "You must build this against 2.6.9 or higher kernels."
138 fi
139
140 # If greater than 2.6.5 use M= instead of SUBDIR=
141 convert_to_m "${NV_SRC}"/Makefile.kbuild
142 fi
143
144 if use pax_kernel; then
145 ewarn "Using PAX patches is not supported. You will be asked to"
146 ewarn "use a standard kernel should you have issues. Should you"
147 ewarn "need support with these patches, contact the PaX team."
148 epatch "${FILESDIR}"/nvidia-drivers-pax-const.patch
149 epatch "${FILESDIR}"/nvidia-drivers-pax-usercopy.patch
150 fi
151
152 cat <<- EOF > "${S}"/nvidia.icd
153 /usr/$(get_libdir)/libnvidia-opencl.so
154 EOF
155
156 # Allow user patches so they can support RC kernels and whatever else
157 epatch_user
158 }
159
160 src_compile() {
161 # This is already the default on Linux, as there's no toplevel Makefile, but
162 # on FreeBSD there's one and triggers the kernel module build, as we install
163 # it by itself, pass this.
164
165 cd "${NV_SRC}"
166 if use kernel_FreeBSD; then
167 MAKE="$(get_bmake)" CFLAGS="-Wno-sign-compare" emake CC="$(tc-getCC)" \
168 LD="$(tc-getLD)" LDFLAGS="$(raw-ldflags)" || die
169 elif use kernel_linux; then
170 linux-mod_src_compile
171 fi
172 }
173
174 # Install nvidia library:
175 # the first parameter is the library to install
176 # the second parameter is the provided soversion
177 # the third parameter is the target directory if its not /usr/lib
178 donvidia() {
179 # Full path to library minus SOVER
180 MY_LIB="$1"
181
182 # SOVER to use
183 MY_SOVER="$2"
184
185 # Where to install
186 MY_DEST="$3"
187
188 if [[ -z "${MY_DEST}" ]]; then
189 MY_DEST="/usr/$(get_libdir)"
190 action="dolib.so"
191 else
192 exeinto ${MY_DEST}
193 action="doexe"
194 fi
195
196 # Get just the library name
197 libname=$(basename $1)
198
199 # Install the library with the correct SOVER
200 ${action} ${MY_LIB}.${MY_SOVER} || \
201 die "failed to install ${libname}"
202
203 # If SOVER wasn't 1, then we need to create a .1 symlink
204 if [[ "${MY_SOVER}" != "1" ]]; then
205 dosym ${libname}.${MY_SOVER} \
206 ${MY_DEST}/${libname}.1 || \
207 die "failed to create ${libname} symlink"
208 fi
209
210 # Always create the symlink from the raw lib to the .1
211 dosym ${libname}.1 \
212 ${MY_DEST}/${libname} || \
213 die "failed to create ${libname} symlink"
214 }
215
216 src_install() {
217 if use kernel_linux; then
218 linux-mod_src_install
219
220 VIDEOGROUP="$(egetent group video | cut -d ':' -f 3)"
221 if [ -z "$VIDEOGROUP" ]; then
222 eerror "Failed to determine the video group gid."
223 die "Failed to determine the video group gid."
224 fi
225
226 # Add the aliases
227 [ -f "${FILESDIR}/nvidia-169.07" ] || die "nvidia missing in FILESDIR"
228 sed -e 's:PACKAGE:'${PF}':g' \
229 -e 's:VIDEOGID:'${VIDEOGROUP}':' "${FILESDIR}"/nvidia-169.07 > \
230 "${WORKDIR}"/nvidia
231 insinto /etc/modprobe.d
232 newins "${WORKDIR}"/nvidia nvidia.conf || die
233
234 # Ensures that our device nodes are created when not using X
235 exeinto "$(udev_get_udevdir)"
236 doexe "${FILESDIR}"/nvidia-udev.sh
237 udev_newrules "${FILESDIR}"/nvidia.udev-rule 99-nvidia.rules
238
239 elif use kernel_FreeBSD; then
240 if use x86-fbsd; then
241 insinto /boot/modules
242 doins "${S}/src/nvidia.kld" || die
243 fi
244
245 exeinto /boot/modules
246 doexe "${S}/src/nvidia.ko" || die
247 fi
248
249 # NVIDIA kernel <-> userspace driver config lib
250 donvidia ${NV_OBJ}/libnvidia-cfg.so ${NV_SOVER}
251
252 if use kernel_linux; then
253 # NVIDIA video decode <-> CUDA
254 donvidia ${NV_OBJ}/libnvcuvid.so ${NV_SOVER}
255 fi
256
257 if use X; then
258 # Xorg DDX driver
259 insinto /usr/$(get_libdir)/xorg/modules/drivers
260 doins ${NV_X11}/nvidia_drv.so || die "failed to install nvidia_drv.so"
261
262 # Xorg GLX driver
263 donvidia ${NV_X11}/libglx.so ${NV_SOVER} \
264 /usr/$(get_libdir)/opengl/nvidia/extensions
265
266 # XvMC driver
267 dolib.a ${NV_X11}/libXvMCNVIDIA.a || \
268 die "failed to install libXvMCNVIDIA.so"
269 donvidia ${NV_X11}/libXvMCNVIDIA.so ${NV_SOVER}
270 dosym libXvMCNVIDIA.so.${NV_SOVER} \
271 /usr/$(get_libdir)/libXvMCNVIDIA_dynamic.so.1 || \
272 die "failed to create libXvMCNVIDIA_dynamic.so symlink"
273 fi
274
275 # OpenCL ICD for NVIDIA
276 if use kernel_linux; then
277 insinto /etc/OpenCL/vendors
278 doins nvidia.icd
279 donvidia ${NV_OBJ}/libnvidia-opencl.so ${NV_SOVER}
280 fi
281
282 # Documentation
283 dohtml ${NV_DOC}/html/*
284 if use kernel_FreeBSD; then
285 dodoc "${NV_DOC}/README"
286 use X && doman "${NV_MAN}/nvidia-xconfig.1"
287 use tools && doman "${NV_MAN}/nvidia-settings.1"
288 else
289 # Docs
290 newdoc "${NV_DOC}/README.txt" README
291 dodoc "${NV_DOC}/NVIDIA_Changelog"
292 doman "${NV_MAN}/nvidia-smi.1.gz"
293 use X && doman "${NV_MAN}/nvidia-xconfig.1.gz"
294 use tools && doman "${NV_MAN}/nvidia-settings.1.gz"
295 doman "${NV_MAN}/nvidia-cuda-proxy-control.1.gz"
296 fi
297
298 # Helper Apps
299 exeinto /opt/bin/
300
301 if use X; then
302 doexe ${NV_OBJ}/nvidia-xconfig || die
303 fi
304
305 if use kernel_linux ; then
306 doexe ${NV_OBJ}/nvidia-debugdump || die
307 doexe ${NV_OBJ}/nvidia-cuda-proxy-control || die
308 doexe ${NV_OBJ}/nvidia-cuda-proxy-server || die
309 doexe ${NV_OBJ}/nvidia-smi || die
310 newinitd "${FILESDIR}/nvidia-smi.init" nvidia-smi
311 fi
312
313 if use tools; then
314 doexe ${NV_OBJ}/nvidia-settings || die
315 fi
316
317 exeinto /usr/bin/
318 doexe ${NV_OBJ}/nvidia-bug-report.sh || die
319
320 # Desktop entries for nvidia-settings
321 if use tools ; then
322 # There is no icon in the FreeBSD tarball.
323 use kernel_FreeBSD || newicon ${NV_OBJ}/nvidia-settings.png nvidia-drivers-settings.png
324 domenu "${FILESDIR}"/nvidia-drivers-settings.desktop
325 exeinto /etc/X11/xinit/xinitrc.d
326 doexe "${FILESDIR}"/95-nvidia-settings
327 fi
328
329 #doenvd "${FILESDIR}"/50nvidia-prelink-blacklist
330
331 if has_multilib_profile && use multilib ; then
332 local OABI=${ABI}
333 for ABI in $(get_install_abis) ; do
334 src_install-libs
335 done
336 ABI=${OABI}
337 unset OABI
338 else
339 src_install-libs
340 fi
341
342 is_final_abi || die "failed to iterate through all ABIs"
343 }
344
345 src_install-libs() {
346 local inslibdir=$(get_libdir)
347 local GL_ROOT="/usr/$(get_libdir)/opengl/nvidia/lib"
348 local CL_ROOT="/usr/$(get_libdir)/OpenCL/vendors/nvidia"
349 local libdir=${NV_OBJ}
350
351 if use kernel_linux && has_multilib_profile && \
352 [[ ${ABI} == "x86" ]] ; then
353 libdir=${NV_OBJ}/32
354 fi
355
356 if use X; then
357 # The GLX libraries
358 donvidia ${libdir}/libGL.so ${NV_SOVER} ${GL_ROOT}
359 donvidia ${libdir}/libnvidia-glcore.so ${NV_SOVER}
360 if use kernel_FreeBSD; then
361 donvidia ${libdir}/libnvidia-tls.so ${NV_SOVER} ${GL_ROOT}
362 else
363 donvidia ${libdir}/tls/libnvidia-tls.so ${NV_SOVER} ${GL_ROOT}
364 fi
365
366 # VDPAU
367 donvidia ${libdir}/libvdpau_nvidia.so ${NV_SOVER}
368 fi
369
370 # NVIDIA monitoring library
371 if use kernel_linux ; then
372 donvidia ${libdir}/libnvidia-ml.so ${NV_SOVER}
373 fi
374
375 # CUDA & OpenCL
376 if use kernel_linux; then
377 donvidia ${libdir}/libcuda.so ${NV_SOVER}
378 donvidia ${libdir}/libnvidia-compiler.so ${NV_SOVER}
379 donvidia ${libdir}/libOpenCL.so 1.0.0 ${CL_ROOT}
380 fi
381 }
382
383 pkg_preinst() {
384 use kernel_linux && linux-mod_pkg_preinst
385
386 # Clean the dynamic libGL stuff's home to ensure
387 # we dont have stale libs floating around
388 if [ -d "${ROOT}"/usr/lib/opengl/nvidia ] ; then
389 rm -rf "${ROOT}"/usr/lib/opengl/nvidia/*
390 fi
391 # Make sure we nuke the old nvidia-glx's env.d file
392 if [ -e "${ROOT}"/etc/env.d/09nvidia ] ; then
393 rm -f "${ROOT}"/etc/env.d/09nvidia
394 fi
395 }
396
397 pkg_postinst() {
398 use kernel_linux && linux-mod_pkg_postinst
399
400 # Switch to the nvidia implementation
401 use X && "${ROOT}"/usr/bin/eselect opengl set --use-old nvidia
402 "${ROOT}"/usr/bin/eselect opencl set --use-old nvidia
403
404 elog "You must be in the video group to use the NVIDIA device"
405 elog "For more info, read the docs at"
406 elog "http://www.gentoo.org/doc/en/nvidia-guide.xml#doc_chap3_sect6"
407 elog
408 elog "This ebuild installs a kernel module and X driver. Both must"
409 elog "match explicitly in their version. This means, if you restart"
410 elog "X, you must modprobe -r nvidia before starting it back up"
411 elog
412 elog "To use the NVIDIA GLX, run \"eselect opengl set nvidia\""
413 elog
414 elog "To use the NVIDIA CUDA/OpenCL, run \"eselect opencl set nvidia\""
415 elog
416 elog "NVIDIA has requested that any bug reports submitted have the"
417 elog "output of /opt/bin/nvidia-bug-report.sh included."
418 elog
419 if ! use X; then
420 elog "You have elected to not install the X.org driver. Along with"
421 elog "this the OpenGL libraries, XvMC, and VDPAU libraries were not"
422 elog "installed. Additionally, once the driver is loaded your card"
423 elog "and fan will run at max speed which may not be desirable."
424 elog "Use the 'nvidia-smi' init script to have your card and fan"
425 elog "speed scale appropriately."
426 elog
427 fi
428 if ! use tools; then
429 elog "USE=tools controls whether the nvidia-settings application"
430 elog "is installed. If you would like to use it, enable that"
431 elog "flag and re-emerge this ebuild. Optionally you can install"
432 elog "media-video/nvidia-settings"
433 elog
434 fi
435 }
436
437 pkg_prerm() {
438 use X && "${ROOT}"/usr/bin/eselect opengl set --use-old xorg-x11
439 }
440
441 pkg_postrm() {
442 use kernel_linux && linux-mod_pkg_postrm
443 use X && "${ROOT}"/usr/bin/eselect opengl set --use-old xorg-x11
444 }
ViewVC Help
Powered by ViewVC 1.1.20
|
__label__pos
| 0.536678 |
Conversion of Fractions
Conversion of fractions is discussed here in order to convert a mixed fraction into an improper fraction and also to convert an improper fraction as a mixed fraction.
Method of reduction of different fractions into like fractions:
Step I: Find the L.C.M of all the denominators.
Step II: Divide the L.C.M by the denominator of the first fraction and get the quotient.
Step III: Multiply both numerator and denominator of the first fraction by the quotient.
Step IV: Repeat step 2 and 3 for all the given fractions.
In order to convert a mixed fraction into an improper fraction, we may use the following formula;
Improper fraction = {(Whole number x Denominator) + Numerator} Denominator
For example;
(i) 31/5 = (3 × 5 + 1)/5 = (15 + 1)/5 = 16/5
(ii) 93/4 = (9 × 4 + 3)/4 = (36 + 3)/4 = 39/4
In order to convert an improper fraction as a mixed fraction, we first divide the numerator by denominator and obtain the quotient and remainder and then we write the mixed fraction as
Quotient = Remainder
Denominator
For example;
(i) ¹⁷/₄ = 4¹/₄ [Since, Quotient = 4, Remainder = 1]
(ii) ⁴⁷/₁₅ = 3²/₁₅ [Since, Quotient = 3, Remainder = 2]
Note:
If the numerator and denominator of a fraction are both multiplied by the same non-zero number, then its value does not change.
i.e., 4/5 = (4 × 2)/(5 × 2) = (4 × 3)/(5 × 3) = (4 × 4)/(5 × 4) = (4 × 5)/(5 × 5)
= (4 × 6)/(5 × 6) etc.
If the numerator and denominator of a fraction are both divided by their common factor, then its value does not change.
i.e., 6/10 = (6 ÷ 2)/(10 ÷ 2) = 3/5;
9/24 = (9 ÷ 3)/(24 ÷ 3) = 3/8 etc.
These are the basic examples on conversion of fractions explained here step by step.
Fractions
Fractions
Types of Fractions
Equivalent Fractions
Like and Unlike Fractions
Conversion of Fractions
Fraction in Lowest Terms
Addition and Subtraction of Fractions
Multiplication of Fractions
Division of Fractions
Fractions - Worksheets
Worksheet on Fractions
Worksheet on Multiplication of Fractions
Worksheet on Division of Fractions
7th Grade Math Problems
From Conversion of Fractions to HOME PAGE
Didn't find what you were looking for? Or want to know more information about Math Only Math. Use this Google Search to find what you need.
Share this page: What’s this?
Recent Articles
1. Relation between Diameter Radius and Circumference |Problems |Examples
Apr 22, 24 05:19 PM
Relation between Radius and Diameter of a Circle
Relation between diameter radius and circumference are discussed here. Relation between Diameter and Radius: What is the relation between diameter and radius? Solution: Diameter of a circle is twice
Read More
2. Circle Math | Terms Related to the Circle | Symbol of Circle O | Math
Apr 22, 24 01:35 PM
Circle using a Compass
In circle math the terms related to the circle are discussed here. A circle is such a closed curve whose every point is equidistant from a fixed point called its centre. The symbol of circle is O. We…
Read More
3. Preschool Math Activities | Colorful Preschool Worksheets | Lesson
Apr 21, 24 10:57 AM
Preschool Math Activities
Preschool math activities are designed to help the preschoolers to recognize the numbers and the beginning of counting. We believe that young children learn through play and from engaging
Read More
4. Months of the Year | List of 12 Months of the Year |Jan, Feb, Mar, Apr
Apr 20, 24 05:39 PM
Months of the Year
There are 12 months in a year. The months are January, February, march, April, May, June, July, August, September, October, November and December. The year begins with the January month. December is t…
Read More
5. What are Parallel Lines in Geometry? | Two Parallel Lines | Examples
Apr 20, 24 05:29 PM
Examples of Parallel Lines
In parallel lines when two lines do not intersect each other at any point even if they are extended to infinity. What are parallel lines in geometry? Two lines which do not intersect each other
Read More
|
__label__pos
| 0.980943 |
XSLT
Think of XSLT programming style as an event driven program, and event listeners (xsl:template) as the behavior of the program. The input XML file will be read by the program as a stream, and once a new declared event happened (template) it will be executed.
If in applying templates it doesn't find a template starting at root, it will traverse all tags and if finds a mtach for one will execute the match, otherwise will display its text. - match statements must be starting from the current node or having a // to be findable.
Hello World XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<greeting>Hello World!</greeting>
you can inlude reference to the xsl file in the xml file and when openning the xml file in a browser it will display the transformed xml.. Just add the following line after the xml declaration in the xml file
<?xml-stylesheet type="text/xsl" href="1.xsl"?>
Hello World xslt transformer
<?xml version="1.0" encoding="ISO-8859-1"?>
<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="2.0">
<head><title>Hello World Title</title></head>
<body><p><xsl:value-of select="/greeting"/></p></body>
</html>
File names shoul not start with a number!
A bash file to execute SAXON to transform the xml file
./run_transform.sh
#!/bin/bash
CLASSPATH=./saxon9he.jar
export CLASSPATH
java net.sf.saxon.Transform -o temp.xml $1 reorder_xform.xsl
This will need an input argument (the xml file) usin the reorder_xform.xslin the current directory, transforms it to the temp.xml in the current directory.
If namespace is not specified for an xml element or an attribute, they are in the default namespace, unless they have explicitly specified the namespace.
Namespace prefix doesn't matter as long as the namespace URI is the same.
<xsl:for-each>
To cycle through a list of elements of same type:
<xsl:for-each select="/TVGuide/Channel">
The title is: <xsl:value-of select="name"/>
<xsl:for-each select="program">
Program: <xsl:value-of select="series"/>
Cast List:
<xsl:for-each select="cast">
<xsl:value-of select="Actor"/>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
Relative paths are always evaluated relative to the context node (current node).
<xsl:apply-templates>
Modularize the XSLT code into templates and call the template right in place.
Write templates as the main children of the document and call them with <xsl:apply-templates selsct="program"/>
If <xsl:apply-templates> does not have a select attribute, the XSLT processor will collect all the children of the current node (nodes that template matches) and applies templates to them. If they have a template associated with them it will be called otherwise their text content will be returned.
If you apply a template to an element but there is no template for that element, the text within the element will be returned. E.g. if we have used <xsl:apply-templates select="name"/> but we have not defined the template for "name", then the text value of the element will be returned -text at all levels concatenated).
For example if we have : some text <character>Mary</character> more text and apply the following to it:
<xsl:template match="character"> <xsl:apply-templates /> </xsl:template>
the txtual content of all the children at all levels will be concatenated together and returned.
Selecting Nodes
/ Matches the document node
* Matches any element
text() Matches text nodes
<xsl:template match="text()"> #text() matches text nodes
<xsl:value-of select="."/>
</xsl:template>
name of an element matches that element
castMember/character: direct child
description//character: character nested to any level of description
Pattern Priority
• Patterns that match a class of nodes e.g. * are -0.5
• Patterns that match according to the name of the tag are 0
• Patterns that match according to their decendancy e.g. books/book1 or books//book1 are 0.5
• You can explicitly assign priority of a template: <xsl:template match="a/b" priority="2"> </xsl:template>
<xsl:next-element>
tells the XSLT processor to find the next most applicable template rule for the context node being processed and apply it, letting you apply multiple template rules to a node while still using a push approach(stand-alone templates). Link
"Go find the next most appropriate template rule after this one, execute all of its instructions, and then resume in this template rule."
you can add xsl:with-param children to the xsl:next-match element to pass parameters, just like you can with named templates.
<xsl:text> </xsl:text>
for explicit text outputs - recommended for preserving whitespaces.
<xsl:variable>
<xsl:variable> name="foo" value="123" />
<xsl:variable name="bar" value="456" />
<xsl:variable name="baz" value="$foo + $bar" />
<xsl:variable name="dummy" value="42 div 0" />
<xsl:template match="/">
<xsl:value-of select="$baz"/>
</xsl:template>
make the result of a template as a variable and call it in another template:
<xsl:variable name="var_template1">
<xsl:apply-templates select="template1" />
</xsl:variable>
<xsl:apply-templates select="template2">
<xsl:with-param name="var_template1" select=$var_template1 />
</xsl:apply-templates>
<xsl:import> <xsl:include>
Used to import xsl codes from other files, with template override capabilities.
<xsl:choose>
<xsl:when test="attribute::ca = 'l'">
<xsl:text>left</xsl:text>
</xsl:when>
<xsl:when test="attribute::ca = 'c'">
<xsl:text>center</xsl:text>
</xsl:when>
</xsl:choose>
Comments
|
__label__pos
| 0.55994 |
Quantum Pixels: Navigating the Future of Image Compression
0
56
In the vast landscape of digital imagery, the quest for efficient image compression has led to the evolution of revolutionary technologies. Traditional methods have paved the way, but Quantum Pixels are emerging as the beacon of the future, promising unparalleled compression ratios and enhanced image quality. Let’s delve into the intricacies of Quantum Pixels and explore how they are navigating the future of image compression.
I. Introduction
In the digital age, where visuals dominate communication, pdf to 200kb image compression plays a pivotal role in optimizing storage and transmission. Quantum Pixels represent a paradigm shift in this arena, introducing a new dimension to the way we perceive and handle visual data.
A. Brief overview of image compression
Image compression is the process of reducing the size of an image file without compromising its quality. It involves various algorithms and methods to eliminate redundant data, making images more manageable for storage and faster for transmission.
B. Importance of efficient image compression in the digital era
Efficient image compression is crucial for seamless online experiences, from faster loading websites to smooth video streaming. As the demand for high-quality visuals increases, the need for advanced compression technologies becomes more evident.
II. Evolution of Image Compression
A. Traditional methods
Traditional image compression methods, such as JPEG and PNG, have been the backbone of digital imaging for decades. While effective, they face challenges in maintaining a balance between file size and image quality, especially in the era of 4K and 8K visuals.
B. The emergence of Quantum Pixels
Quantum Pixels mark a departure from the classical pixel representation. Leveraging principles of quantum mechanics, they redefine the way visual information is encoded and decoded, promising a quantum leap in compression capabilities.
C. Advancements in quantum computing
The rise of Quantum Pixels is closely tied to advancements in quantum computing. The ability to harness quantum entanglement and superposition allows for novel approaches to data representation, fundamentally different from classical bits and pixels.
III. Understanding Quantum Pixels
A. Definition and concept
Quantum Pixels, or Qixels, represent the smallest unit of visual information in quantum image compression. Unlike classical pixels, which can only be in one state (0 or 1), Qixels can exist in multiple states simultaneously, thanks to quantum superposition.
B. How quantum pixels differ from traditional pixels
Traditional pixels are binary, representing colors in combinations of red, green, and blue. Quantum Pixels, on the other hand, can represent a broader spectrum of colors simultaneously, allowing for richer and more detailed images.
C. Quantum entanglement in image representation
The phenomenon of quantum entanglement enables the correlation between Qixels, even when separated by great distances. This unique property contributes to enhanced compression ratios and improved image reconstruction.
IV. Benefits of Quantum Pixel Compression
A. Enhanced compression ratios
Quantum Pixel Compression surpasses traditional methods by achieving higher compression ratios. The ability of Qixels to exist in multiple states enables a more efficient representation of visual information, reducing file sizes significantly.
B. Improved image quality
While traditional compression methods may introduce artifacts and loss of detail, Quantum Pixels preserve the integrity of visual data. The richer color spectrum and finer details contribute to an overall improvement in image quality.
C. Applications in various industries
The applications of Quantum Pixel Compression extend across diverse industries. From healthcare and scientific imaging to entertainment and virtual reality, Qixels are poised to revolutionize how we perceive and interact with visual content.
V. Challenges and Considerations
A. Current limitations of quantum pixel technology
Despite the promises, Quantum Pixel technology is not without its challenges. Current implementations face issues related to error rates, decoherence, and the need for extremely low temperatures for stable quantum states.
B. Potential solutions and ongoing research
Researchers are actively addressing the challenges faced by Quantum Pixels. Ongoing efforts focus on error correction codes, improved quantum gates, and the development of quantum error correction algorithms to enhance the reliability of quantum image compression.
C. Ethical implications and concerns
As with any emerging technology, Quantum Pixels raise ethical considerations. Issues such as privacy concerns, the potential misuse of quantum-compressed images, and the environmental impact of quantum computing require careful examination and regulation.
|
__label__pos
| 0.999939 |
Compartir a través de
Personalización de WebView
Una Xamarin.FormsWebView es una vista que muestra contenido web y HTML en la aplicación. En este artículo se explica cómo crear un representador personalizado que extienda WebView para permitir la invocación de código de C# desde JavaScript.
Todas las vistas de Xamarin.Forms tienen un representador que las acompaña para cada plataforma y que crea una instancia de un control nativo. Cuando una aplicación de Xamarin.Forms representa un WebView en iOS, se crea una instancia de la clase WkWebViewRenderer, que a su vez crea una instancia del control WkWebView nativo. En la plataforma de Android, la clase WebViewRenderer crea una instancia de un control WebView nativo. En Plataforma universal de Windows (UWP), la clase WebViewRenderer crea una instancia de un control WebView nativo. Para obtener más información sobre el representador y las clases de control nativo a las que se asignan los controles de Xamarin.Forms, vea Clases base y controles nativos del representador.
El siguiente diagrama muestra la relación entre la clase View y los controles nativos correspondientes que la implementan:
Relación entre la clase WebView y sus clases nativas de implementación
El proceso de representación se puede usar para implementar personalizaciones de plataforma mediante la creación de un representador personalizado para un objeto WebView en cada plataforma. Para ello, siga este procedimiento:
1. Cree el control HybridWebView personalizado.
2. Consuma el elemento HybridWebView de Xamarin.Forms.
3. Cree el representador personalizado para el elemento HybridWebView en cada plataforma.
Ahora se describirá cada elemento para implementar un representador de HybridWebView que mejore los objetos Xamarin.FormsWebView para permitir la invocación de código de C# desde JavaScript. Se usa la instancia de HybridWebView para mostrar una página HTML que pide al usuario que escriba su nombre. Luego, cuando el usuario hace clic en un botón HTML, una función de JavaScript invoca a un elemento Action de C# que muestra una ventana emergente que contiene el nombre de los usuarios.
Para más información sobre el proceso de invocación de C# desde JavaScript, vea Invocación de C# desde JavaScript. Para más información sobre la página HTML, vea Creación de la página web.
Nota:
Un objeto WebView puede invocar una función de JavaScript desde C# y devolver cualquier resultado al código de C# que realiza la llamada. Para más información, vea Invocación de JavaScript.
Creación de HybridWebView
El control personalizado HybridWebView se puede crear mediante la creación de subclases de la clase WebView:
public class HybridWebView : WebView
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
}
El control HybridWebView personalizado se crea en el proyecto de biblioteca de .NET Standard y define la siguiente API para el control:
• Una propiedad Uri que especifica la dirección de la página web que se va a cargar.
• Un método RegisterAction que registra un elemento Action con el control. Se invoca a la acción registrada desde el código de JavaScript incluido en el archivo HTML al que hace referencia la propiedad Uri.
• Un método CleanUp que quita la referencia al elemento registrado Action.
• Un método InvokeAction que invoca al elemento registrado Action. Este método se llamará desde un representador personalizado en cada proyecto de plataforma.
Uso de HybridWebView
En XAML, se puede hacer referencia al control personalizado HybridWebView en el proyecto de biblioteca de .NET Standard al declarar un espacio de nombres para su ubicación y usar el prefijo del espacio de nombres en el control personalizado. El siguiente ejemplo de código muestra cómo se puede usar el control personalizado HybridWebView en una página XAML:
<ContentPage ...
xmlns:local="clr-namespace:CustomRenderer;assembly=CustomRenderer"
x:Class="CustomRenderer.HybridWebViewPage"
Padding="0,40,0,0">
<local:HybridWebView x:Name="hybridWebView"
Uri="index.html" />
</ContentPage>
El prefijo de espacio de nombres local puede tener cualquier nombre. Empero, los valores clr-namespace y assembly deben coincidir con los detalles del control personalizado. Después de declarar el espacio de nombres, el prefijo se usa para hacer referencia al control personalizado.
El siguiente ejemplo de código muestra cómo se puede usar el control personalizado HybridWebView en una página C#:
public HybridWebViewPageCS()
{
var hybridWebView = new HybridWebView
{
Uri = "index.html"
};
// ...
Padding = new Thickness(0, 40, 0, 0);
Content = hybridWebView;
}
La instancia de HybridWebView se usa para mostrar un control web nativo en cada plataforma. Su propiedad Uri se establece en un archivo HTML que se almacena en cada proyecto de plataforma y que se mostrará mediante el control web nativo. El HTML representado pide al usuario que escriba su nombre, con una función de JavaScript que invoca a un elemento Action de C# en respuesta a un clic de botón HTML.
HybridWebViewPage registra la acción que se va a invocar desde JavaScript, como se muestra en el ejemplo de código siguiente:
public partial class HybridWebViewPage : ContentPage
{
public HybridWebViewPage()
{
// ...
hybridWebView.RegisterAction(data => DisplayAlert("Alert", "Hello " + data, "OK"));
}
}
Esta acción llama al método DisplayAlert para mostrar un elemento emergente modal que presenta el nombre especificado en la página HTML que muestra la instancia de HybridWebView.
Ahora se puede agregar un representador personalizado a cada proyecto de aplicación para mejorar los controles web de la plataforma si se permite la invocación de código de C# desde JavaScript.
Creación del representador personalizado en cada plataforma
El proceso de creación de la clase de representador personalizada es el siguiente:
1. Cree una subclase de la clase WkWebViewRenderer en iOS y de la clase WebViewRenderer en Android y UWP, que representa el control personalizado.
2. Invalide el método OnElementChanged que representa el objeto WebView y escriba lógica para personalizarlo. Este método se llama cuando se crea un objeto HybridWebView.
3. Agregue un atributo ExportRenderer a la clase del representador personalizado o AssemblyInfo.cs, para especificar que se va a usar para representar el control personalizado de Xamarin.Forms. Este atributo se usa para registrar al representador personalizado con Xamarin.Forms.
Nota:
Para la mayoría de los elementos de Xamarin.Forms, proporcionar un representador personalizado en cada proyecto de la plataforma es un paso opcional. Si no se registra un representador personalizado, se usará el representador predeterminado de la clase base del control. Pero los representadores personalizados son necesarios en cada proyecto de plataforma al representar un elemento View.
El siguiente diagrama muestra las responsabilidades de cada proyecto de la aplicación de ejemplo, junto con las relaciones entre ellos:
Responsabilidades de proyecto del representador personalizado de HybridWebView
El control personalizado HybridWebView se representa mediante clases de representador de la plataforma, que se derivan de la clase WkWebViewRenderer en iOS y de la clase WebViewRenderer en Android y UWP. Esto da lugar a que cada control personalizado HybridWebView se represente con controles web, como se muestra en las capturas de pantalla siguientes:
HybridWebView en cada plataforma
Las clases WkWebViewRenderer y WebViewRenderer exponen el método OnElementChanged, al que se llama cuando se crea el control personalizado de Xamarin.Forms para representar el control web nativo correspondiente. Este método toma un parámetro VisualElementChangedEventArgs que contiene propiedades OldElement y NewElement. Estas propiedades representan al elemento de Xamarin.Forms al que estaba asociado el representador y al elemento de Xamarin.Forms al que está asociado el representador, respectivamente. En la aplicación de ejemplo la propiedad OldElement será null y la propiedad NewElement contendrá una referencia a la instancia HybridWebView.
El lugar para realizar la personalización del control nativo es una versión reemplazada del método OnElementChanged, en cada clase de representador de la plataforma. Mediante la propiedad Xamarin.Forms se puede obtener una referencia al control de Element que se representa.
Cada clase de representador personalizado se decora con un atributo ExportRenderer que registra el representador con Xamarin.Forms. El atributo toma dos parámetros: el nombre de tipo del control personalizado de Xamarin.Forms que se representa y el nombre de tipo del representador personalizado. El prefijo assembly del atributo especifica que el atributo se aplica a todo el ensamblado.
En las secciones siguientes se describe la estructura de la página web cargada por cada control web nativo, el proceso para invocar C# desde JavaScript y su implementación en cada clase de representador personalizado de la plataforma.
Creación de la página web
El ejemplo de código siguiente muestra la página web que va a mostrar el control personalizado HybridWebView:
<html>
<body>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<h1>HybridWebView Test</h1>
<br />
Enter name: <input type="text" id="name">
<br />
<br />
<button type="button" onclick="javascript: invokeCSCode($('#name').val());">Invoke C# Code</button>
<br />
<p id="result">Result:</p>
<script type="text/javascript">function log(str) {
$('#result').text($('#result').text() + " " + str);
}
function invokeCSCode(data) {
try {
log("Sending Data:" + data);
invokeCSharpAction(data);
}
catch (err) {
log(err);
}
}</script>
</body>
</html>
La página web permite que un usuario escriba su nombre en un elemento input y proporciona un elemento button que va a invocar a código de C# cuando se haga clic sobre él. El proceso para lograrlo es el siguiente:
• Cuando el usuario hace clic en el elemento button, se llama a la función de JavaScript invokeCSCode y el valor del elemento input se pasa a la función.
• La función invokeCSCode llama a la función log para mostrar los datos que está enviando al elemento Action de C#. Luego llama al método invokeCSharpAction para invocar al elemento Action de C#, pasando el parámetro recibido desde el elemento input.
La función de JavaScript invokeCSharpAction no está definida en la página web, así que es cada representador personalizado el que la inserta en ella.
En iOS, este archivo HTML se encuentra en la carpeta de contenido del proyecto de la plataforma e incluye una acción de compilación de BundleResource. En Android, este archivo HTML se encuentra en la carpeta de contenido o recursos del proyecto de la plataforma e incluye una acción de compilación de AndroidAsset.
Invocación de C# desde JavaScript
El proceso para invocar a C# desde JavaScript es idéntico en cada plataforma:
• El representador personalizado crea un control web nativo y carga el archivo HTML especificado por la propiedad HybridWebView.Uri.
• Una vez que se ha cargado la página web, el representador personalizado inserta la función de JavaScript invokeCSharpAction en la página web.
• Cuando el usuario escribe su nombre y hace clic en el elemento HTML button, se invoca a la función invokeCSCode, que a su vez invoca a la función invokeCSharpAction.
• La función invokeCSharpAction invoca a un método del representador personalizado, que a su vez invoca al método HybridWebView.InvokeAction.
• El método HybridWebView.InvokeAction invoca al elemento registrado Action.
En las secciones siguientes se habla de cómo se implementa este proceso en cada plataforma.
Creación del representador personalizado en iOS
El ejemplo de código siguiente muestra el representador personalizado para la plataforma iOS:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace CustomRenderer.iOS
{
public class HybridWebViewRenderer : WkWebViewRenderer, IWKScriptMessageHandler
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}";
WKUserContentController userController;
public HybridWebViewRenderer() : this(new WKWebViewConfiguration())
{
}
public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
{
userController = config.UserContentController;
var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript(script);
userController.AddScriptMessageHandler(this, "invokeAction");
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
HybridWebView hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
string filename = Path.Combine(NSBundle.MainBundle.BundlePath, $"Content/{((HybridWebView)Element).Uri}");
LoadRequest(new NSUrlRequest(new NSUrl(filename, false)));
}
}
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
((HybridWebView)Element).InvokeAction(message.Body.ToString());
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((HybridWebView)Element).Cleanup();
}
base.Dispose(disposing);
}
}
}
La clase HybridWebViewRenderer carga la página web especificada en la propiedad HybridWebView.Uri en un control nativo WKWebView y la función de JavaScript invokeCSharpAction se inserta en la página web. Una vez que el usuario escribe su nombre y hace clic en el elemento HTML button, se ejecuta la función de JavaScript invokeCSharpAction y se llama al método DidReceiveScriptMessage después de que se reciba un mensaje de la página web. A su vez, este método invoca al método HybridWebView.InvokeAction, que invoca a la acción registrada para mostrar la ventana emergente.
Esta funcionalidad se logra del siguiente modo:
• El constructor del representador crea un objeto WkWebViewConfiguration y recupera su objeto WKUserContentController. El objeto WkUserContentController permite publicar mensajes e insertar scripts de usuario en una página web.
• El constructor del representador crea un WKUserScript objeto, que inserta la función invokeCSharpAction de JavaScript en la página web después de cargarla.
• El constructor del representador llama al método WKUserContentController.AddUserScript para agregar el objeto WKUserScript al controlador de contenido.
• El constructor del representador llama al método WKUserContentController.AddScriptMessageHandler para agregar un controlador de mensajes de script denominado invokeAction al objeto WKUserContentController, lo que hace que la función window.webkit.messageHandlers.invokeAction.postMessage(data) de JavaScript se defina en todos los marcos de todas las instancias de WebView en las que se usa el objeto WKUserContentController.
• Siempre que el representador personalizado está asociado a un nuevo elemento de Xamarin.Forms:
• El método WKWebView.LoadRequest carga el archivo HTML especificado por la propiedad HybridWebView.Uri. El código especifica que el archivo se almacena en la carpeta Content del proyecto. Una vez que se muestra la página web, la función de JavaScript invokeCSharpAction se inserta en la página web.
• Los recursos se liberan cuando cambia el elemento al que está asociado el representador.
• El elemento de Xamarin.Forms se limpia cuando se desecha el representador.
Nota:
La clase WKWebView solo se admite en iOS 8 y versiones posteriores.
Además, Info.plist debe actualizarse para que incluya los siguientes valores:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Creación del representador personalizado en Android
El siguiente ejemplo de código muestra el representador personalizado para la plataforma de Android:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace CustomRenderer.Droid
{
public class HybridWebViewRenderer : WebViewRenderer
{
const string JavascriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";
Context _context;
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
Control.RemoveJavascriptInterface("jsBridge");
((HybridWebView)Element).Cleanup();
}
if (e.NewElement != null)
{
Control.SetWebViewClient(new JavascriptWebViewClient(this, $"javascript: {JavascriptFunction}"));
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.LoadUrl($"file:///android_asset/Content/{((HybridWebView)Element).Uri}");
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((HybridWebView)Element).Cleanup();
}
base.Dispose(disposing);
}
}
}
La clase HybridWebViewRenderer carga la página web especificada en la propiedad HybridWebView.Uri en un control nativo WebView y la función de JavaScript invokeCSharpAction se inserta en la página web, una vez que la página web ha terminado de cargarse, con la invalidación OnPageFinished en la clase JavascriptWebViewClient:
public class JavascriptWebViewClient : FormsWebViewClient
{
string _javascript;
public JavascriptWebViewClient(HybridWebViewRenderer renderer, string javascript) : base(renderer)
{
_javascript = javascript;
}
public override void OnPageFinished(WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
}
}
Una vez que el usuario escribe su nombre y hace clic en el elemento HTML button, se ejecuta la función de JavaScript invokeCSharpAction. Esta funcionalidad se logra del siguiente modo:
• Siempre que el representador personalizado está asociado a un nuevo elemento de Xamarin.Forms:
• El método SetWebViewClient establece un nuevo objeto JavascriptWebViewClient como la implementación de WebViewClient.
• El método WebView.AddJavascriptInterface inserta una nueva instancia de JSBridge en el marco principal del contexto de JavaScript de WebView y le asigna el nombre jsBridge. Esto permite acceder a los métodos de la clase JSBridge desde JavaScript.
• El método WebView.LoadUrl carga el archivo HTML especificado por la propiedad HybridWebView.Uri. El código especifica que el archivo se almacena en la carpeta Content del proyecto.
• En la clase JavascriptWebViewClient, la función de JavaScript invokeCSharpAction se inserta en la página web una vez que esta termina de cargarse.
• Los recursos se liberan cuando cambia el elemento al que está asociado el representador.
• El elemento de Xamarin.Forms se limpia cuando se desecha el representador.
Cuando se ejecuta la función de JavaScript invokeCSharpAction, a su vez invoca al método JSBridge.InvokeAction, que se muestra en el ejemplo de código siguiente:
public class JSBridge : Java.Lang.Object
{
readonly WeakReference<HybridWebViewRenderer> hybridWebViewRenderer;
public JSBridge(HybridWebViewRenderer hybridRenderer)
{
hybridWebViewRenderer = new WeakReference<HybridWebViewRenderer>(hybridRenderer);
}
[JavascriptInterface]
[Export("invokeAction")]
public void InvokeAction(string data)
{
HybridWebViewRenderer hybridRenderer;
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out hybridRenderer))
{
((HybridWebView)hybridRenderer.Element).InvokeAction(data);
}
}
}
La clase debe derivar de Java.Lang.Object y los métodos que se exponen a JavaScript deben decorarse con los atributos [JavascriptInterface] y [Export]. Por lo tanto, cuando se inserta la función de JavaScript invokeCSharpAction en la página web y se ejecuta, llama al método JSBridge.InvokeAction, puesto que está decorado con los atributos [JavascriptInterface] y [Export("invokeAction")]. A su vez, el método InvokeAction invoca al método HybridWebView.InvokeAction, que invocará a la acción registrada para mostrar la ventana emergente.
Importante
En los proyectos de Android en los que se use el atributo [Export] se debe incluir una referencia a Mono.Android.Export, o bien se producirá un error del compilador.
Tenga en cuenta que la clase JSBridge mantiene un elemento WeakReference para la clase HybridWebViewRenderer. Esto es para evitar la creación de una referencia circular entre las dos clases. Para más información, vea Referencias débiles.
Creación del representador personalizado en UWP
En el siguiente ejemplo de código se muestra el representador personalizado para UWP:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace CustomRenderer.UWP
{
public class HybridWebViewRenderer : WebViewRenderer
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.external.notify(data);}";
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
Control.NavigationCompleted -= OnWebViewNavigationCompleted;
Control.ScriptNotify -= OnWebViewScriptNotify;
}
if (e.NewElement != null)
{
Control.NavigationCompleted += OnWebViewNavigationCompleted;
Control.ScriptNotify += OnWebViewScriptNotify;
Control.Source = new Uri($"ms-appx-web:///Content//{((HybridWebView)Element).Uri}");
}
}
async void OnWebViewNavigationCompleted(Windows.UI.Xaml.Controls.WebView sender, WebViewNavigationCompletedEventArgs args)
{
if (args.IsSuccess)
{
// Inject JS script
await Control.InvokeScriptAsync("eval", new[] { JavaScriptFunction });
}
}
void OnWebViewScriptNotify(object sender, NotifyEventArgs e)
{
((HybridWebView)Element).InvokeAction(e.Value);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((HybridWebView)Element).Cleanup();
}
base.Dispose(disposing);
}
}
}
La clase HybridWebViewRenderer carga la página web especificada en la propiedad HybridWebView.Uri en un control nativo WebView y la función de JavaScript invokeCSharpAction se inserta en la página web, una vez cargada, con el método WebView.InvokeScriptAsync. Una vez que el usuario escribe su nombre y hace clic en el elemento HTML button, se ejecuta la función de JavaScript invokeCSharpAction y se llama al método OnWebViewScriptNotify después de que se reciba una notificación de la página web. A su vez, este método invoca al método HybridWebView.InvokeAction, que invoca a la acción registrada para mostrar la ventana emergente.
Esta funcionalidad se logra del siguiente modo:
• Siempre que el representador personalizado está asociado a un nuevo elemento de Xamarin.Forms:
• Se registran controladores de eventos para los eventos NavigationCompleted y ScriptNotify. El evento NavigationCompleted se desencadena cuando el control nativo WebView ha terminado de cargar el contenido actual o si se ha producido un error de navegación. El evento ScriptNotify se desencadena cuando el contenido del control nativo WebView usa JavaScript para pasar una cadena a la aplicación. La página web desencadena el evento ScriptNotify mediante una llamada a window.external.notify al pasar un parámetro string.
• La propiedad WebView.Source está establecida en el URI del archivo HTML especificado por la propiedad HybridWebView.Uri. El código da por supuesto que el archivo está almacenado en la carpeta Content del proyecto. Una vez que se muestra la página web, se desencadena el evento NavigationCompleted y se invoca al método OnWebViewNavigationCompleted. La función de JavaScript invokeCSharpAction se inserta en la página web con el método WebView.InvokeScriptAsync, siempre que la navegación se haya realizado correctamente.
• La suscripción de los eventos se cancela cuando cambia el representador al que está adjunto el elemento.
• El elemento de Xamarin.Forms se limpia cuando se desecha el representador.
|
__label__pos
| 0.607922 |
Asp.Net Core中5种异常处理方案
异常处理在编程中非常重要,一来可以给用户友好提示,二来也是为了程序安全。在Asp.Net Core中,默认已经为我们了提供很多解决方案,下面就来总结一下。
一,继承Controller,重写OnActionExecuted
使用vs新建controller时,默认都会继承一个Controller类,重写OnActionExecuted,添加上异常处理即可。一般情况下我们会新建一个BaseController, 让所有Controller继承BaseController。代码如下
public class BaseController : Controller
{
public override void OnActionExecuted(ActionExecutedContext context)
{
var exception = context.Exception;
if (exception != null)
{
context.ExceptionHandled = true;
context.Result = new ContentResult
{
Content = $"BaseController错误 : { exception.Message }"
};
}
base.OnActionExecuted(context);
}
}
这种处理方式优点当然是简单,缺点也很明显,如果cshtml页面抛错,就完全捕获不了。当然如果项目本身就是一个web api 项目,没有view,这还是可以的。
二,使用 ActionFilterAttribute
ActionFilterAttribute是一个特性,本身实现了 IActionFilter 及 IResultFilter , 所以不管是action里抛错,还是view里抛错,理论上都可以捕获。我们新建一个 ExceptionActionFilterAttribute, 重写 OnActionExecuted及OnResultExecuted,添加上异常处理,完整代码如下。
public class ExceptionActionFilterAttribute:ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
var exception = context.Exception;
if (exception != null)
{
context.ExceptionHandled = true;
context.Result = new ContentResult
{
Content = $"错误 : { exception.Message }"
};
}
base.OnActionExecuted(context);
}
public override void OnResultExecuted(ResultExecutedContext context)
{
var exception = context.Exception;
if (exception != null)
{
context.ExceptionHandled = true;
context.HttpContext.Response.WriteAsync($"错误 : {exception.Message}");
}
base.OnResultExecuted(context);
}
}
使用方式有两种,
1. 在controller里打上 [TypeFilter(typeof(ExceptionActionFilter)] 标签。
2. 在Startup里以filter方式全局注入。
services.AddControllersWithViews(options =>
{
options.Filters.Add<ExceptionActionFilterAttribute>();
})
三,使用 IExceptionFilter
我们知道, Asp.Net Core提供了5类filter, IExceptionFilter是其中之一,顾名思义,这就是用来处理异常的。Asp.net Core中ExceptionFilterAttribute已经实现了IExceptionFilter,所以我们只需继承ExceptionFilterAttribute,重写其中方法即可。 同样新建CustomExceptionFilterAttribute继承 ExceptionFilterAttribute,重写 OnException ,添加异常处理,完整代码如下
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
context.ExceptionHandled = true;
context.HttpContext.Response.WriteAsync($"CustomExceptionFilterAttribute错误:{context.Exception.Message}");
base.OnException(context);
}
}
注意,ExceptionFilterAttribute还提供了异步方法OnExceptionAsync,这两个处理方法,只需重写一个即可,如果两个都重写,两个方法都会执行一次。
使用方式有两种,
1. 在controller里打上 [CustomExceptionFilter] 标签。
2. 在Startup里以filter方式全局注入。
services.AddControllersWithViews(options =>
{
options.Filters.Add<CustomExceptionFilterAttribute>();
})
四,使用ExceptionHandler
在 startup 里,vs新建的项目会默认加上
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
上边这段代码,大意为:开发环境使用app.UseDeveloperExceptionPage(); 。生产环境会跳转至 home/error 页面。
UseDeveloperExceptionPage 会给出具体错误信息,具体包括 Stack trace、Query、Cookies、Headers 四部分。.net core 3.1后有些改动,如果请求头加上 accept:text/html, 就返回html页面,不加的话,只会返回错误。
注意:app.UseDeveloperExceptionPage(); 应该置于最前边。
if (!env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
await context.Response.WriteAsync($"error:{exceptionHandlerPathFeature.Error.Message}");
});
});
}
五,自定义Middleare处理
通过middleware全局处理。
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (System.Exception ex)
{
//处理异常
}
}
}
出自:网站“.NET技术栈”
原文作者:the7
原文标题:Asp.Net Core中5种异常处理方案
原文链接:https://ut32.com/post/handle-exception
原文出处:.NET技术栈【the7】
原文链接:https://ut32.com/post/handle-exception
本文观点不代表Dotnet9立场,转载请联系原作者。
发表评论
登录后才能评论
|
__label__pos
| 0.998449 |
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 trying to create multiple database tables in android where each table will represent an account. I am struggling to get more then one table per database
Would anyone have any sample code they could show me? Or any suggestions?
Thanks
share|improve this question
4 Answers 4
up vote 2 down vote accepted
I don't know anything about your app, but the way you're designing your database schema sounds a little questionable. Does creating a table for every account (whatever an "account" might be) really make the most sense?
Regardless, creating tables in SQLite is pretty straightforward. In your SQLiteOpenHelper class, you can call db.execSQL(CREATE_TABLE_STATEMENT) to create a table, where CREATE_TABLE_STATEMENT is your SQL statement for a particular table. You can call this for every table you need created. This is typically going to be called in your SqliteOpenHelper's onCreate method when the database is initialized, but you can call it outside of the helper as well.
share|improve this answer
See I am not too sure how to format the database. I was thinking each account have its own table with all the transactions listed on it which seems to be the easiest. – Vuzuggu Mar 10 '12 at 0:01
1
Again, I'm not sure what an account is exactly in your case, but a table-per-account design is not a good choice. What happens when you have 100,000 accounts? Do you have 100,000 tables? Why not have an accounts table and a transactions table. The transactions table then references the accounts table using a foreign key. – Tyler Treat Mar 10 '12 at 0:04
there would only be 2-3 accounts with anywhere from 1 to 10,000 transactions on each so would be the easiest way. – Vuzuggu Mar 10 '12 at 0:12
If you are going to use a fair amount of tables and data, including a prepopulated database in your assets folder is another way to go.
share|improve this answer
When I started to use databases on android I found this very helful.
http://developer.android.com/resources/tutorials/notepad/index.html
ps now that you mentioned that there are only 2-3 accounts, creating one table/account sounds much more reasonable than first expected.
But it really depends on what you are planning to do with the data and where your performance requirements are. One could even use one single table or as well multiple tables for each (fixed) type of transaction - if the data for transaction types have very different structure.
share|improve this answer
Creating database table in Android is pretty straghtforward: db.execSQL(CREATE_TABLE_STATEMENT); where db is SQLiteDatabase object and CREATE_TABLE_STATEMENT is your create table sql statement
As in your question you did not explain clearly the requirement of your app, but I can see a few cons in your approach of creating one table for each user
1. If there are many users created, u will have many tables in ur database
2. If later on you have some information, settings that would be shared across some users or all user, you will have to replicate them in every user single table.
My recommendation would be you have one table for users, and another table for transactions with one column is user_id to link back to the user table. It would be easier to expand or maintain your database later.
Hope it helps :)
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.642775 |
Questions on the various algorithms used in linear algebra computations (matrix computations).
learn more… | top users | synonyms
0
votes
1answer
70 views
LU Factorization of a full rank square matrix.
If A is an invertible matrix then a necessary and sufficient condition for the LU Factorization to exist is : If A is invertible, then it admits an LU (or LDU) factorization if and only if all its ...
0
votes
0answers
27 views
SVM optimisation problem, finding w
I am finding it difficult to find the value for vector w (weight) for the optimization problem which is: $\min \{ (1/2) * w^T * w : y(i) * w^T * x(i) > 0, \ i = 1,\dots,m\}.$ Can someone ...
0
votes
2answers
36 views
Simplifying the function
Identify for which values of $x$ there is subtraction of nearly equal numbers, and find an alternate form that avoids the problem: $$E = \frac{1}{1+x} - \frac{1}{1-x} = -\frac{2x}{1-x^2} = \frac{2x}{x^...
0
votes
0answers
13 views
Let a and $a_1,…,a_m$ be given vectors i n $\mathbb R^n$ .
Show that two statement are equivalent. (a) For all x ≥ 0 , we have $a'x≤ max a'_ix.$ (b) There exist nonnegative coefficients $b_i$ that sum to 1 and such that $a \le \sum_{i=1}^m b_i a_i $ can ...
5
votes
0answers
51 views
Maximizing the pairwise Frobenuis distance between M othrogonal matrices
I want to maximize the pairwise Frobenius distance between $M$ orthogonal matrices. That is, I'm looking for $Q_{i}, i = 1, 2, ... M$ such that \begin{equation*} \begin{aligned} & \underset{ 1 \...
0
votes
1answer
27 views
Derive formula for condition (A)
Consider the linear system $Ax=b$ where $$ A = \begin{bmatrix}2&4\\1&2+\varepsilon\end{bmatrix} $$ 1) Derive a formula for $\operatorname{cond}_1 ( A )$, the $1$-norm condition number of $A$....
1
vote
1answer
21 views
How do I find a Solution Common to Many Linear Systems?
So I have the following equation: $$ \sum_{n=1}^{N} S_n f_n(x,y,z) = g(x,y,z) $$ And then for every particular set $\xi$ of $N$ random $(x,y,z)$ points, $\forall x,y,z \in {\mathbb R} $, I can ...
1
vote
1answer
31 views
Calculating $k$ algebraically smallest eigenvalues of a real symmetric matrix
I have a very big matrix assume $1000 \times 1000$. I want to find $k$ of its algebraically smallest eigenvalues where $k$ is $2$ or $3$. I am using MATLAB to solve this problem. My Try: I try to ...
1
vote
1answer
33 views
Proof for error analysis
I am trying to proof the following equality for matrix error analysis. Sorry for all the syntax. I am new to math stack. Thanks in advance. $$b = Ax$$ $r = A(x-\hat{x})$, where $\hat{x} =$ ...
0
votes
1answer
40 views
Elimination problem with polynomial equations involving multiple variables
Hi guys I am very stuck with this problem. I am trying to eliminate 2 out of the three variables it does not matter which one remains, I personally tried keep x and eliminate the others. My question ...
1
vote
0answers
18 views
Solving a system of PDE by fixed point Gauss-seidel iteration method
I have the following system of PDE $$ u-u_0=\operatorname{div}\left(\frac{\nabla u-w}{|\nabla u-w|}\right) \tag 1 $$ $$ \frac{w-\nabla u}{|w-\nabla u|} = \operatorname{div}\left(\frac{\nabla w}{|\...
-1
votes
1answer
55 views
Chebyshev interpolation vs equally spaced interpolation [closed]
Which one is better to use and why? What's the advantage of Chebyshev interpolation over equally spaced interpolation and vice versa?
0
votes
1answer
94 views
Rayleigh quotients being the diagonal entry of a matrix after orthogonal transformation
So there's this problem in Numerical linear algebra by Trefethan and Bau a textbook I am reading. (It's great! basically taught me MATLAB and some great numerical methods, its also free!) The ...
1
vote
1answer
30 views
Separable linear programs
Assume, we have two distinct LPs: \begin{equation*} \begin{aligned} & \text{min}_{x_1} & & c_1^Tx_1 \\ & \text{subject to} & & A_1x_1 = b \\ & & & x_1 \geq 0 \\ \...
0
votes
1answer
33 views
Under-determined linear system, showing any solution can be written as $x_{0} + Zw$
In my notes for under-determined linear systems, the following is just given as fact, but I've restructured it as a question because I don't quite understand it. Consider $Ax=b$ where $A$ is an $...
1
vote
0answers
50 views
Given a CRS stored matrix A, provide an algorithm for calculating vector u.
Given an $NxN$ matrix $A$ and vectors $u,v,b$ such that: $$u_i = {\frac1{a_{ii}}}(b_i - \sum_{j=1,j\neq{i}}^n a_{ij}v_i)$$ And considering $A$ is stored using CRS, provide an algorithm (or pseudocode)...
0
votes
0answers
21 views
number of iterations for the generalized conjugate residuals method?
I have the matrix $n \times n $ defined as: $A=\begin{bmatrix} 0 & 1 & 0 & \dots& 0 \\ 0 & 0 & 1 & \dots &0 \\ \dots &\dots ...
0
votes
0answers
23 views
Generalized conjugate residuals method applied to a block matrix
I have the diagonal block matrix A with $2 \times 2$ k-blocks given by : $D_k=\begin{bmatrix} 1 & k\\ 0 & 1 \end{bmatrix} $. I have to show that the generalized ...
0
votes
1answer
39 views
How many divisions needed for LU Decomposition of a square matrix
If a general matrix is of dimensions $n \times n$, how many divisions are needed to compute the LU Decomposition of this matrix? Can we say zero divisions are needed (it can be done with only ...
0
votes
1answer
94 views
Hyperplane Matrix Linear transformation
Let $$u =\begin{bmatrix}u_1\\.\\.\\.\\u_n\end{bmatrix}$$ be a nonzero vector in $\mathbb R^n$, and let $T:\mathbb R^n \to \mathbb R^n$ be the linear transformation given by $T(x) = u^\top x$. Show ...
0
votes
2answers
43 views
Relation between perturbed matrix and condition number of the matrix
If A is non‐singular but the perturbed matrix (A+δA) is singular, then show that $$∥A∥/∥δA∥≤y $$ Where y is condition number of the matrix A. Tried for a solution The relation $$(A+δA)(x+δx)=b $$ ...
0
votes
1answer
27 views
Power Method: Showing convergence to dominant eigenvector
What follows is taken from Numerical Analysis, by R. Burden and D. Faires: Let $A\in \mathbb{R}^{n\times n}$, with eigenvalues $\lambda_1,\dots,\lambda_n$ such that $|\lambda_1|>|\lambda_2|\ge |\...
0
votes
0answers
21 views
Conjugate gradient method and rietz values
I'm working on the conjugate gradient method. I have the matrix A, defined as A= diag(v) where $v=[ones(1,10), 11:1000]$. I have to solve the system $Ax=b$ ,b=ones(1000,1) with the conjugate ...
1
vote
1answer
53 views
What is the largest floating point number a so that fl(100 + a) = 100?
What is the largest floating point number a so that fl(100 + a) = 100? Here is how float number is computed. $fl(a ⊙ b) = (a ⊙ b)(1 + δ)$. Where $|δ| ≤ ε$. Furthermore, $ε = 2^{-53}$. My thought ...
2
votes
0answers
26 views
Looking for matrices such that $\kappa(A) =1$
Looking clues for this problem. Find all the matrices such that $\kappa(A) = 1$ We define $\kappa(A) = \|A\|\,\|A^{-1}\|$. If I'm looking matrices such that $\kappa(A) = 1$, I was thinking in ...
0
votes
0answers
40 views
Find the inverse of $A+uB+vC+uvD+u^2E+v^2F$ where $A,B,C,D,E,F$ are symmetric.
Given scalars $u,v$ s.t. $0<u,v<1$, we seek the properties of the matrix defined by $$P=A+uB+vC+uvD+u^2E+v^2F$$ A is symmetric and positive definite. $B,C,D,E,F$ are symmetric, but might not ...
0
votes
1answer
52 views
Symmetric Gauss Seidel iteration
Let $A=L+D+R$, where $L$ is a strict lower triangular, $D$ a diagonal and $R$ an strict upper triangular matrix. Consider the symmetric Gauss Seidel iteration: \begin{align*} (L+D)x^{(k+1/2)}+Rx^{(k)...
0
votes
0answers
10 views
How to find How to find ΔU if LU factorization of tridiagonal Matrix A is used to sovle system Ax=b?
How to find ΔU if LU factorization of tridiagonal Matrix A is used to solve system Ax=b? By using forward and back substitution to show that x̂ satisfies (L̂+ΔL)...
0
votes
1answer
42 views
What comes after sorting eigenvalues in PCA?
I'm a student, I have to build PCA from scratch using Matlab on iris data. Iris data have 4 features, I want to reduce them to 2. I reached the sorting of eigenvalues step. What is the next step?
0
votes
1answer
34 views
Linear Algebra Complex
A homogonous linear system is given by: x1 + x2 = 0 a · x2 + x3 = 0 2·x1 + x2 + a·x3 =0 where a ∈ C, a) Find the determinant of A and give the values of a for which matrix A is ...
0
votes
1answer
22 views
How to have a consistent or inconsistent linear algebra equation?
I have been a bit confused about this linear algebra question, if someone can explain it would be great. So my professor is asking us to determine all values of x for which the linear system a, is ...
0
votes
0answers
112 views
How to decide if a system is ill conditioned when the matrix condition number is very different for different norms?
A linear system Ax=b is said to be ill-conditioned if the condition number (A)of the coefficient matrix A is far from 1. Consider the system $$\begin{align}x_1 = &b_1 \\ x_1+x_2 = &b_2 \\ ...
0
votes
1answer
47 views
Successive over-relaxation vs conjugate gradient
What is the advantages of successive over-relaxation and conjugate gradient methods over each other? When should I use one of them over the other? Here the discussion is limited to solving linear ...
0
votes
0answers
25 views
How to find Common (invariant) Subspace between more than two Hankel Matrices?
Note: I am not a mathematician but a control engineer. A general nonlinear $n_{a}^{th}$ order discrete-time state-space model is described by the following equations: \begin{align} ...
0
votes
0answers
20 views
Prove if a square root of a Herimitian positive semi-definite matrix is also Herimitian positive semi-definite, then it is unique.
Prove if a square root of a Herimitian positive semi-definite matrix is also Herimitian positive semi-definite, then it is unique. Here is what I have done so far: By the spectrum theorem, suppose $...
0
votes
0answers
28 views
LU Decomposition simplification on a tridiagonal matrix
If I have a tridiagonal matrix that looks like Tn = diag[1, 3, 1], I can do LU Decomposition of it using n - 1 multiplications (by omitting multiplications with 1) but not n - 1 divisions, right? In ...
0
votes
0answers
22 views
A problem about the condition number
Given that $I\in R^{n\times n}$ is identity matrix and $||I||=1$.Assumed that Matrix $A\in R^{n\times n}$ is nonsingular,with $\delta A$ satisfying $||A^{-1}||||\delta A||<1$. Then $A+\delta A$ is ...
2
votes
1answer
23 views
Issue with trigonometry identity related to condition number of matrix
So, in attempting to compute the condition number for the 2-norm of a matrix, I have stumbled upon a problem i can't resolve. I have the formula $$ \frac{1-\cos\left(\frac{n}{n+1} \pi\right)}{1-\...
3
votes
1answer
41 views
partition of block matrices
If $A=\begin{bmatrix} A_{11} & A_{12} \\ A_{21} & A_{22} \\ \end{bmatrix}$ is a partition of $A$ such that $A_{11}$ and $A_{22}$ are $r × r$ and $(n − r) × (n − r)$ ...
0
votes
2answers
40 views
Show that n(n+1)/2 multiplications are required
$a_{11}x_1$+$a_{12}x_2$+$a_{13}x_3$+ ...+ $a_{1,n-1}x_{n-1}$+$a_{1n}x_n$ =$b_1$ $a_{22}x_2$+$a_{23}x_3$+ ...+ $a_{2,n-1}x_{n-1}$+$a_{2n}x_n$ =$b_2$ $a_{33}x_3$+ ...+ $a_{3,n-1}x_{n-1}$+$a_{3n}x_n$ =$...
0
votes
0answers
17 views
Question related to matrix transformation in sequence spaces.
Let $M=[K_{i,j}]$ be an infinite matrix, where $K_{ij}=1/i \text{ if } 1\leq i \leq j \text{ and } K_{ij}=0 \text{ if } i>j\geq 1$. Then $M$ defines a map $\ell^p \to \ell^r$ iff $p=1 \text{ and } ...
0
votes
0answers
15 views
convergnece of QR-method
I'm studying the QR-algorithm. In particular I have this algorithm: For every $k=0..n $ select a shift $\sigma_k$ factorize $A_k-\sigma_k I =Q_kR_k$ multiply $A_{k+1}=R_k Q_k+\sigma_kI$ muliply ...
0
votes
1answer
57 views
Guaranteeing Invertibility with Banach Lemma
I'm trying to find an $\epsilon$ for which the Banach Lemma guarantees $I_n + ɛA_n$ is Invertible, where $A_n$ is a matrix of $1$'s, and $I_n$ is the identity matrix, and $n$ can be any dimension. $...
1
vote
1answer
104 views
Prove that Q is also upper Hessenberg in A = QR
Background: Suppose $\mathbf{A}$ is an $n \times n$ matrix and it is upper Hessenberg. Using QR-factorization, we have $\mathbf{A=QR}$, where $\mathbf{R}$ is an upper triangular matrix and $\mathbf{...
1
vote
0answers
237 views
GAXPY Operations
Let A ∈$R^2$, x ∈ $R^k$. Find the first column of M = (A − x1I)(A − x2I)...(A − xkI) using a sequence of GAXPY’s operations. GAXPY: General matrix A multiplied by a vector X plus a vector Y. I tried ...
0
votes
0answers
45 views
Compression of a matrix A by V
I can't understand and even can't find any text on Compression of a matrix A by V. meaning if $B=V^*AV$ then B is called the compression of A. What does it mean???
1
vote
1answer
42 views
Householder reflection
Let $\tau \in \mathbb C$, $x,y,v \in \mathbb C^n$. I have to show that if i) $|\tau| =\frac{ \|x \|_2}{\|y\|_2}$, ii) $\tau x^H y \in \mathbb R $ iii) $ \rho( x-\tau y)=v$ with $|p|=\frac{1}{\|x-...
1
vote
2answers
48 views
Inverse of a block matrix with particular entries
Good afternoon; I have the following block matrix: $X$ = $$\pmatrix{U&M\\M&V}$$ Where $U,V,M$ are square matrices of size $n\times n $, and it holds: $U^2 = V^2 = M^2 = I$ ; with $I$: ...
1
vote
3answers
67 views
Matrix Norm Proofs: Dropping the “max” term and denominator
To prove that $||A||_{\infty}≤\sqrt{n}||A||_{2}$, this math.exchange proof does the following: $$||A(x)||_{\infty}≤ ||A(x)||_{2}≤||A||_{2}||x||_{2}≤||A||_{2}\sqrt{n}||x||_{\infty}$$ Given the ...
0
votes
0answers
41 views
Solving for intersection of line and a vector function.
How would one approach a problem of finding intersection points between a line $\vec l = \vec S + d \vec t$ and vector of the form $$\vec v = \begin{pmatrix} x \\ y \\f(x, y) \end{pmatrix}$$ I am ...
|
__label__pos
| 0.990119 |
How to copy, cut, paste, and delete audio in Audition
Copy or cut audio data
1. In the Waveform Editor, select the audio data you want to copy or cut. Or, to copy or cut the entire waveform, deselect all audio data.
2. Choose one of the following:
• Edit > Copy to copy audio data to the clipboard.
• Edit > Copy To New to copy and paste the audio data into a newly created file.
• Edit > Cut to remove audio data from the current waveform and copy it to the clipboard.
Paste audio data
1. Do either of the following:
• To paste audio into the current file, place the current-time indicator where you want to insert the audio or select existing audio you want to replace. Then choose Edit > Paste.
• To paste audio data into a new file, choose Edit > Paste To New. The new file automatically inherits the sample type (rate and bit depth) from the original clipboard material.
Mix audio data when pasting
The Mix Paste command mixes audio data from the clipboard with the current waveform.
1. In the Editor panel, place the current-time indicator where you want to start mixing the audio data. Alternately, select the audio data you want to replace.
2. Choose Edit > Mix Paste.
3. Set the following options and click OK.
Copied and Existing Audio
Adjust the percentage volume of copied and existing audio.
Invert Copied Audio
Reverses the phase of copied audio, either exaggerating or reducing phase cancellation if the existing audio contains similar content. (To understand phase cancellation, see How sound waves interact.)
Crossfade
Applies a crossfade to the beginning and end of the pasted audio, producing smoother transitions. Specify the fade length in milliseconds.
Paste Type | Audition CC
Specify the paste type. The options are as follows:
Insert
Inserts audio at the current location or selection. Adobe Audition inserts audio at the cursor location, moving any existing data to the end of the inserted material.
Overlap (Mix)
Mixes audio at the selected volume level with the current waveform. If the audio is longer than the current waveform, the current waveform is lengthened to accommodate the pasted audio.
Overwrite
Overdubs the audio beginning at the cursor location, and replaces the existing material thereafter for the duration of audio. For example, pasting 5 seconds of material replaces the first 5 seconds after the cursor.
Modulate
Modulates the audio with the current waveform for an interesting effect. The result is similar to overlapping, except that the values of the two waveforms are multiplied by each other, sample by sample, instead of added.
From Clipboard
Pastes audio data from the active internal clipboard.
From File
Pastes audio data from a file. Click Browse to navigate to the file.
Loop Paste
Pastes audio data the specified number of times. If the audio is longer than the current selection, the current selection is automatically lengthened accordingly.
Delete or crop audio
1. Do one of the following:
• Select audio you want to delete, and choose Edit > Delete.
• Select audio you want to keep, and choose Edit > Crop. (Unwanted audio at the beginning and end of the file is removed.)
Adobes logotyp
Logga in på ditt konto
|
__label__pos
| 0.897675 |
Contact us Career
Report
blockchain in telecom market north america
North America Blockchain in Telecom Market Forecast upto 2025
To Be Published: May, 2020
Blockchain is a distributed ledger technology developed on a shared network infrastructure that can permanently record transactions between parties. In telecommunication applications, with the support of blockchain technology, the data can be shared between users without the need for any centralized authorization. Blockchain links the record by using cryptography that offers a more secure and scalable environment by storing subscriber identity information more securely. In a multi-partnered communication network environment, blockchain technology enables each operator to have access to other operators through a registry of public keys for each operator. Additionally, CSP’s supply chain integrated with blockchain offers enhanced visibility to network participants and helps to execute efficient SLA-based contracts.
Market Dynamics – North America Blockchain in Telecom Market
Increasing demand for ancillary digital technologies that enables telecommunication operators to enhance security, transparency, visibility, and efficiency across operations is the key factor contributing to the growth of the North America Blockchain in the telecom market. Increasing interest in optimizing the order to provisioning process and growing focus on eliminating the manual reconciliation activities/tasks is expected to accelerate the growth of the North America Blockchain in telecom market.
North America Blockchain in Telecom Market
An increase in the number of consortia, such as Hyperledger and Carrier Blockchain Study Group (CBSG), focusing on integrating blockchain to telecom and the growing number of start-ups focused on developing telco-grade blockchain solutions are anticipated to fuel the growth of the North America blockchain in telecom market. However, lack of common industry-standards telco-grade blockchain solutions is identified as restraints likely to deter the progression of the North America blockchain in telecom market during the forecast period.
Market Segmentation – North America Blockchain in Telecom Market
The North America blockchain in telecom market is segmented based on providers, applications, organization size, and by country. Based on providers, the North America blockchain in telecom market is segmented into application providers, middleware providers, and infrastructure providers. Based on application, the North America blockchain in telecom market is segmented into smart contracts, streamlining OSS and BSS processes, identity and fraud management, payments, secure connectivity, and others.
North America Blockchain in Telecom
Country-level Outlook – North America Blockchain in Telecom Market
In terms of country-wise analysis, the North America blockchain in telecom market is segmented into US and Canada. The US dominates the North America blockchain in telecom market and is expected to maintain its market dominance throughout the forecast period. This is mainly due to the increasing focus on improving security, transparency, and visibility across network operations.
Benefits and Vendors – North America Blockchain in Telecom Market
The study on the North America blockchain in telecom market contains an in-depth analysis of vendors, which includes financial health, business units, key business priorities, SWOT, strategies, and views, and competitive landscape. Few of the key players profiled in this study include IBM Corporation, Microsoft, Amazon (AWS), SAP, Oracle, Cisco, ShoCard, Abra, Bitfury, Blockchain Foundry, and BlockCypher, Inc.
The study offers a comprehensive analysis of the “North America Blockchain in Telecom Market”. Bringing out the complete key insights of the industry, the report aims to provide an insight into the latest trends, current market scenario, and technologies related to the market. In addition, it helps the venture capitalists to understand the revenue opportunities across different segments to take better decisions.
1. Executive Summary
2. Industry Outlook
1. Industry Overview
2. Industry Trends
3. Market Snapshot
1. Total Addressable Market
2. Segmented Addressable Market
1. PEST Analysis
2. Porter’s Five Force Analysis
3. Related Markets
4. Market Characteristics
1. Ecosystem
2. Market Trends and Impact
3. Value Chain Analysis
4. Market Segmentation
5. Market Dynamics
1. Drivers
2. Restraints
3. Opportunities
4. DRO – Impact Analysis
5. Blockchain in Telecom Market, By Providers
1. Overview
2. Application Providers
3. Middleware Providers
4. Infrastructure Providers
6. Blockchain in Telecom Market, By Applications
1. Overview
2. Smart Contracts
3. Streamlining OSS and BSS Processes
4. Identity and Fraud Management
5. Payments
6. Secure Connectivity
7. Others
7. Blockchain in Telecom Market, By Organization Size
1. Overview
2. Large Enterprises
3. SMEs
8. Blockchain in Telecom Market, By Country
1. Overview
2. US
3. Canada
9. Competitive Landscape
1. Competitor Analysis
2. Product/Offerings Portfolio Analysis
3. Market Developments
1. Partnerships & Collaborations
2. Product Launches & Exhibitions
10. Vendor Profile
1. IBM Corporation
2. Microsoft
3. Amazon (AWS)
4. SAP
5. Oracle
6. Cisco
7. ShoCard
8. Abra
9. Bitfury
10. Blockchain Foundry
11. BlockCypher, Inc.
11. Annexure
1. Report Scope
2. Market Definition
3. Research Methodology
1. Data Collation & In-house Estimation
2. Market Triangulation
3. Forecasting
4. Study Declarations
5. Report Assumptions
6. Abbreviations
Research Framework
Infoholic Research works on a holistic 360° approach in order to deliver high quality, validated and reliable information in our market reports. The Market estimation and forecasting involves following steps:
• Data Collation (Primary & Secondary)
• In-house Estimation (Based on proprietary data bases and Models)
• Market Triangulation
• Forecasting
Methodology
Market related information is congregated from both primary and secondary sources.
Primary sources
Involved participants from all global stakeholders such as Solution providers, service providers, Industry associations, thought leaders etc. across levels such as CXOs, VPs and managers. Plus, our in-house industry experts having decades of industry experience contribute their consulting and advisory services.
Secondary sources
Include public sources such as regulatory frameworks, government IT spending, government demographic indicators, industry association statistics, and company publications along with paid sources such as Factiva, OneSource, Bloomberg among others.
outicon
Select User License
$
Want to customize this report?
This report can be personalized according to your needs. Our analysts and industry experts will work directly with you to understand your requirements and provide you with customized data in a short amount of time.
Speak to our analyst
Related Reports
|
__label__pos
| 0.786396 |
Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.
Find $X_t = c_1 X_{t-1} + \dots + c_n X_{t-n} + n_t$ for given $c_i$, initial conditions $(X_1, \dots, X_n)$, and distribution for i.i.d. $n_t$.
I would like to know if there is a more efficient or elegant way to code this than using a for loop.
share|improve this question
I think something like my answer here is what you want. This is the same (or nearly the same) as that question, but yours is much clearer. I guess I'll hold off on voting to close... – rm -rf May 17 '12 at 1:09
All the answers were good. I learned something from you all; I'm glad I asked. Yes, I meant "generate" when I said "find". – Emre May 17 '12 at 5:20
3 Answers 3
up vote 7 down vote accepted
Generating an autoregressive time series is not the same as "finding" it, since you have the parameters. If I understand you correctly, this is an application made for FoldList:
Here is a simple AR(1) process to illustrate the technique:
FoldList[c1 #1 + #2&, x0, RandomVariate[NormalDistribution[0,1],{100}]
For example
FoldList[0.9 #1 + #2 &, 0.2, RandomVariate[NormalDistribution[0, 1], {100}]]
ListLinePlot[%]
A simulated AR(1) process
For an AR($p$) process with $p>1$, something like this would work:
FoldList[Join[{params.#1+#2},Most[#1]]&, startingvalues,
RandomVariate[NormalDistribution[0, 1], {100}]]
Where params is your list of c parameters and startingvalues is your list of starting values.
Multivariate processes (i.e. simulation of data from a VAR to get a vector of length $p$ at each time period) can be handled similarly except of course that params will be a matrix and you'll be saving a matrix consisting of the vector of data for the current period, plus the $p$ lags, at each step. Then you need to extract the matrix of data from the repetitions representing the lags at each step using Part, i.e.
FoldList[Join[{matrixofparams.#1+#2},Most[#1]]&, matrixofstartingvalues,
RandomVariate[NormalDistribution[0, 1], {100,p}]][[All, 1, All ]]
share|improve this answer
Do you think "finding" means something else or that he just expressed himself wrong? If it means something else, what would it be? – Rojo May 17 '12 at 4:29
I would have assumed "finding" meant "estimating the parameters", but he has the parameters and the title says "generating", so I interpret him as meaning "simulate". I use the FoldList approach to generating an AR process all the time, to show people how functional programming in Mathematica works, and to generate fake economic-looking data for my test graphs. – Verbeia May 17 '12 at 4:34
Yeah, it's a practical one-liner, +1 – Rojo May 17 '12 at 4:42
A straightforward way would be using recursion and memoization. An example:
n = 5;
c = RandomReal[NormalDistribution[], n]/100;
Clear[x]
Array[(x[#] = RandomReal[NormalDistribution[]]) &, n]; (* Initial conditions *)
x[t_Integer] /; t > n := x[t] = c.Table[x[i], {i, t - 1, t - n, -1}] +
RandomReal[NormalDistribution[]]
ListLinePlot[x /@ Range[300]]
enter image description here
share|improve this answer
I like @RM 's approach. Another one, with a more "mathematical" notation (but I must say I'm not certain of the random behaviour of the way I'm getting the numbers) could be the following
First we create the discrete noise
i : noise["Seed"] := i = RandomInteger[{-# , #}] &[Developer`$MaxMachineInteger];
noise[n_Integer] :=
BlockRandom[SeedRandom[# + n];
RandomVariate[NormalDistribution[]]] &[noise["Seed"]]
Now, noise is a realisation of the process. You can realise another one by resetting the seed with noise["Seed"]=.;
If you do DiscretePlot[noise[n], {n, 0, 10}] several times, you'll see what I mean.
Now, just use RecurrenceTable
RecurrenceTable[{
x[0] == 0.5,
x[1] == 0.54,
x[2] == -2.3,
x[n] == noise[n] + 0.75 x[n - 1] - 0.23 x[n - 2] + 0.2 x[n - 3]},
x[n], {n, 0, 10}]
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.918464 |
Tell me more ×
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 wanna know how to solve this equation: $-2x^3 +10x^2 -17x +8=(2x^2)(5x -x^3)^{1/3}$
I have some trouble to do that and I'd glad with any help I may get.
share|improve this question
I am curious. How did you come across this equation? – Aryabhata Nov 4 '10 at 22:38
I´m preparing to a proof that has high reputation, then i collect questions in forums which have this purpose, that was the way i found out that exercise.In addition, the proof is high school level. I´m not sure that equation has some solution based in that grade of knowledge. Sorry about my english. – tom Nov 4 '10 at 23:07
1
Which forum did you find it in? Perhaps a link? – Aryabhata Nov 4 '10 at 23:08
1
@tom: I'd like the link - any time I can practice my portuguese is good for me! – Jason DeVito Nov 4 '10 at 23:23
1
The link of the community is orkut.com.br/Main#Community?cmm=1299345 – tom Nov 5 '10 at 4:31
show 3 more comments
4 Answers
Note that $\frac{1}{12} \left(17+\sqrt{97}\right)$ is not a solution. It just appeared because of cubing.
share|improve this answer
I hate it when downvoters don't explain themselves... they're being jerks. – J. M. Nov 4 '10 at 22:27
I imagine the claim is this should be a comment. But I will upvote to counteract it. The statement is quite useful. – Ross Millikan Nov 4 '10 at 22:35
thanks, it was a important note. – tom Nov 4 '10 at 23:29
Are you sure? If x and y are real, then x^3 = y^3 implies x = y. – Aryabhata Nov 5 '10 at 1:07
@J.M, Ross: Maybe the downvoters did this because the statement is false? btw, I don't see any downvotes! – Aryabhata Nov 5 '10 at 1:08
show 1 more comment
Cube both sides and collect terms. You should get \begin{eqnarray} 512 - 3264 x + 8856 x^2 - 13457 x^3 + 12702 x^4 - 7794 x^5 + 3136 x^6 - 844 x^7 + 120 x^8 = 0 \end{eqnarray} which factorizes into \begin{eqnarray} (8 - 17 x + 6 x^2) (64 - 272 x + 481 x^2 - 456 x^3 + 258 x^4 - 84 x^5 + 20 x^6) = 0. \end{eqnarray} Since this is an $8^{\text{th}}$-degree polynomial equation, you can use Mathematica or a calculator to determine six of the eight solutions (by solving the $6^{\text{th}}$-degree polynomial equation numerically) and the other two by solving the quadratic equation: $\frac{1}{12}(17 \pm \sqrt{97})$. The 6 solutions are 3 pairs of complex conjugates: \begin{eqnarray} & & 0.647522 \dots \pm i 2.21209 \dots \ & & 0.657656 \dots \pm i 0.218497 \dots \ & & 0.794822 \dots \pm i 0.788971 \dots \end{eqnarray} Of course, you'll have to check that these solutions work. At most one real solution and two complex solutions are spurious.
share|improve this answer
Really? Is it impossible solve it by factorize or trick of algebra? Sorry, I´m just a high school grade studant. – tom Nov 4 '10 at 21:12
If I'm reading your equation correctly, no, not if you are seeking all solutions. Is the 1/3 an exponent? Please use latex formatting. It's tough to tell what you mean. – user02138 Nov 4 '10 at 21:14
1/3 is a exponent – tom Nov 4 '10 at 23:09
I am not sure if "at least one real solution is spurious" is correct. Did you actually verify? – Aryabhata Nov 5 '10 at 1:14
Checking Wolfram Alpha (wolframalpha.com/input/…), the three valid solutions are $\frac{1}{{12}}\left( {17 - \sqrt {97} } \right)$ and $0.64752 \pm 2.21209i$. – Alexsander Akers Nov 5 '10 at 2:31
show 5 more comments
Once someone gives the answer, it becomes easier!
I presume you are only looking for real roots and that $\displaystyle (5x-x^3)^{1/3}$ is the unique real number whose cube is $\displaystyle 5x - x^3$.
First observe that
$\displaystyle (x-2)^3 + 5x - x^3 = -6x^2 + 17x -8$
So if $\displaystyle a = (5x-x^3)^{1/3}$ and $\displaystyle b = x-2$
then the equation becomes
$$\displaystyle -2x^2(x-2) - (-6x^2 - 17x - 8) = 2x^2(5x-x^3)^{1/3}$$
and thus
$$\displaystyle -2x^2 b - (a^3 + b^3) = 2x^2a$$
and so
$$\displaystyle (a+b)(a^2 - ab + b^2 + 2x^2) = 0$$
Now for any real numbers $\displaystyle a,b,x$ we have that
$\displaystyle a^2 -ab + b^2 \ge 0$ and $\displaystyle 2x^2 \ge 0$ and thus we must have that
$\displaystyle a + b = 0$ or $\displaystyle 2x^2 = 0$
$\displaystyle a = -b$ can be cubed to give $\displaystyle 6x^2 - 17x + 8 = 0$.
$\displaystyle 2x^2 = 0$ can be easily eliminated.
Note that the transformations we did were equivalent, and so both roots of $\displaystyle 6x^2 - 17x + 8 = 0$ are also roots of the original equation, given the definition of cuberoot at the top of the answer.
If you define $\displaystyle z^{1/3}$ using the principal branch of $\log z$, then the above assumption of $\displaystyle a$ being real is valid only if $\displaystyle 5x - x^3 \ge 0$, which eliminates $\displaystyle \dfrac{17 + \sqrt{97}}{12}$ as a root.
share|improve this answer
I´d only like to know how did you imagine the factorize of begining - (w-2)^3 +5w - w^3=-6w^2 +17w -8 - did you look to second member of equation? That was wonderful. Thanks very much. – tom Nov 4 '10 at 23:49
@Tom: Knowing that is was a factor (based on user02138's solution) helped. I am not sure exactly how I came up with it. Sorry. – Aryabhata Nov 5 '10 at 1:12
it make sense, I appreciate your attention. – tom Nov 5 '10 at 1:21
1
"If you define $z^{1/3}$ as the complex number with the least argument (which has become pretty standard convention nowadays)"—depends on exactly what you meant by least argument. I have seen $z^{1/3}$ defined as having argument in either $[0,\frac{2\pi}{3})$ or argument in $(-\frac{\pi}{3},\frac{\pi}{3}]$, the latter being more common in technological implementations. – Isaac Dec 8 '10 at 8:03
@Isaac: Thanks, I will edit the answer to remove that and just mention principal branch of log z. – Aryabhata Dec 8 '10 at 8:09
The algebraic $\frac{1}{12}(17 + \sqrt{97})$ is not a root of the equation \begin{eqnarray} -2 x^3 + 10 x^2 - 17 x + 8 = (2 x^2) (5 x - x^3)^{1/3} \end{eqnarray} Plugging it in, you find that the left hand side is real and equal to \begin{eqnarray} \tfrac{1}{216}(-149 - 37 \sqrt{97}) = -2.37689 \dots \end{eqnarray} The right side is \begin{eqnarray} \tfrac{1}{432} (\tfrac{1}{2}( 595 - 61 \sqrt{97})^{1/3} (17 + \sqrt{97})^2 = 1.18844 \dots + i 2.05845 \dots \end{eqnarray} Note: $595 < 61 \sqrt{97}$. I think the ambiguity lies in the fact that we have not used the third-roots of unity. Numerical computations aside, just plot the two functions. The RHS is a positive function defined only in the I and II quadrants. The LHS is cubic. There is only one real intersection point.
share|improve this answer
cuberoot of an arbitrary real R number is well defined: the unique real root of x^3 = R. In this case 5x-x^3 becomes negative and your software seems to be getting unnecessarily "complex". – Aryabhata Nov 5 '10 at 3:38
It depends on the definition of (5x-x^3)^(1/3). Given that this is a high school level problem, I presume we are only talking of the real values of the three possible values. I am not sure what is standard, though. Apparently, Mathematica seems to take the one with positive imaginary part. – Aryabhata Nov 5 '10 at 5:35
@Moron: The approach taken in Mathematica is to take the root that is consistent with the principal value of the logarithm, which is the same as the conventional cube root when the argument is positive. That's one reason there is an add-on package in Mathematica that forces the cube root to be $\mathrm{sgn}(x)\sqrt[3]{|x|}$ to agree with the "usual" cube root, to cater for less-advanced users. – J. M. Nov 5 '10 at 11:05
@J.M: Yes, I gathered that (and hence changed my answer to reflect that) :-) – Aryabhata Nov 5 '10 at 13:16
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.91647 |
What Is Protocol?
Question: What Is Protocol?
Answer: A set of rules that guides data communication is called protocol. It represents an agreement between the communication devices. Without a proper protocol, the device may be connected but they cannot communicate with each other. For Example, a person whose mother language is English cannot communicate with a person who can speak only Urdu.
What Is DOS? Question: What Is DOS? Answer: DOS stands for Disk Operating System. DOS is developed by Apple C...
What Is Softcopy? Question: What is Softcopy? Answer: The output received on the display screen is called softcopy...
The Term Computer is Derived from the Word Question: The Term Computer is Derived from the Word? Spanish Word Russian Word German Wo...
What Is Local Area Network (LAN)? Question: What Is Local Area Network (LAN)? Answer: Local Area Network is a type of computer netw...
Keyboard is an Input Device or Output Device? Question: Keyboard is an Input Device or Output Device? Answer: The Keyboard is an Input Device ...
Define A Byte? Question: Define A Byte? Answer: Byte stands for Binary Term. A combination or sum of 8-bits is c...
What Is WAN? Question: What Is WAN? Answer: A Wide Area Network is a network system that covers a large area s...
Who Many Types Of Computer? Question: Who Many Types Of Computer? Answer: Computer can also be divided into three categories ...
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.998823 |
Bing vs Google on a Mac
2 posts / 0 new
Last post
Anonymous Visitor
Bing vs Google on a Mac
How do I replace replace Bing with Google on mac?
Apple Eater
Re: Bing vs Google on a Mac
Assuming you mean while using the Safari web browser, do this:
While in Safari, click Preferences
In the preferences window, click Search
In the "Search Engine" dropdown, choose your preferred search engine.
Remember that no matter what default search engine is configured, you can always simply type in Google.com or bing.com or whatever you want, into the address bar to use it.
Add new comment
|
__label__pos
| 0.523587 |
Thrust
◆ adjacent_difference() [2/4]
template<typename DerivedPolicy , typename InputIterator , typename OutputIterator , typename BinaryFunction >
__host__ __device__ OutputIterator thrust::adjacent_difference ( const thrust::detail::execution_policy_base< DerivedPolicy > & exec,
InputIterator first,
InputIterator last,
OutputIterator result,
BinaryFunction binary_op
)
adjacent_difference calculates the differences of adjacent elements in the range [first, last). That is, *first is assigned to *result, and, for each iterator i in the range [first + 1, last), binary_op(*i, *(i - 1)) is assigned to *(result + (i - first)).
This version of adjacent_difference uses the binary function binary_op to calculate differences.
The algorithm's execution is parallelized as determined by exec.
Parameters
execThe execution policy to use for parallelization.
firstThe beginning of the input range.
lastThe end of the input range.
resultThe beginning of the output range.
binary_opThe binary function used to compute differences.
Returns
The iterator result + (last - first)
Template Parameters
DerivedPolicyThe name of the derived execution policy.
InputIteratoris a model of Input Iterator, and InputIterator's value_type is convertible to BinaryFunction's first_argument_type and second_argument_type, and InputIterator's value_type is convertible to a type in OutputIterator's set of value_types.
OutputIteratoris a model of Output Iterator.
BinaryFunction'sresult_type is convertible to a type in OutputIterator's set of value_types.
Remarks
Note that result is permitted to be the same iterator as first. This is useful for computing differences "in place".
The following code snippet demonstrates how to use adjacent_difference to compute the sum between adjacent elements of a range using the thrust::device execution policy:
...
int h_data[8] = {1, 2, 1, 2, 1, 2, 1, 2};
thrust::device_vector<int> d_data(h_data, h_data + 8);
thrust::adjacent_difference(thrust::device, d_data.begin(), d_data.end(), d_result.begin(), thrust::plus<int>());
// d_result is now [1, 3, 3, 3, 3, 3, 3, 3]
See also
https://en.cppreference.com/w/cpp/algorithm/adjacent_difference
inclusive_scan
|
__label__pos
| 0.83828 |
Commit 0bbc1088 authored by Vitali Stupin's avatar Vitali Stupin
adding tests
parent b6905226
sonar.projectKey=xtss-catalogue
sonar.sources=src
sonar.sourceEncoding=UTF-8
sonar.exclusions=**/node_modules/**,**/*.spec.ts
sonar.exclusions=**/node_modules/**,**/*.spec.ts,src/environments/**,src/karma.conf.js,src/main.ts
sonar.tests=src
sonar.test.inclusions=**/*.spec.ts
sonar.typescript.lcov.reportPaths=coverage/methods/lcov.info
......
......@@ -2,6 +2,7 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { HeaderComponent } from './header.component';
import { HttpClientModule } from '@angular/common/http';
import { LanguagesService } from '../languages.service';
describe('HeaderComponent', () => {
let component: HeaderComponent;
......@@ -27,4 +28,11 @@ describe('HeaderComponent', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
it('should set language', () => {
const languagesService: LanguagesService = TestBed.get(LanguagesService);
spyOn(languagesService, 'setLang').and.returnValue(null);
component.setLang('xxx');
expect(languagesService.setLang).toHaveBeenCalledWith('xxx');
});
});
import { TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { LanguagesService } from './languages.service';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
describe('LanguagesService', () => {
beforeEach(() => TestBed.configureTestingModule({
......@@ -13,4 +13,28 @@ describe('LanguagesService', () => {
const service: LanguagesService = TestBed.get(LanguagesService);
expect(service).toBeTruthy();
});
it('should set default lang with empty localStorage', () => {
const translateService: TranslateService = TestBed.get(TranslateService);
spyOn(translateService, 'setDefaultLang');
spyOn(window.localStorage, 'getItem').and.returnValue(undefined);
TestBed.get(LanguagesService);
expect(translateService.setDefaultLang).toHaveBeenCalledWith('est');
});
it('should set default lang from localStorage', () => {
const translateService: TranslateService = TestBed.get(TranslateService);
spyOn(translateService, 'setDefaultLang');
spyOn(window.localStorage, 'getItem').and.returnValue('ENG');
TestBed.get(LanguagesService);
expect(translateService.setDefaultLang).toHaveBeenCalledWith('eng');
});
it('should set language', () => {
const translateService: TranslateService = TestBed.get(TranslateService);
spyOn(translateService, 'use');
const service = TestBed.get(LanguagesService);
service.setLang('ENG');
expect(translateService.use).toHaveBeenCalledWith('eng');
});
});
......@@ -3,10 +3,12 @@ import { TranslateModule } from '@ngx-translate/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { SearchComponent } from './search.component';
import { SubsystemsService } from 'src/app/subsystems.service';
describe('SearchComponent', () => {
let component: SearchComponent;
let fixture: ComponentFixture<SearchComponent>;
let subsystemsService: SubsystemsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
......@@ -21,6 +23,10 @@ describe('SearchComponent', () => {
}));
beforeEach(() => {
subsystemsService = TestBed.get(SubsystemsService);
spyOn(subsystemsService, 'setNonEmpty').and.returnValue(null);
spyOn(subsystemsService, 'setLimit').and.returnValue(null);
spyOn(subsystemsService, 'setFilter').and.returnValue(null);
fixture = TestBed.createComponent(SearchComponent);
component = fixture.componentInstance;
fixture.detectChanges();
......@@ -29,4 +35,19 @@ describe('SearchComponent', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
it('setNonEmpty should work', () => {
component.setNonEmpty(true);
expect(subsystemsService.setNonEmpty).toHaveBeenCalledWith(true);
});
it('setLimit should work', () => {
component.setLimit('50');
expect(subsystemsService.setLimit).toHaveBeenCalledWith('50');
});
it('setFilter should work', () => {
component.setFilter('test');
expect(subsystemsService.setFilter).toHaveBeenCalledWith('test');
});
});
......@@ -3,10 +3,15 @@ import { TranslateModule } from '@ngx-translate/core';
import { HttpClientModule } from '@angular/common/http';
import { SubsystemItemComponent } from './subsystem-item.component';
import { RouterTestingModule } from '@angular/router/testing';
import { SubsystemsService } from 'src/app/subsystems.service';
import { Router } from '@angular/router';
import { PREVIEW_SIZE } from '../../config';
import { Method } from 'src/app/method';
describe('SubsystemItemComponent', () => {
let component: SubsystemItemComponent;
let fixture: ComponentFixture<SubsystemItemComponent>;
let subsystemsService: SubsystemsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
......@@ -17,29 +22,62 @@ describe('SubsystemItemComponent', () => {
TranslateModule.forRoot(),
HttpClientModule,
RouterTestingModule
],
providers: [
{ provide: Router, useValue: {
navigateByUrl: jasmine.createSpy('navigateByUrl')
}}
]
})
.compileComponents();
}));
beforeEach(() => {
subsystemsService = TestBed.get(SubsystemsService);
spyOn(subsystemsService, 'getApiUrlBase').and.returnValue(null);
fixture = TestBed.createComponent(SubsystemItemComponent);
component = fixture.componentInstance;
component.subsystem = {
xRoadInstance: 'XRD',
xRoadInstance: 'INST',
memberClass: 'CLASS',
memberCode: 'CODE',
subsystemCode: 'SUB',
subsystemStatus: 'OK',
fullSubsystemName: 'XRD/CLASS/CODE/SUB',
fullSubsystemName: 'INST/CLASS/CODE/SUB',
methods: []
};
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('getApiUrlBase should work', () => {
component.getApiUrlBase();
expect(subsystemsService.getApiUrlBase).toHaveBeenCalled();
});
it('should preview methods', () => {
expect(component.getMethodsPreview().length).toBe(0);
for (let i = 0; i < PREVIEW_SIZE + 10; i++) {
component.subsystem.methods.push(new Method());
}
expect(component.getMethodsPreview().length).toBe(PREVIEW_SIZE);
});
it('should calculate methods not in preview', () => {
expect(component.getNotInPreview()).toBe(0);
for (let i = 0; i < PREVIEW_SIZE + 10; i++) {
component.subsystem.methods.push(new Method());
}
expect(component.getNotInPreview()).toBe(10);
});
it('should go to detail view', () => {
component.showDetail();
expect(TestBed.get(Router).navigateByUrl).toHaveBeenCalledWith('/INST/CLASS/CODE/SUB');
});
});
......@@ -5,8 +5,10 @@ import { RouterTestingModule } from '@angular/router/testing';
import { SubsystemListComponent } from './subsystem-list.component';
import { Component, Input } from '@angular/core';
import { Subsystem } from '../subsystem';
import { ActivatedRoute } from '@angular/router';
import { ActivatedRoute, Router, Scroll } from '@angular/router';
import { of } from 'rxjs';
import { SubsystemsService } from '../subsystems.service';
import { ViewportScroller } from '@angular/common';
@Component({selector: 'app-header', template: ''})
class HeaderStubComponent {}
......@@ -20,6 +22,9 @@ class SubsystemItemStubComponent {
describe('SubsystemListComponent', () => {
let component: SubsystemListComponent;
let fixture: ComponentFixture<SubsystemListComponent>;
let getInstanceSpy;
let getInstancesSpy;
let subsystemsService: SubsystemsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
......@@ -31,24 +36,85 @@ describe('SubsystemListComponent', () => {
],
imports: [
TranslateModule.forRoot(),
HttpClientModule,
RouterTestingModule
HttpClientModule
],
providers: [
{ provide: ActivatedRoute, useValue: {
params: of({
instance: 'INST'
})
}},
{ provide: Router, useValue: {
events: of(new Scroll(null, [11, 12], null)),
navigateByUrl: jasmine.createSpy('navigateByUrl')
}}
]
})
.compileComponents();
}));
beforeEach(() => {
// Mocks and spies
TestBed.get(ActivatedRoute).params = of({
instance: 'EE'
});
subsystemsService = TestBed.get(SubsystemsService);
getInstanceSpy = spyOn(subsystemsService, 'getInstance').and.returnValue('INST');
getInstancesSpy = spyOn(subsystemsService, 'getInstances').and.returnValue(['INST']);
spyOn(TestBed.get(ViewportScroller), 'scrollToPosition');
spyOn(subsystemsService, 'setInstance').and.returnValue(null);
spyOn(subsystemsService, 'getDefaultInstance').and.returnValue('DEFINST');
spyOn(TestBed.get(SubsystemsService), 'getApiUrlBase').and.returnValue('base');
});
it('should create', () => {
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should create', () => {
expect(component).toBeTruthy();
it('should redirect on incorrect instance', () => {
getInstancesSpy.and.returnValue(['XXX']);
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(TestBed.get(Router).navigateByUrl).toHaveBeenCalledWith('/DEFINST');
});
it('should detect when instance is not selected', () => {
getInstanceSpy.and.returnValue('');
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(subsystemsService.setInstance).toHaveBeenCalledWith('INST');
});
it('should detect change instance', () => {
getInstanceSpy.and.returnValue('INST2');
getInstancesSpy.and.returnValue(['INST', 'INST2']);
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(subsystemsService.setInstance).toHaveBeenCalledWith('INST');
});
it('should scroll to position', () => {
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(TestBed.get(ViewportScroller).scrollToPosition).toHaveBeenCalledWith([11, 12]);
});
it('switchInstance should work', () => {
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.switchInstance('NEWINST');
expect(TestBed.get(Router).navigateByUrl).toHaveBeenCalledWith('/NEWINST');
});
it('should receive service warnings', () => {
fixture = TestBed.createComponent(SubsystemListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
subsystemsService.warnings.emit('WARN');
expect(component.message).toBe('WARN');
});
});
......@@ -73,7 +73,7 @@ export class SubsystemListComponent implements OnInit, AfterViewInit, OnDestroy
}
// Only reload on switching of instance or when no instance is selected yet on service side
if (this.getInstance() === '' || this.getInstance() !== params.instance) {
this.subsystemsService.setInstance(params.instance ? params.instance : this.subsystemsService.getDefaultInstance());
this.subsystemsService.setInstance(params.instance);
}
});
}
......
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { Component } from '@angular/core';
import { Component, EventEmitter } from '@angular/core';
import { SubsystemComponent } from './subsystem.component';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientModule } from '@angular/common/http';
// import { ViewportScroller } from '@angular/common';
// import { SubsystemsService } from '../methods.service';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { Router, ActivatedRoute, Scroll } from '@angular/router';
import { of, BehaviorSubject } from 'rxjs';
import { SubsystemsService } from '../subsystems.service';
import { ViewportScroller } from '@angular/common';
@Component({selector: 'app-header', template: ''})
class HeaderStubComponent {}
......@@ -15,6 +14,9 @@ class HeaderStubComponent {}
describe('SubsystemComponent', () => {
let component: SubsystemComponent;
let fixture: ComponentFixture<SubsystemComponent>;
let getInstanceSpy;
let getInstancesSpy;
let subsystemsService: SubsystemsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
......@@ -24,40 +26,114 @@ describe('SubsystemComponent', () => {
],
imports: [
TranslateModule.forRoot(),
HttpClientModule,
RouterTestingModule
]/*,
HttpClientModule
],
providers: [
SubsystemsService
]*/
{ provide: ActivatedRoute, useValue: {
params: of({
instance: 'INST',
class: 'CLASS',
member: 'MEMBER',
subsystem: 'SYSTEM'
})
}},
{ provide: Router, useValue: {
events: of(new Scroll(null, [11, 12], null)),
navigateByUrl: jasmine.createSpy('navigateByUrl')
}}
]
})
.compileComponents();
}));
beforeEach(() => {
// Mocks and spies
TestBed.get(ActivatedRoute).params = of({
instance: 'EE',
class: 'CLASS',
member: 'MEMBER',
subsystem: 'SYSTEM'
});
// spyOn(TestBed.get(ViewportScroller), "scrollToPosition").and.callFake(() => {});
subsystemsService = TestBed.get(SubsystemsService);
getInstanceSpy = spyOn(subsystemsService, 'getInstance').and.returnValue('INST');
getInstancesSpy = spyOn(subsystemsService, 'getInstances').and.returnValue(['INST']);
spyOn(TestBed.get(ViewportScroller), 'scrollToPosition');
spyOn(subsystemsService, 'setInstance').and.returnValue(null);
spyOn(TestBed.get(SubsystemsService), 'getApiUrlBase').and.returnValue('base');
subsystemsService.subsystemsSubject = new BehaviorSubject([
{
memberClass: '',
subsystemCode: '',
xRoadInstance: '',
subsystemStatus: '',
memberCode: '',
fullSubsystemName: 'INST/CLASS/MEMBER/SYSTEM',
methods: []
}
]);
});
it('should create', () => {
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(component).toBeTruthy();
});
/*afterEach(() => {
TestBed.resetTestEnvironment()
});*/
it('should detect incorrect instance', () => {
getInstancesSpy.and.returnValue(['XXX']);
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(component.message).toBe('Incorrect instance!');
});
it('should create', () => {
expect(component).toBeTruthy();
it('should detect when instance is not selected', () => {
getInstanceSpy.and.returnValue('');
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(subsystemsService.setInstance).toHaveBeenCalledWith('INST');
});
it('should detect change instance', () => {
getInstanceSpy.and.returnValue('INST2');
getInstancesSpy.and.returnValue(['INST', 'INST2']);
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(subsystemsService.setInstance).toHaveBeenCalledWith('INST');
});
it('should detect incorrect subsystem', () => {
subsystemsService.subsystemsSubject = new BehaviorSubject([]);
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(component.message).toBe('Subsystem "INST/CLASS/MEMBER/SYSTEM" cannot be found!');
});
/*it('scrollToPosition was called', async(() => {
expect(TestBed.get(ViewportScroller).scrollToPosition).toHaveBeenCalledWith([0, 0])
}));*/
it('should scroll to position', () => {
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
expect(TestBed.get(ViewportScroller).scrollToPosition).toHaveBeenCalledWith([11, 12]);
});
it('getApiUrlBase should work', () => {
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.getApiUrlBase();
expect(subsystemsService.getApiUrlBase).toHaveBeenCalled();
});
it('goToList should work', () => {
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.goToList();
expect(TestBed.get(Router).navigateByUrl).toHaveBeenCalledWith('/INST');
});
it('should receive service warnings', () => {
fixture = TestBed.createComponent(SubsystemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
subsystemsService.warnings.emit('WARN');
expect(component.message).toBe('WARN');
});
});
......@@ -67,17 +67,20 @@ export class SubsystemComponent implements OnInit, AfterViewInit, OnDestroy {
this.routeSubscription = this.route.params.subscribe( params => {
// Checking if instance is correct
if (!this.subsystemsService.getInstances().includes(params.instance)) {
// TODO: translation!
this.message = 'Incorrect instance!';
return;
}
this.subsystemId = params.instance + '/' + params.class + '/' + params.member + '/' + params.subsystem;
// Only reload on switching of instance or when no instance is selected yet on service side
if (this.getInstance() === '' || this.getInstance() !== params.instance) {
this.subsystemsService.setInstance(params.instance ? params.instance : this.subsystemsService.getDefaultInstance());
// this.subsystemsService.setInstance(params.instance ? params.instance : this.subsystemsService.getDefaultInstance());
this.subsystemsService.setInstance(params.instance);
}
this.subsystemsSubscription = this.subsystemsService.subsystemsSubject.subscribe(subsystems => {
const subsystem = this.getSubsystem(subsystems, this.subsystemId);
if (!subsystem && !this.message) {
// TODO: translation!
this.message = 'Subsystem "' + this.subsystemId + '" cannot be found!';
} else {
this.subsystemSubject.next(subsystem);
......@@ -96,10 +99,26 @@ export class SubsystemComponent implements OnInit, AfterViewInit, OnDestroy {
}
ngOnDestroy() {
this.routerScrollSubscription.unsubscribe();
// TODO: optimize this...
if (this.routerScrollSubscription) {
this.routerScrollSubscription.unsubscribe();
}
if (this.routeSubscription) {
this.routeSubscription.unsubscribe();
}
if (this.warningsSubscription) {
this.warningsSubscription.unsubscribe();
}
if (this.scrollSubjectSubscription) {
this.scrollSubjectSubscription.unsubscribe();
}
if (this.subsystemsSubscription) {
this.subsystemsSubscription.unsubscribe();
}
/*this.routerScrollSubscription.unsubscribe();
this.routeSubscription.unsubscribe();
this.warningsSubscription.unsubscribe();
this.scrollSubjectSubscription.unsubscribe();
this.subsystemsSubscription.unsubscribe();
this.subsystemsSubscription.unsubscribe();*/
}
}
import { TestBed } from '@angular/core/testing';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateModule } from '@ngx-translate/core';
import { SubsystemsService } from './subsystems.service';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { HttpLoaderFactory } from './app.module';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
describe('SubsystemsService', () => {
let service: SubsystemsService;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
HttpClientModule
TranslateModule.forRoot(),
HttpClientTestingModule
]
}));
beforeEach(() => {
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(SubsystemsService);
});
it('should be created', () => {
const service: SubsystemsService = TestBed.get(SubsystemsService);
expect(service).toBeTruthy();
});
/*it('should set instance', () => {
service.setInstance('EE');
// expect(service).toBeTruthy();
// httpTestingController.expectOne('https://x-tee.ee/catalogue/EE/wsdls/index.json');
});*/
});
......@@ -19,7 +19,7 @@ export class SubsystemsService {
filteredSubsystemsSubject: BehaviorSubject<Subsystem[]> = new BehaviorSubject([]);
private updateFilter = new Subject<string>();
|
__label__pos
| 0.997173 |
View Javadoc
1 package net.sumaris.server.http.graphql.extraction;
2
3 /*-
4 * #%L
5 * SUMARiS:: Server
6 * %%
7 * Copyright (C) 2018 SUMARiS Consortium
8 * %%
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public
20 * License along with this program. If not, see
21 * <http://www.gnu.org/licenses/gpl-3.0.html>.
22 * #L%
23 */
24
25 import com.google.common.base.Preconditions;
26 import io.leangen.graphql.annotations.GraphQLArgument;
27 import io.leangen.graphql.annotations.GraphQLQuery;
28 import net.sumaris.core.dao.technical.SortDirection;
29 import net.sumaris.core.extraction.service.ExtractionService;
30 import net.sumaris.core.extraction.vo.ExtractionFilterVO;
31 import net.sumaris.core.extraction.vo.ExtractionResultVO;
32 import net.sumaris.core.extraction.vo.filter.ExtractionTypeFilterVO;
33 import net.sumaris.core.extraction.vo.ExtractionTypeVO;
34 import net.sumaris.server.http.rest.DownloadController;
35 import net.sumaris.server.http.security.IsUser;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.stereotype.Service;
38 import org.springframework.transaction.annotation.Transactional;
39
40 import java.io.File;
41 import java.io.IOException;
42 import java.util.List;
43
44 @Service
45 @Transactional
46 public class ExtractionGraphQLService {
47
48 @Autowired
49 private ExtractionService extractionService;
50
51 @Autowired
52 private DownloadController downloadController;
53
54 /* -- Extraction / table -- */
55
56 @GraphQLQuery(name = "extractionTypes", description = "Get all available extraction types")
57 @Transactional(readOnly = true)
58 public List<ExtractionTypeVO> getAllExtractionTypes(@GraphQLArgument(name = "filter") ExtractionTypeFilterVO filter) {
59 return extractionService.findByFilter(filter);
60 }
61
62 @GraphQLQuery(name = "extractionRows", description = "Preview some extraction rows")
63 @Transactional
64 @IsUser
65 public ExtractionResultVO getExtractionRows(@GraphQLArgument(name = "type") ExtractionTypeVO type,
66 @GraphQLArgument(name = "filter") ExtractionFilterVO filter,
67 @GraphQLArgument(name = "offset", defaultValue = "0") Integer offset,
68 @GraphQLArgument(name = "size", defaultValue = "1000") Integer size,
69 @GraphQLArgument(name = "sortBy") String sort,
70 @GraphQLArgument(name = "sortDirection", defaultValue = "asc") String direction
71 ) {
72 Preconditions.checkNotNull(type, "Argument 'type' must not be null.");
73 Preconditions.checkNotNull(type.getLabel(), "Argument 'type.label' must not be null.");
74 Preconditions.checkNotNull(offset, "Argument 'offset' must not be null.");
75 Preconditions.checkNotNull(size, "Argument 'size' must not be null.");
76
77 return extractionService.executeAndRead(type, filter, offset, size, sort, direction != null ? SortDirection.valueOf(direction.toUpperCase()) : null);
78 }
79
80 @GraphQLQuery(name = "extractionFile", description = "Execute extraction to a file")
81 @Transactional
82 @IsUser
83 public String getExtractionFile(@GraphQLArgument(name = "type") ExtractionTypeVO type,
84 @GraphQLArgument(name = "filter") ExtractionFilterVO filter
85 ) throws IOException {
86 Preconditions.checkNotNull(type, "Argument 'type' must not be null.");
87 Preconditions.checkNotNull(type.getLabel(), "Argument 'type.label' must not be null.");
88
89 File tempFile = extractionService.executeAndDump(type, filter);
90 String fileServerPath = downloadController.registerFile(tempFile, true);
91
92 return fileServerPath;
93 }
94
95 }
|
__label__pos
| 0.818567 |
changeset 16043:0c9424895efb
8006409: ThreadLocalRandom should dropping padding fields from its serialized form Reviewed-by: dl, martin, alanb, shade
author chegar
date Thu, 28 Feb 2013 12:39:29 +0000
parents 0bf6469a1cfb
children 85f90a877d17 c65f0f54851c
files jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java
diffstat 1 files changed, 30 insertions(+), 48 deletions(-) [+]
line wrap: on
line diff
--- a/jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java Wed Feb 27 11:00:20 2013 -0800
+++ b/jdk/src/share/classes/java/util/concurrent/ThreadLocalRandom.java Thu Feb 28 12:39:29 2013 +0000
@@ -83,22 +83,20 @@
* programs.
*
* Because this class is in a different package than class Thread,
- * field access methods must use Unsafe to bypass access control
- * rules. The base functionality of Random methods is
- * conveniently isolated in method next(bits), that just reads and
- * writes the Thread field rather than its own field. However, to
- * conform to the requirements of the Random constructor, during
- * construction, the common static ThreadLocalRandom must maintain
- * initialization and value fields, mainly for the sake of
- * disabling user calls to setSeed while still allowing a call
- * from constructor. For serialization compatibility, these
- * fields are left with the same declarations as used in the
- * previous ThreadLocal-based version of this class, that used
- * them differently. Note that serialization is completely
- * unnecessary because there is only a static singleton. But these
- * mechanics still ensure compatibility across versions.
+ * field access methods use Unsafe to bypass access control rules.
+ * The base functionality of Random methods is conveniently
+ * isolated in method next(bits), that just reads and writes the
+ * Thread field rather than its own field. However, to conform to
+ * the requirements of the Random superclass constructor, the
+ * common static ThreadLocalRandom maintains an "initialized"
+ * field for the sake of rejecting user calls to setSeed while
+ * still allowing a call from constructor. Note that
+ * serialization is completely unnecessary because there is only a
+ * static singleton. But we generate a serial form containing
+ * "rnd" and "initialized" fields to ensure compatibility across
+ * versions.
*
- * Per-instance initialization is similar to that in the no-arg
+ * Per-thread initialization is similar to that in the no-arg
* Random constructor, but we avoid correlation among not only
* initial seeds of those created in different threads, but also
* those created using class Random itself; while at the same time
@@ -132,10 +130,11 @@
private static final ThreadLocal<Double> nextLocalGaussian =
new ThreadLocal<Double>();
- /*
- * Field used only during singleton initialization
+ /**
+ * Field used only during singleton initialization.
+ * True when constructor completes.
*/
- boolean initialized; // true when constructor completes
+ boolean initialized;
/** Constructor used only for static singleton */
private ThreadLocalRandom() {
@@ -184,7 +183,8 @@
* @throws UnsupportedOperationException always
*/
public void setSeed(long seed) {
- if (initialized) // allow call from super() constructor
+ // only allow call from super() constructor
+ if (initialized)
throw new UnsupportedOperationException();
}
@@ -357,39 +357,29 @@
r ^= r >>> 17;
r ^= r << 5;
}
- else if ((r = (int)UNSAFE.getLong(t, SEED)) == 0)
- r = 1; // avoid zero
+ else {
+ localInit();
+ if ((r = (int)UNSAFE.getLong(t, SEED)) == 0)
+ r = 1; // avoid zero
+ }
UNSAFE.putInt(t, SECONDARY, r);
return r;
}
- // Serialization support, maintains original persistent form.
+ // Serialization support
private static final long serialVersionUID = -5851777807851030925L;
/**
* @serialField rnd long
+ * seed for random computations
* @serialField initialized boolean
- * @serialField pad0 long
- * @serialField pad1 long
- * @serialField pad2 long
- * @serialField pad3 long
- * @serialField pad4 long
- * @serialField pad5 long
- * @serialField pad6 long
- * @serialField pad7 long
+ * always true
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("rnd", long.class),
- new ObjectStreamField("initialized", boolean.class),
- new ObjectStreamField("pad0", long.class),
- new ObjectStreamField("pad1", long.class),
- new ObjectStreamField("pad2", long.class),
- new ObjectStreamField("pad3", long.class),
- new ObjectStreamField("pad4", long.class),
- new ObjectStreamField("pad5", long.class),
- new ObjectStreamField("pad6", long.class),
- new ObjectStreamField("pad7", long.class) };
+ new ObjectStreamField("initialized", boolean.class)
+ };
/**
* Saves the {@code ThreadLocalRandom} to a stream (that is, serializes it).
@@ -398,16 +388,8 @@
throws java.io.IOException {
java.io.ObjectOutputStream.PutField fields = out.putFields();
- fields.put("rnd", 0L);
+ fields.put("rnd", UNSAFE.getLong(Thread.currentThread(), SEED));
fields.put("initialized", true);
- fields.put("pad0", 0L);
- fields.put("pad1", 0L);
- fields.put("pad2", 0L);
- fields.put("pad3", 0L);
- fields.put("pad4", 0L);
- fields.put("pad5", 0L);
- fields.put("pad6", 0L);
- fields.put("pad7", 0L);
out.writeFields();
}
|
__label__pos
| 0.982921 |
Hi folks, I'm reading about Dart's null safety and...
# announcements
s
Hi folks, I'm reading about Dart's null safety and based on their video, it says that Kotlin does not have this "Sound null safety". For what I understand reading the docs (https://dart.dev/null-safety) "Sound null safety" but looks like exactly what kotlin does when you are writing a full kotlin code, like a project that only uses others Kotlin libraries. Can someone clarify why kotlin is not "Sound null safety"? (image taken from
https://www.youtube.com/watch?v=iYhOU9AuaFs
)
r
Probably because Kotlin uses runtime null checks.
j
Is this related with a old version of moshi library where you can declare properties as non null but if they are null you don't get the crash until you try to read them?
s
So the "problem" is in the Kotlin interop with other languages, but, in case I'm developing a project that uses only kotlin libraries, what the compiler does? They will still have runtime checks for my code? Other case is KMM, when we get to do a full application only from shared/common code, I guess this will happen in some close future, in this case, you will ONLY have libraries that are build in kotlin and all its types are already checked by the compiler, in this case it will still generate runtime checks?
t
Copy code
object Ouch {
val world: String = { temp }()
private val temp: String = "World"
init {
println("Hello ${world}")
}
}
=>
Copy code
> Hello null
👍 3
e
Can anyone explain to me why above is not a bug?
|
__label__pos
| 0.64424 |
somemo's diary
プログラマ、雑記、プログラミング関係はLinkから、数式はこっちでまとめていることが多い
【php】シングルトンのテスト【PHPUnit】
会社にあるPHPデザパタ本で勉強を始めました。
書籍ではWEB上での確認ですが、自分はテストコードを使うことにしました。
シングルトンの理解については特に問題ないのですが、cloneの防止や例外のテストが勉強になりました。
<?php
class SingletonSample {
/**
* 自身のクラスを保持するメンバ変数
* @var SingletonSample
*/
private static $instance;
/**
* ID
* @var String
*/
private $id;
/**
* コンストラクタ
*/
private function __construct() {
$this->id = md5(date('r'). mt_rand());
}
/**
* インスタンスの取得
*/
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new SingletonSample();
echo 'create';
};
return self::$instance;
}
/**
* IDの取得
*/
public function getId() {
return $this->id;
}
/**
* clone防止
*/
public final function __clone() {
throw new RuntimeException('Clone is not allowed against '. get_class($this));
}
}
<?php
require_once dirname(__FILE__).'/../../src/singleton/SingletonSample.class.php';
class SingletonTest extends PHPUnit_Framework_TestCase {
private $instance1;
private $instance2;
public function setUp() {
$this->instance1 = SingletonSample::getInstance();
$this->instance2 = SingletonSample::getInstance();
}
/**
* インスタンスのIDが同一であることをテストする
*/
public function testSameId() {
$this->assertTrue($this->instance1->getId() === $this->instance2->getId());
}
/**
* インスタンスが同一であることをテストする
*/
public function testSameInstance() {
$this->assertTrue($this->instance1 === $this->instance2);
}
/**
* インスタンスのコピーを生成できないようにする
*/
public function testDisableClone() {
try {
$instance_copy = clone $this->instance1;
} catch (Exception $e) {
return;
}
$this->fail('able copy');
}
}
追記:インスタンスコピー防止のテストの修正しました。5tests、4assertionsになっていました・・・。
/**
* インスタンスのコピーを生成できないようにする
*/
public function testDisableClone() {
try {
$instance_copy = clone $this->instance1;
$this->fail('able copy');
} catch (Exception $e) {
$this->assertTrue(true);
// または、assertTrueに渡す引数を変数化して、try-catchブロックの外で判定する
}
}
}
|
__label__pos
| 0.771363 |
专栏首页京程一灯共享可变状态中出现的问题以及如何避免[每日前端夜话0xDB]
共享可变状态中出现的问题以及如何避免[每日前端夜话0xDB]
共享可变状态的解释如下:
• 如果两个或多个参与方可以更改相同的数据(变量,对象等),并且
• 如果它们的生命周期重叠,
则可能会有一方修改会导致另一方无法正常工作的风险。以下是一个例子:
1function logElements(arr) {
2 while (arr.length > 0) {
3 console.log(arr.shift());
4 }
5}
6
7function main() {
8 const arr = ['banana', 'orange', 'apple'];
9
10 console.log('Before sorting:');
11 logElements(arr);
12
13 arr.sort(); // changes arr
14
15 console.log('After sorting:');
16 logElements(arr); // (A)
17}
18main();
19
20// Output:
21// 'Before sorting:'
22// 'banana'
23// 'orange'
24// 'apple'
25// 'After sorting:'
这里有两个独立的部分:函数logElements()和函数main()。后者想要在对数组进行排序的前后都打印其内容。但是它到用了 logElements() ,会导致数组被清空。所以 main() 会在A行输出一个空数组。
在本文的剩余部分,我们将介绍三种避免共享可变状态问题的方法:
• 通过复制数据避免共享
• 通过无损更新来避免数据变动
• 通过使数据不可变来防止数据变动
针对每一种方法,我们都会回到刚才看到的示例并进行修复。
通过复制数据避免共享
在开始研究如何避免共享之前,我们需要看一下如何在 JavaScript 中复制数据。
浅拷贝与深拷贝
对于数据,有两个可复制的“深度”:
• 浅拷贝仅复制对象和数组的顶层条目。原始值和副本中的输入值仍然相同。
• 深拷贝还会复制条目值的条目。也就是说,它会完整遍历树,并复制所有节点。
不幸的是,JavaScript 仅内置了对浅拷贝的支持。如果需要深拷贝,则需要自己实现。
JavaScript 中的浅拷贝
让我们看一下浅拷贝的几种方法。
通过传播复制普通对象和数组
我们可以扩展为对象字面量和扩展为数组字面量进行复制:
1const copyOfObject = {...originalObject};
2const copyOfArray = [...originalArray];
但是传播有几个限制:
• 不复制原型: 1class MyClass {} 2 3const original = new MyClass(); 4assert.equal(MyClass.prototype.isPrototypeOf(original), true); 5 6const copy = {...original}; 7assert.equal(MyClass.prototype.isPrototypeOf(copy), false);
• 正则表达式和日期之类的特殊对象有未复制的特殊“内部插槽”。
• 仅复制自己的(非继承)属性。鉴于原型链的工作原理,这通常是最好的方法。但是你仍然需要意识到这一点。在以下示例中,copy 中没有 original 的继承属性 .inheritedProp,因为我们仅复制自己的属性,而未保留原型。 1const proto = { inheritedProp: 'a' }; 2const original = {__proto__: proto, ownProp: 'b' }; 3assert.equal(original.inheritedProp, 'a'); 4assert.equal(original.ownProp, 'b'); 5 6const copy = {...original}; 7assert.equal(copy.inheritedProp, undefined); 8assert.equal(copy.ownProp, 'b');
• 仅复制可枚举的属性。例如数组实例自己的属性 .length 不可枚举,也不能复制: 1const arr = ['a', 'b']; 2assert.equal(arr.length, 2); 3assert.equal({}.hasOwnProperty.call(arr, 'length'), true); 4 5const copy = {...arr}; 6assert.equal({}.hasOwnProperty.call(copy, 'length'), false);
• 与 property 的 attributes无关,它的副本始终是可写和可配置的 data 属性,例如: 1const original = Object.defineProperties({}, { 2prop: { 3 value: 1, 4 writable: false, 5 configurable: false, 6 enumerable: true, 7}, 8}); 9assert.deepEqual(original, {prop: 1}); 10 11const copy = {...original}; 12// Attributes “writable” and “configurable” of copy are different: 13assert.deepEqual(Object.getOwnPropertyDescriptors(copy), { 14prop: { 15 value: 1, 16 writable: true, 17 configurable: true, 18 enumerable: true, 19}, 20});
这意味着,getter 和 setter 都不会被如实地被复制:value 属性(用于数据属性),get 属性(用于 getter)和set 属性(用于 setter)是互斥的。
js const original = { get myGetter() { return 123 }, set mySetter(x) {}, }; assert.deepEqual({...original}, { myGetter: 123, // not a getter anymore! mySetter: undefined, });
• 拷贝很浅:该副本具有原始版本中每个键值条目的新版本,但是原始值本身不会被复制。例如: 1const original = {name: 'Jane', work: {employer: 'Acme'}}; 2const copy = {...original}; 3 4// Property .name is a copy 5copy.name = 'John'; 6assert.deepEqual(original, 7{name: 'Jane', work: {employer: 'Acme'}}); 8assert.deepEqual(copy, 9{name: 'John', work: {employer: 'Acme'}}); 10 11// The value of .work is shared 12copy.work.employer = 'Spectre'; 13assert.deepEqual( 14original, {name: 'Jane', work: {employer: 'Spectre'}}); 15assert.deepEqual( 16copy, {name: 'John', work: {employer: 'Spectre'}});
这些限制有的可以消除,而其他则不能:
• 我们可以在拷贝过程中为副本提供与原始原型相同的原型: 1class MyClass {} 2 3const original = new MyClass(); 4 5const copy = { 6__proto__: Object.getPrototypeOf(original), 7...original, 8}; 9assert.equal(MyClass.prototype.isPrototypeOf(copy), true);
另外,我们可以在副本创建后通过 Object.setPrototypeOf() 设置原型。
• 没有简单的方法可以通用地复制特殊对象。
• 如前所述,仅复制自己的属性是功能而非限制。
• 我们可以用 Object.getOwnPropertyDescriptors()Object.defineProperties() 复制对象(操作方法稍后说明):
• 他们考虑了所有属性(而不仅仅是 value),因此正确地复制了getters,setters,只读属性等。
• Object.getOwnPropertyDescriptors() 检索可枚举和不可枚举的属性。
• 我们将在本文后面的内容中介绍深拷贝。
通过 `Object.assign()` 进行浅拷贝(高级)
Object.assign()的工作原理就像传播到对象中一样。也就是说以下两种复制方式大致相同:
1const copy1 = {...original};
2const copy2 = Object.assign({}, original);
使用方法而不是语法的好处是可以通过库在旧的 JavaScript 引擎上对其进行填充。
不过 Object.assign() 并不完全像传播。它在一个相对微妙的方面有所不同:它以不同的方式创建属性。
• Object.assign() 使用 assignment 创建副本的属性。
• 传播定义副本中的新属性。
除其他事项外,assignment 会调用自己的和继承的设置器,而 definition 不会(关于 assignment 与 definition 的更多信息)。这种差异很少引起注意。以下代码是一个例子,但它是人为设计的:
1const original = {['__proto__']: null};
2const copy1 = {...original};
3// copy1 has the own property '__proto__'
4assert.deepEqual(
5 Object.keys(copy1), ['__proto__']);
6
7const copy2 = Object.assign({}, original);
8// copy2 has the prototype null
9assert.equal(Object.getPrototypeOf(copy2), null);
通过 `Object.getOwnPropertyDescriptors()` 和 `Object.defineProperties()` 进行浅拷贝(高级)
JavaScript 使我们可以通过属性描述符创建属性,这些对象指定属性属性。例如,通过 Object.defineProperties() ,我们已经看到了它。如果将该方法与 Object.getOwnPropertyDescriptors()结合使用,则可以更加忠实地进行复制:
1function copyAllOwnProperties(original) {
2 return Object.defineProperties(
3 {}, Object.getOwnPropertyDescriptors(original));
4}
这消除了通过传播复制对象的两个限制。
首先,能够正确复制自己 property 的所有 attribute。我们现在可以复制自己的 getter 和 setter:
1const original = {
2 get myGetter() { return 123 },
3 set mySetter(x) {},
4};
5assert.deepEqual(copyAllOwnProperties(original), original);
其次,由于使用了 Object.getOwnPropertyDescriptors(),非枚举属性也被复制了:
1const arr = ['a', 'b'];
2assert.equal(arr.length, 2);
3assert.equal({}.hasOwnProperty.call(arr, 'length'), true);
4
5const copy = copyAllOwnProperties(arr);
6assert.equal({}.hasOwnProperty.call(copy, 'length'), true);
JavaScript 的深拷贝
现在该解决深拷贝了。首先我们将手动进行深拷贝,然后再研究通用方法。
通过嵌套传播手动深拷贝
如果嵌套传播,则会得到深层副本:
1const original = {name: 'Jane', work: {employer: 'Acme'}};
2const copy = {name: original.name, work: {...original.work}};
3
4// We copied successfully:
5assert.deepEqual(original, copy);
6// The copy is deep:
7assert.ok(original.work !== copy.work);
Hack:通过 JSON 进行通用深拷贝
尽管这是一个 hack,但是在紧要关头,它提供了一个快速的解决方案:为了对 `original 对象进行深拷贝”,我们首先将其转换为 JSON 字符串,然后再解析该它:
1function jsonDeepCopy(original) {
2 return JSON.parse(JSON.stringify(original));
3}
4const original = {name: 'Jane', work: {employer: 'Acme'}};
5const copy = jsonDeepCopy(original);
6assert.deepEqual(original, copy);
这种方法的主要缺点是,我们只能复制具有 JSON 支持的键和值的属性。
一些不受支持的键和值将被忽略:
1assert.deepEqual(
2 jsonDeepCopy({
3 [Symbol('a')]: 'abc',
4 b: function () {},
5 c: undefined,
6 }),
7 {} // empty object
8);
其他导致的例外:
1assert.throws(
2 () => jsonDeepCopy({a: 123n}),
3 /^TypeError: Do not know how to serialize a BigInt$/);
实现通用深拷贝
可以用以下函数进行通用深拷贝:
1function deepCopy(original) {
2 if (Array.isArray(original)) {
3 const copy = [];
4 for (const [index, value] of original.entries()) {
5 copy[index] = deepCopy(value);
6 }
7 return copy;
8 } else if (typeof original === 'object' && original !== null) {
9 const copy = {};
10 for (const [key, value] of Object.entries(original)) {
11 copy[key] = deepCopy(value);
12 }
13 return copy;
14 } else {
15 // Primitive value: atomic, no need to copy
16 return original;
17 }
18}
该函数处理三种情况:
• 如果 original 是一个数组,我们创建一个新的 Array,并将 original 的元素复制到其中。
• 如果 original 是一个对象,我们将使用类似的方法。
• 如果 original 是原始值,则无需执行任何操作。
让我们尝试一下deepCopy()
1const original = {a: 1, b: {c: 2, d: {e: 3}}};
2const copy = deepCopy(original);
3
4// Are copy and original deeply equal?
5assert.deepEqual(copy, original);
6
7// Did we really copy all levels
8// (equal content, but different objects)?
9assert.ok(copy !== original);
10assert.ok(copy.b !== original.b);
11assert.ok(copy.b.d !== original.b.d);
注意,deepCopy() 仅解决了一个扩展问题:浅拷贝。而其他所有内容:不复制原型,仅部分复制特殊对象,忽略不可枚举的属性,忽略大多数属性。
通常完全完全实现复制是不可能的:并非所有数据的都是一棵树,有时你并不需要所有属性,等等。
更简洁的 `deepCopy()` 版本
如果我们使用 .map()Object.fromEntries(),可以使以前的 deepCopy() 实现更加简洁:
1function deepCopy(original) {
2 if (Array.isArray(original)) {
3 return original.map(elem => deepCopy(elem));
4 } else if (typeof original === 'object' && original !== null) {
5 return Object.fromEntries(
6 Object.entries(original)
7 .map(([k, v]) => [k, deepCopy(v)]));
8 } else {
9 // Primitive value: atomic, no need to copy
10 return original;
11 }
12}
在类中实现深拷贝(高级)
通常使用两种技术可以实现类实例的深拷贝:
• .clone() 方法
• 复制构造函数
`.clone()` 方法
该技术为每个类引入了一个方法 .clone(),其实例将被深拷贝。它返回 this 的深层副本。以下例子显示了可以克隆的三个类。
1class Point {
2 constructor(x, y) {
3 this.x = x;
4 this.y = y;
5 }
6 clone() {
7 return new Point(this.x, this.y);
8 }
9}
10class Color {
11 constructor(name) {
12 this.name = name;
13 }
14 clone() {
15 return new Color(this.name);
16 }
17}
18class ColorPoint extends Point {
19 constructor(x, y, color) {
20 super(x, y);
21 this.color = color;
22 }
23 clone() {
24 return new ColorPoint(
25 this.x, this.y, this.color.clone()); // (A)
26 }
27}
A 行展示了此技术的一个重要方面:复合实例属性值也必须递归克隆。
静态工厂方法
拷贝构造函数是用当前类的另一个实例来设置当前实例的构造函数。拷贝构造函数在静态语言(例如 C++ 和 Java)中很流行,你可以在其中通过 static 重载static 表示它在编译时发生)提供构造函数的多个版本。
在 JavaScript 中,你可以执行以下操作(但不是很优雅):
1class Point {
2 constructor(...args) {
3 if (args[0] instanceof Point) {
4 // Copy constructor
5 const [other] = args;
6 this.x = other.x;
7 this.y = other.y;
8 } else {
9 const [x, y] = args;
10 this.x = x;
11 this.y = y;
12 }
13 }
14}
这是使用方法:
1const original = new Point(-1, 4);
2const copy = new Point(original);
3assert.deepEqual(copy, original);
相反,静态工厂方法在 JavaScript 中效果更好(static 意味着它们是类方法)。
在以下示例中,三个类 PointColorColorPoint 分别具有静态工厂方法 .from()
1class Point {
2 constructor(x, y) {
3 this.x = x;
4 this.y = y;
5 }
6 static from(other) {
7 return new Point(other.x, other.y);
8 }
9}
10class Color {
11 constructor(name) {
12 this.name = name;
13 }
14 static from(other) {
15 return new Color(other.name);
16 }
17}
18class ColorPoint extends Point {
19 constructor(x, y, color) {
20 super(x, y);
21 this.color = color;
22 }
23 static from(other) {
24 return new ColorPoint(
25 other.x, other.y, Color.from(other.color)); // (A)
26 }
27}
在 A 行中,我们再次使用递归复制。
这是 ColorPoint.from() 的工作方式:
1const original = new ColorPoint(-1, 4, new Color('red'));
2const copy = ColorPoint.from(original);
3assert.deepEqual(copy, original);
拷贝如何帮助共享可变状态?
只要我们仅从共享状态读取,就不会有任何问题。在修改它之前,我们需要通过复制(必要的深度)来“取消共享”。
防御性复制是一种在问题可能出现时始终进行复制的技术。其目的是确保当前实体(函数、类等)的安全:
• 输入:复制(潜在地)传递给我们的共享数据,使我们可以使用该数据而不受外部实体的干扰。
• 输出:在将内部数据公开给外部方之前复制内部数据,意味着不会破坏我们的内部活动。
请注意,这些措施可以保护我们免受其他各方的侵害,同时也可以保护其他各方免受我们的侵害。
下一节说明两种防御性复制。
复制共享输入
请记住,在本文开头的例子中,我们遇到了麻烦,因为 logElements() 修改了其参数 arr
1function logElements(arr) {
2 while (arr.length > 0) {
3 console.log(arr.shift());
4 }
5}
让我们在此函数中添加防御性复制:
1function logElements(arr) {
2 arr = [...arr]; // defensive copy
3 while (arr.length > 0) {
4 console.log(arr.shift());
5 }
6}
现在,如果在 main() 内部调用 logElements() 不会再引发问题:
1function main() {
2 const arr = ['banana', 'orange', 'apple'];
3
4 console.log('Before sorting:');
5 logElements(arr);
6
7 arr.sort(); // changes arr
8
9 console.log('After sorting:');
10 logElements(arr); // (A)
11}
12main();
13
14// Output:
15// 'Before sorting:'
16// 'banana'
17// 'orange'
18// 'apple'
19// 'After sorting:'
20// 'apple'
21// 'banana'
22// 'orange'
复制公开的内部数据
让我们从 StringBuilder 类开始,该类不会复制它公开的内部数据(A行):
1class StringBuilder {
2 constructor() {
3 this._data = [];
4 }
5 add(str) {
6 this._data.push(str);
7 }
8 getParts() {
9 // We expose internals without copying them:
10 return this._data; // (A)
11 }
12 toString() {
13 return this._data.join('');
14 }
15}
只要不使用 .getParts(),一切就可以正常工作:
1const sb1 = new StringBuilder();
2sb1.add('Hello');
3sb1.add(' world!');
4assert.equal(sb1.toString(), 'Hello world!');
但是,如果更改了 .getParts() 的结果(A行),则 StringBuilder 会停止正常工作:
1const sb2 = new StringBuilder();
2sb2.add('Hello');
3sb2.add(' world!');
4sb2.getParts().length = 0; // (A)
5assert.equal(sb2.toString(), ''); // not OK
解决方案是在内部 ._data 被公开之前防御性地对它进行复制(A行):
1class StringBuilder {
2 constructor() {
3 this._data = [];
4 }
5 add(str) {
6 this._data.push(str);
7 }
8 getParts() {
9 // Copy defensively
10 return [...this._data]; // (A)
11 }
12 toString() {
13 return this._data.join('');
14 }
15}
现在,更改 .getParts() 的结果不再干扰 sb 的操作:
1const sb = new StringBuilder();
2sb.add('Hello');
3sb.add(' world!');
4sb.getParts().length = 0;
5assert.equal(sb.toString(), 'Hello world!'); // OK
通过无损更新来避免数据改变
我们将首先探讨以破坏性方式和非破坏性方式更新数据之间的区别。然后将学习非破坏性更新如何避免数据改变。
背景:破坏性更新与非破坏性更新
我们可以区分两种不同的数据更新方式:
• 数据的破坏性更新使数据被改变,使数据本身具有所需的形式。
• 数据的非破坏性更新创建具有所需格式的数据副本。
后一种方法类似于先复制然后破坏性地更改它,但两者同时进行。
示例:以破坏性和非破坏性的方式更新对象
这就是我们破坏性地设置对象的属性 .city 的方式:
1const obj = {city: 'Berlin', country: 'Germany'};
2const key = 'city';
3obj[key] = 'Munich';
4assert.deepEqual(obj, {city: 'Munich', country: 'Germany'});
以下函数以非破坏性的方式更改属性:
1function setObjectNonDestructively(obj, key, value) {
2 const updatedObj = {};
3 for (const [k, v] of Object.entries(obj)) {
4 updatedObj[k] = (k === key ? value : v);
5 }
6 return updatedObj;
7}
它的用法如下:
1const obj = {city: 'Berlin', country: 'Germany'};
2const updatedObj = setObjectNonDestructively(obj, 'city', 'Munich');
3assert.deepEqual(updatedObj, {city: 'Munich', country: 'Germany'});
4assert.deepEqual(obj, {city: 'Berlin', country: 'Germany'});
传播使 setObjectNonDestructively() 更加简洁:
1function setObjectNonDestructively(obj, key, value) {
2 return {...obj, [key]: value};
3}
注意:setObject NonDestructively() 的两个版本都进行了较浅的更新。
示例:以破坏性和非破坏性的方式更新数组
以下是破坏性地设置数组元素的方式:
1const original = ['a', 'b', 'c', 'd', 'e'];
2original[2] = 'x';
3assert.deepEqual(original, ['a', 'b', 'x', 'd', 'e']);
非破坏性地更新数组要复杂得多。
1function setArrayNonDestructively(arr, index, value) {
2 const updatedArr = [];
3 for (const [i, v] of arr.entries()) {
4 updatedArr.push(i === index ? value : v);
5 }
6 return updatedArr;
7}
8
9const arr = ['a', 'b', 'c', 'd', 'e'];
10const updatedArr = setArrayNonDestructively(arr, 2, 'x');
11assert.deepEqual(updatedArr, ['a', 'b', 'x', 'd', 'e']);
12assert.deepEqual(arr, ['a', 'b', 'c', 'd', 'e']);
.slice() 和扩展使 setArrayNonDestructively() 更加简洁:
1function setArrayNonDestructively(arr, index, value) {
2 return [
3 ...arr.slice(0, index), value, ...arr.slice(index+1)]
4}
注意:setArrayNonDestructively() 的两个版本都进行了较浅的更新。
手动深度更新
到目前为止,我们只是浅层地更新了数据。让我们来解决深度更新。以下代码显示了如何手动执行此操作。我们正在更改 nameemployer
1const original = {name: 'Jane', work: {employer: 'Acme'}};
2const updatedOriginal = {
3 ...original,
4 name: 'John',
5 work: {
6 ...original.work,
7 employer: 'Spectre'
8 },
9};
10
11assert.deepEqual(
12 original, {name: 'Jane', work: {employer: 'Acme'}});
13assert.deepEqual(
14 updatedOriginal, {name: 'John', work: {employer: 'Spectre'}});
实现通用深度更新
以下函数实现了通用的深度更新。
1function deepUpdate(original, keys, value) {
2 if (keys.length === 0) {
3 return value;
4 }
5 const currentKey = keys[0];
6 if (Array.isArray(original)) {
7 return original.map(
8 (v, index) => index === currentKey
9 ? deepUpdate(v, keys.slice(1), value) // (A)
10 : v); // (B)
11 } else if (typeof original === 'object' && original !== null) {
12 return Object.fromEntries(
13 Object.entries(original).map(
14 (keyValuePair) => {
15 const [k,v] = keyValuePair;
16 if (k === currentKey) {
17 return [k, deepUpdate(v, keys.slice(1), value)]; // (C)
18 } else {
19 return keyValuePair; // (D)
20 }
21 }));
22 } else {
23 // Primitive value
24 return original;
25 }
26}
如果我们将 value 视为要更新的树的根,则 deepUpdate() 只会深度更改单个分支(A 和 C 行)。所有其他分支均被浅复制(B 和 D 行)。
以下是使用 deepUpdate() 的样子:
1const original = {name: 'Jane', work: {employer: 'Acme'}};
2
3const copy = deepUpdate(original, ['work', 'employer'], 'Spectre');
4assert.deepEqual(copy, {name: 'Jane', work: {employer: 'Spectre'}});
5assert.deepEqual(original, {name: 'Jane', work: {employer: 'Acme'}});
非破坏性更新如何帮助共享可变状态?
使用非破坏性更新,共享数据将变得毫无问题,因为我们永远不会改变共享数据。(显然,这只有在各方都这样做的情况下才有效。)
有趣的是,复制数据变得非常简单:
1const original = {city: 'Berlin', country: 'Germany'};
2const copy = original;
仅在必要时以及在我们进行无损更改的情况下,才进行 original 的实际复制。
通过使数据不变来防止数据改变
我们可以通过使共享数据不变来防止共享数据发生改变。接下来,我们将研究 JavaScript 如何支持不变性。之后,讨论不可变数据如何帮助共享可变状态。
背景:JavaScript 中的不变性
JavaScript 具有三个级别的保护对象:
• Preventing extensions 使得无法向对象添加新属性。但是,你仍然可以删除和更改属性。
• 方法: Object.preventExtensions(obj)
• Sealing 可以防止扩展,并使所有属性都无法配置(大约:您无法再更改属性的工作方式)。
• 方法: Object.seal(obj)
• Freezing 使对象的所有属性不可写后将其密封。也就是说,对象是不可扩展的,所有属性都是只读的,无法更改它。
• 方法: Object.freeze(obj)
有关更多信息,请参见 “Speaking JavaScript”【】。
鉴于我们希望对象是完全不变的,因此在本文中仅使用 Object.freeze()
浅层冻结
Object.freeze(obj) 仅冻结 obj 及其属性。它不会冻结那些属性的值,例如:
1const teacher = {
2 name: 'Edna Krabappel',
3 students: ['Bart'],
4};
5Object.freeze(teacher);
6
7assert.throws(
8 () => teacher.name = 'Elizabeth Hoover',
9 /^TypeError: Cannot assign to read only property 'name'/);
10
11teacher.students.push('Lisa');
12assert.deepEqual(
13 teacher, {
14 name: 'Edna Krabappel',
15 students: ['Bart', 'Lisa'],
16 });
实现深度冻结
如果要深度冻结,则需要自己实现:
1function deepFreeze(value) {
2 if (Array.isArray(value)) {
3 for (const element of value) {
4 deepFreeze(element);
5 }
6 Object.freeze(value);
7 } else if (typeof value === 'object' && value !== null) {
8 for (const v of Object.values(value)) {
9 deepFreeze(v);
10 }
11 Object.freeze(value);
12 } else {
13 // Nothing to do: primitive values are already immutable
14 }
15 return value;
16}
回顾上一节中的例子,我们可以检查 deepFreeze() 是否真的冻结了:
1const teacher = {
2 name: 'Edna Krabappel',
3 students: ['Bart'],
4};
5deepFreeze(teacher);
6
7assert.throws(
8 () => teacher.name = 'Elizabeth Hoover',
9 /^TypeError: Cannot assign to read only property 'name'/);
10
11assert.throws(
12 () => teacher.students.push('Lisa'),
13 /^TypeError: Cannot add property 1, object is not extensible$/);
不可变包装器(高级)
用不可变的包装器包装可变的集合并提供相同的 API,但没有破坏性的操作。现在对于同一集合,我们有两个接口:一个是可变的,另一个是不可变的。当我们具有要安全的公开内部可变数据时,这很有用。
接下来展示了 Maps 和 Arrays 的包装器。它们都有以下限制:
• 它们比较简陋。为了使它们适合实际中的使用,需要做更多的工作:更好的检查,支持更多的方法等。
• 他们是浅拷贝。
map的不变包装器
ImmutableMapWrapper 为 map 生成包装器:
1class ImmutableMapWrapper {
2 constructor(map) {
3 this._self = map;
4 }
5}
6
7// Only forward non-destructive methods to the wrapped Map:
8for (const methodName of ['get', 'has', 'keys', 'size']) {
9 ImmutableMapWrapper.prototype[methodName] = function (...args) {
10 return this._self[methodName](...args);
11 }
12}
这是 action 中的类:
1const map = new Map([[false, 'no'], [true, 'yes']]);
2const wrapped = new ImmutableMapWrapper(map);
3
4// Non-destructive operations work as usual:
5assert.equal(
6 wrapped.get(true), 'yes');
7assert.equal(
8 wrapped.has(false), true);
9assert.deepEqual(
10 [...wrapped.keys()], [false, true]);
11
12// Destructive operations are not available:
13assert.throws(
14 () => wrapped.set(false, 'never!'),
15 /^TypeError: wrapped.set is not a function$/);
16assert.throws(
17 () => wrapped.clear(),
18 /^TypeError: wrapped.clear is not a function$/);
19
数组的不可变包装器
对于数组 arr,常规包装是不够的,因为我们不仅需要拦截方法调用,而且还需要拦截诸如 arr [1] = true 之类的属性访问。JavaScript proxies 使我们能够执行这种操作:
1const RE_INDEX_PROP_KEY = /^[0-9]+$/;
2const ALLOWED_PROPERTIES = new Set([
3 'length', 'constructor', 'slice', 'concat']);
4
5function wrapArrayImmutably(arr) {
6 const handler = {
7 get(target, propKey, receiver) {
8 // We assume that propKey is a string (not a symbol)
9 if (RE_INDEX_PROP_KEY.test(propKey) // simplified check!
10 || ALLOWED_PROPERTIES.has(propKey)) {
11 return Reflect.get(target, propKey, receiver);
12 }
13 throw new TypeError(`Property "${propKey}" can’t be accessed`);
14 },
15 set(target, propKey, value, receiver) {
16 throw new TypeError('Setting is not allowed');
17 },
18 deleteProperty(target, propKey) {
19 throw new TypeError('Deleting is not allowed');
20 },
21 };
22 return new Proxy(arr, handler);
23}
让我们包装一个数组:
1const arr = ['a', 'b', 'c'];
2const wrapped = wrapArrayImmutably(arr);
3
4// Non-destructive operations are allowed:
5assert.deepEqual(
6 wrapped.slice(1), ['b', 'c']);
7assert.equal(
8 wrapped[1], 'b');
9
10// Destructive operations are not allowed:
11assert.throws(
12 () => wrapped[1] = 'x',
13 /^TypeError: Setting is not allowed$/);
14assert.throws(
15 () => wrapped.shift(),
16 /^TypeError: Property "shift" can’t be accessed$/);
不变性如何帮助共享可变状态?
如果数据是不可变的,则可以共享数据而没有任何风险。特别是无需防御性复制。
非破坏性更新是对不变数据的补充,使其与可变数据一样通用,但没有相关风险。
用于避免共享可变状态的库
有几种可用于 JavaScript 的库,它们支持对不可变数据进行无损更新。其中流行的两种是:
• Immutable.js 提供了不变(版本)的数据结构,例如 ListMapSetStack
• Immer 还支持不可变性和非破坏性更新,但仅适用于普通对象和数组。
Immutable.js
在其存储库中,Immutable.js 的描述为:
用于 JavaScript 的不可变的持久数据集,可提高效率和简便性。
Immutable.js 提供了不可变的数据结构,例如:
• List
• Map (不同于JavaScript的内置Map
• Set (不同于JavaScript的内置 Set
• Stack
在以下示例中,我们使用不可变的 Map
1import {Map} from 'immutable/dist/immutable.es.js';
2const map0 = Map([
3 [false, 'no'],
4 [true, 'yes'],
5]);
6
7const map1 = map0.set(true, 'maybe'); // (A)
8assert.ok(map1 !== map0); // (B)
9assert.equal(map1.equals(map0), false);
10
11const map2 = map1.set(true, 'yes'); // (C)
12assert.ok(map2 !== map1);
13assert.ok(map2 !== map0);
14assert.equal(map2.equals(map0), true); // (D)
说明:
• 在 A 行中,我们新创建了一个 map0 的不同版本 map1,其中 true 映射到了 'maybe'
• 在 B 行中,我们检查更改是否为非破坏性的。
• 在 C 行中,我们更新 map1,并撤消在 A 行中所做的更改。
• 在 D 行中,我们使用 Immutable 的内置 .equals() 方法来检查是否确实撤消了更改。
Immer
在其存储库中,Immer 库 的描述为:
通过更改当前状态来创建下一个不可变状态。
Immer 有助于非破坏性地更新(可能嵌套)普通对象和数组。也就是说,不涉及特殊的数据结构。
这是使用 Immer 的样子:
1import {produce} from 'immer/dist/immer.module.js';
2
3const people = [
4 {name: 'Jane', work: {employer: 'Acme'}},
5];
6
7const modifiedPeople = produce(people, (draft) => {
8 draft[0].work.employer = 'Cyberdyne';
9 draft.push({name: 'John', work: {employer: 'Spectre'}});
10});
11
12assert.deepEqual(modifiedPeople, [
13 {name: 'Jane', work: {employer: 'Cyberdyne'}},
14 {name: 'John', work: {employer: 'Spectre'}},
15]);
16assert.deepEqual(people, [
17 {name: 'Jane', work: {employer: 'Acme'}},
18]);
原始数据存储在 people 中。produce() 为我们提供了一个变量 draft。我们假设这个变量是 people,并使用通常会进行破坏性更改的操作。Immer 拦截了这些操作。代替变异draft,它无损地改变 people。结果由 modifiedPeople 引用。它是一成不变的。
致谢
• Ron Korvig 提醒我在 JavaScript 中进行深拷贝时使用静态工厂方法,而不要重载构造函数。
本文分享自微信公众号 - 前端先锋(jingchengyideng),作者:疯狂的技术宅
原文出处及转载信息见文内详细说明,如有侵权,请联系 [email protected] 删除。
原始发表时间:2019-10-28
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句
0 条评论
登录 后参与评论
相关文章
• 七个简单但棘手的 JS 面试问题[每日前端夜话0xD4]
如果你参加 JavaScript 高级开发面试,那么很有可能在编码面试中被问到一些棘手的问题。
疯狂的技术宅
• 用JavaScript把CSV与Excel转为Json[每日前端夜话0xC5]
有两个 JavaScript 插件可用于读取和处理 CSV 和 Excel 文件,之后仅对自己的脚本进行编码即可。
疯狂的技术宅
• JavaScript的工作原理:V8引擎内部机制及优化代码的5个技巧 [每日前端夜话(0x15)]
几个星期前,我们开始了一系列旨在深入挖掘 JavaScript 及其工作原理的系列:通过了解JavaScript的构建模块以及它们如何共同发挥作用,你将能够编写...
疯狂的技术宅
• 127个常用的JS代码片段,每段代码花30秒就能看懂(一)
JavaScript 是目前最流行的编程语言之一,正如大多数人所说:“如果你想学一门编程语言,请学JavaScript。”
前端达人
• 速读原著-TCP/IP(IP分片)
正如我们在2 . 8节描述的那样,物理网络层一般要限制每次发送数据帧的最大长度。任何时候I P层接收到一份要发送的 I P数据报时,它要判断向本地哪个接口发送数...
cwl_java
• 数据库分库分表,分片配置轻松入门!
当我们把 MyCat + MySQL 的架构搭建完成之后,接下来面临的一个问题就是,数据库的分片规则:有那么多 MySQL ,一条记录通过 MyCat 到底要插...
江南一点雨
• 大数据的搜索引擎——ElasticSearch
结果显示分片大都是因为 node_left 导致未分配,然后通过 explain API 查看分片 myindex[3] 不自动分配的具体原因:
用户4143945
• 解析 Elasticsearch 棘手问题,集群的 RED 与 YELLOW
结果显示分片大都是因为 node_left 导致未分配,然后通过 explain API 查看分片 myindex[3] 不自动分配的具体原因:
Java3y
• 解析 Elasticsearch 棘手问题,集群的 RED 与 YELLOW
结果显示分片大都是因为 node_left 导致未分配,然后通过 explain API 查看分片 myindex[3] 不自动分配的具体原因:
用户1737318
• 一文读懂分片基础原理, 数据分片, 跨分片交易, 区块链分片和缩放究竟是什么鬼?
以太坊是所有区块链中一直与分片概念同步的底层平台,想要理解为什么以太坊开发者社区想要实现分片,重点是要理解分片是什么,以及这个解决方案为何如此有吸引力。
区块链大本营
扫码关注云+社区
领取腾讯云代金券
|
__label__pos
| 0.997425 |
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 need to determine if a value exists in an array using javascript.
I am using the following function:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
The above function always returns false.
The array values and the function call is as below
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
Please suggest what to do
share|improve this question
6
The code works in Safari 4.0.2. BTW: I'd do a === comparison instead of just ==. – Georg Schölly Jul 25 '09 at 8:45
1
"The above function always returns false." No it doesn't: The function works as expected - the error must be somewhere else. – Christoph Jul 25 '09 at 8:59
1
See also: stackoverflow.com/q/237104/1569 – Factor Mystic Feb 18 '11 at 21:08
1
Finally its worked. its due to improper trim of the comparing value. there was some space in the comparing value (A comment from the asker, to the accepted answer.) – ANeves Oct 1 '12 at 9:09
add comment
11 Answers
up vote 313 down vote accepted
arrValues.indexOf('Sam') > -1
IE 8 and below do not have the Array.prototype.indexOf method. For these versions of IE use:
if(!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
Edit after a long time: It's best not to patch the prototype of native primitives in JavaScript. A better way:
var indexOf = function(needle) {
if(typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
if(this[i] === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = indexOf.call(myArray, needle); // 1
The function will detect the presence of a native indexOf method, once, then overwrite itself with either the native function or the shim.
share|improve this answer
2
Note that indexOf on arrays is not implemented in IE, but you can define it yourself – RaYell Jul 25 '09 at 8:36
5
you should use a typed comparison with === to be compatible with the native implementation – Christoph Jul 25 '09 at 9:08
2
fixed the comparison and added the missing return -1; please note that according to the ES5 spec, this method will behave differently from the native one in case ofsigned zeroes and NaNs (see 15.4.4.14 and 9.12 vs. 11.9.6) – Christoph Jul 25 '09 at 9:26
3
What version of IE does this answer refer to? – Daniel Allen Langdon Feb 24 '12 at 22:20
3
@RiceFlourCookies, IE < 9. – eyelidlessness Feb 25 '12 at 0:54
show 8 more comments
jQuery has a utility function for this:
$.inArray(value, array)
Returns index of value in array. Returns -1 if array does not contain value.
See also array.contains(obj) in JavaScript
share|improve this answer
54
Don't let the name "inArray" fool you. As mentioned above (but of course I didn't read closely enough), returns -1 (not false) if the element doesn't exist. – Greg Bernhardt Apr 19 '11 at 20:13
15
I can't believe they named the function so badly. – Steve Paul Jun 6 '13 at 8:23
1
@Steve Paul what is wrong with name? it does what it says: -1=it's NOT there, anything else= it's there – Jeffz Jun 22 '13 at 18:09
31
'inArray' implies that a boolean will be returned indicating whether the element could be found in the array. Therefore users may feel tempted to use the expression: if ($.inArray('myval', myarray)) {...} This will evaluate to true if 'myval' is NOT in myarray. Furthermore, it will evaluate to false if myval's index is 0. – Steve Paul Jun 24 '13 at 5:11
The non-booleanness of $.inArray's return definitely feels like a mistake on jQuery's part. Surely, it ought to be renamed to $.indexOf, if that's the function it's polyfilling? – ChaseMoskal Mar 7 at 23:01
add comment
An option that accounts for different types within the array (corrected to make p local to the for-loop):
Array.prototype.contains = function(k) {
for(var p in this)
if(this[p] === k)
return true;
return false;
}
for example:
var list = ["one",2];
list.contains("one") // returns true
list.contains("2") // returns false
list.contains(2) // returns true
share|improve this answer
1
Isn't this technique of augmenting built-in types frowned upon? – Twilight Pony Inc. Oct 11 '12 at 3:49
3
Why does p have to pollute the global scope? – Micah Henning Nov 24 '12 at 1:22
Good point Micah. I've modified the code to make p local. – threed Nov 26 '12 at 18:56
1
Buggy: [1,2,4].contains([].contains) is true. Also unnecessarily slow due to the same bug. Avoid for..in over arrays. – Eamon Nerbonne Jan 17 '13 at 15:02
@Eamon Nerbonne: I just pasted that code into jsfiddle.net and got false. Am I doing something wrong. Also, could you elaborate on how this bug slows the code down? Finally, I wasn't aware that there is a performance difference for "for..in" loops. Could you explain or direct me towards an article where I could read more? – threed Jan 18 '13 at 17:59
show 2 more comments
Given the implementation of indexOf for IE (as described by eyelidlessness):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
share|improve this answer
3
That's redundant. – eyelidlessness Jul 25 '09 at 9:34
3
Maybe, but it makes your code cleaner. if (myArray.contains(obj)) is easier to read and states the intent better than if (myArray.indexOf(obj) > -1). I definitively would implement both. – rlovtang Jul 25 '09 at 13:52
Does this work in all browsers? Or do some browsers consider the index of "2" and 2 the same? – threed Oct 11 '12 at 20:52
add comment
This is generally what the indexOf() method is for. You would say:
if (arrValues.indexOf('Sam') > -1) {return true;}
else {return false;}
share|improve this answer
13
you can reduce that to: return (arrValues.indexOf('Sam') > -1); – Kenneth J Apr 22 '10 at 19:34
add comment
The answer provided didn't work for me, but it gave me an idea:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
var c=[];
var d=[];
function a()
{
var e = '1';
var f = '2';
c[0] = ['1','1'];
c[1] = ['2','2'];
c[2] = ['3','3'];
d[0] = [document.getElementById('g').value,document.getElementById('h').value];
document.getElementById('i').value = c.join(',');
document.getElementById('j').value = d.join(',');
document.getElementById('b').value = c.contains(d);
}
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.
share|improve this answer
add comment
You can use _.indexOf method or if you don't want to include whole Underscore.js library in your app, you can have a look how they did it and extract necessary code.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
share|improve this answer
add comment
It's almost always safe to use a library like underscore.js, simply because of all the issues with cross-browser compatibilities and effieciency.
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
_.contains([1, 2, 3], 3); // returns true
share|improve this answer
add comment
I highly think that you should regular expression there. I found this brief tutorial very helpful myself: Match an element against an array with regular expression
share|improve this answer
You should always use regex sparingly. Especially provided that there are simpler ways of accomplishing the task. – ncabral Jan 25 at 3:01
add comment
My little contribution:
function isInArray(array, search)
{
return (array.indexOf(search) >= 0) ? true : false;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
share|improve this answer
add comment
If the list is fixed, you can use the native hasOwnProperty
var arrValues = {Alpha:0, Beta:0, Gamma:0};
alert(arrValues.hasOwnProperty("Beta"));
share|improve this answer
5
the is not an array. its a hash-map – Kumar Harsh Sep 21 '12 at 7:01
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.585055 |
Can someone explain this code to me?
This code was given to us in class as an example, but my prof has a rough accent and its hard to understand her. here is the code:
/* Colour Morph
Example for COMP 1010
Draw a bar across the centre of the window, with height
BAR_HEIGHT, that consists of NUM_STEPS rectangles of
equal width, with the left one having the colour set by
INIT_RED, INIT_GREEN, INIT_BLUE, and the right one set by
FINAL_RED, FINAL_GREEN, and FINAL_BLUE, and changing
smoothly in between.
*/
size(700,200); //Make it wide but not too tall.
final int NUM_STEPS = 8; //The number of different coloured bars to use
final int BAR_HEIGHT = 150; //The height of the bar
final float BAR_WIDTH = (float)width/NUM_STEPS; //The width of each small slice
final float INIT_RED=156, INIT_GREEN=63, INIT_BLUE=178; //Initial colour
final float FINAL_RED=25, FINAL_GREEN=162, FINAL_BLUE=159; //Final colour
for(int i=0; i<NUM_STEPS; i++){
//i will be 0,1,...,NUMSTEPS-1
float position = i/(NUM_STEPS-1.0); //A value from 0.0 to 1.0
float redValue = INIT_RED+(FINAL_RED-INIT_RED)*position;
float greenValue = INIT_GREEN+(FINAL_GREEN-INIT_GREEN)*position;
float blueValue = INIT_BLUE+(FINAL_BLUE-INIT_BLUE)*position;
fill(redValue,greenValue,blueValue);
stroke(redValue,greenValue,blueValue); //Make the outline match, too.
rect(i*BAR_WIDTH,(height-BAR_HEIGHT)/2,BAR_WIDTH,BAR_HEIGHT);
}//for
In the loop, why do we use those operations? If I was asked to code this on an exam, how would I know to do that?? I dont get the logic behind it
Tagged:
Answers
• Answer ✓
Forget about that code for now. Let's just say you want to draw a rectangle. Just one rectangle. What do you need to know about this rectangle in order to be able to draw it?
I can think of a few things. First, you need to know where the rectangle is going to be drawn. Then you need to know how big the rectangle is going to be. And you also need to know what color the rectangle is.
That's already like, seven variables! The x position, the y position, the width, the height, the amount of red, the amount of green, and the amount of blue.
So here is some code that draws a rectangle.
size(600,400);
background(0);
fill(200,100,50);
rect(30,80,90,180);
Notice that the color is sort of orange. This is because I set the fill color to 200 red, 10 green, and 50 blue. Notice that the rectangle is at (30,80), and is 90 wide and 180 high.
• Answer ✓
Now that we have one rectangle done, let's draw many rectangles across the screen. How many rectangles should we drawn? Let's pick 8. Okay, so we want to draw 8 rectangles. How wide are they going to be? Well, each one needs to be 1/8 of the width of the sketch, so we know the width of each rectangle is width/8. We also want to draw them at different horizontal positions, so they are not all in the same place.
size(600, 400);
background(0);
fill(200, 100, 50);
rect(0*(width/8), 80, (width/8), 180);
rect(1*(width/8), 80, (width/8), 180);
rect(2*(width/8), 80, (width/8), 180);
rect(3*(width/8), 80, (width/8), 180);
rect(4*(width/8), 80, (width/8), 180);
rect(5*(width/8), 80, (width/8), 180);
rect(6*(width/8), 80, (width/8), 180);
rect(7*(width/8), 80, (width/8), 180);
Do you see a problem here? I do. This code is not DRY. DRY means Don't Repeat Yourself. If you see code that is doing the same thing over and over again, then realize immediately that there is a better way.
In this case, we can have a loop:
size(600, 400);
background(0);
fill(200, 100, 50);
for( int i = 0; i < 8; i++){
rect(i*(width/8), 80, (width/8), 180);
}
Still with me? The loop runs 8 times, and thus is draws 8 rectangles.
In fact, we really should not hard-code the 8 in. We could use variable instead, one that is the number of rectangles:
size(600, 400);
background(0);
fill(200, 100, 50);
int count = 9;
for( int i = 0; i < count; i++){
rect(i*(width/float(count)), 0, (width/float(count)), height);
}
Notice that I've also remove the division by 8 when it comes to widths now, as the width depends on how many rectangles there are. Instead, we're now dividing by the total number o rectangles, since each is 1/count the width of the sketch wide.
• edited December 2017 Answer ✓
If this code is starting to look similar to some example you already have, hopefully you can tell why. All that's really left to do is to make the colors go from one color to a different color.
So we should put in what the start and end colors are going to be.
int count = 9;
color start = color(200,100,50);
color end = color(0,255,0);
size(600, 400);
background(0);
fill(start);
for( int i = 0; i < count; i++){
rect(i*(width/float(count)), 0, (width/float(count)), height);
}
So the next question is... How much do you need to change each rectangle's color to get from the start color to the end color in count number of steps?
• edited December 2017 Answer ✓
Well, you have the crazy detailed example of doing that already. Basically you compute what the total change for each of the red, green, and blue amounts needs to be, and then do 1/count of that change for each rectangle.
Personally, this is much cleaner:
float count = 9;
color start = color(200,100,50);
color end = color(0,255,0);
size(600, 400);
background(0);
for( int i = 0; i < count; i++){
fill( lerpColor( start, end, i/(count-1) ) );
rect(i*(width/count), 0, (width/count), height);
}
And probably easier to understand.
• Wow this is so thorough.. thank you so much, I completely get it.. I wish you were my prof instead haha
Sign In or Register to comment.
|
__label__pos
| 0.932708 |
godaddy hit counter
How to solve circle problems in geometry accurately?
In some SAT circle problems you cannot have even an idea from math diagram of how to solve the circle problems. It means that the information given in the math shape is not sufficient. In such case, drawing an additional line by your judgment may help you to solve math circle problems. Following is an example to illustrate you how an additional line is added to solve circle problems in geometry.
How to solve circle problems:Example
In the figure, C is a point on the circle whose centre is O and whose radius is r, and OACB is a rectangle. What is the length of diagonal?How to solve circle problems
(A) 2/3 r
(B) r
(C) r2
(D) r2/2 п
(E) 2 r2/ п
Solution:
It is difficult to have an idea of diagonal AB with information given in the figure. So we draw line of radius OC (dotted line). How to solve circle problemsWe observe that OC and AB are diagonals of rectangle OABC. Since diagonal of a rectangle are always equal, so diagonal AB is equal to diagonal OC, which is radius r (B).
See you need not to use circle formula or triangle formula or Pythagorean Theorem to calculate the radius of the circle in this circle problem.
Top Query
How to solve circle problems easily?
{ 1 comment… read it below or add one }
Maria June 22, 2011 at 11:37 am
This is another approach to solving circle geometry questions. great idea!
Reply
Leave a Comment
Previous post:
Next post:
|
__label__pos
| 0.982943 |
** Pastebin PRO Accounts Winter Special ** Get 40% discount for a limited time only! Click Here to check it out ;-)Want more features on Pastebin? Sign Up, it's FREE!
Guest
Untitled
By: a guest on Apr 19th, 2010 | syntax: Diff | size: 2.46 KB | views: 114 | expires: Never
download | raw | embed | report abuse | print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. diff --git a/rbutil/mkamsboot/dualboot/dualboot.S b/rbutil/mkamsboot/dualboot/dualboot.S
2. index 8bb2059..426940c 100644
3. --- a/rbutil/mkamsboot/dualboot/dualboot.S
4. +++ b/rbutil/mkamsboot/dualboot/dualboot.S
5. @@ -101,7 +101,7 @@ uclcopy:
6. /* TODO : M200V4 ? */
7. #if defined(SANSA_CLIP) || defined(SANSA_CLIPV2)
8. #define USB_PIN 6
9. -#elif defined(SANSA_FUZE) || defined(SANSA_E200V2) || defined(SANSA_FUZEV2)
10. +#elif defined(SANSA_FUZE) || defined(SANSA_E200V2)
11. #define USB_PIN 3
12. #endif
13.
14. @@ -213,19 +213,59 @@ uclcopy:
15.
16. cmp r1, #0
17. beq boot_of
18. -#elif defined(SANSA_E200V2) || defined(SANSA_FUZE) || defined(SANSA_FUZEV2)
19. +#elif defined(SANSA_E200V2) || defined(SANSA_FUZE)
20. ldr r0, =GPIOC
21. mov r1, #0
22. str r1, [r0, #0x400]
23. ldr r1, [r0, #0x20] /* read pin C3 */
24.
25. cmp r1, #0 /* C3 = #0 means button pressed */
26. -#ifdef SANSA_FUZEV2
27. - /* the logic is reversed on the fuzev2 */
28. - bne boot_of
29. -#else
30. beq boot_of
31. -#endif /* SANSA_FUZEV2 */
32. +
33. +#elif defined(SANSA_FUZEV2)
34. + ldr r0, =GPIOC
35. + mov r1, #0
36. + str r1, [r0, #0x400]
37. + ldr r1, [r0, #0x40] /* read pin C4 */
38. +
39. + cmp r1, #0 /* C4 != #0 means select pressed */
40. + bne boot_of
41. +
42. +#if 0
43. + ldr r2, =0xC810000C @ CCU_IO
44. + ldr r3, [r2]
45. + bic r3, r3, #(1<<12) @ clear bit 12
46. + str r3, [r2]
47. +
48. + ldr r2, =GPIOB
49. + mov r3, #(1<<0)
50. + ldr r4, [r2, #0x400]
51. + orr r4, r4, r3 @ GPIOB_DIR: pin0 out
52. + str r4, [r2, #0x400]
53. +
54. + str r3, [r2, #0x4] @ GPIOB_PIN(0) = 1
55. + mov r4, #500
56. +1: nop
57. + subs r4, r4, #1
58. + bne 1b
59. +
60. + ldr r4, =GPIOD
61. + ldr r3, [r4, #0x400]
62. + bic r3, r3, #(1<<6)
63. + ldr r3, [r4, #0x100] @ read d6 and discard it
64. +
65. + mov r3, #0
66. + str r3, [r2, #0x4] @ GPIOB_PIN(0) = 0
67. + mov r4, #240
68. +1: nop
69. + subs r4, r4, #1
70. + bne 1b
71. +#endif
72. +
73. + ldr r1, [r0, #0x08] /* read pin C1 */
74. + ldr r1, [r0, #0x10] /* read pin C2 */
75. + ldr r1, [r0, #0x20] /* read pin C3 */
76. + bne boot_of /* C3 != #0 means left pressed */
77.
78. #elif defined(SANSA_CLIPPLUS)
79. @ read pins
clone this paste RAW Paste Data
|
__label__pos
| 0.682598 |
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2017 Nicira, Inc. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include #include #include #include #include #include #include #include #include #include #include "datapath.h" #include "meter.h" static const struct nla_policy meter_policy[OVS_METER_ATTR_MAX + 1] = { [OVS_METER_ATTR_ID] = { .type = NLA_U32, }, [OVS_METER_ATTR_KBPS] = { .type = NLA_FLAG }, [OVS_METER_ATTR_STATS] = { .len = sizeof(struct ovs_flow_stats) }, [OVS_METER_ATTR_BANDS] = { .type = NLA_NESTED }, [OVS_METER_ATTR_USED] = { .type = NLA_U64 }, [OVS_METER_ATTR_CLEAR] = { .type = NLA_FLAG }, [OVS_METER_ATTR_MAX_METERS] = { .type = NLA_U32 }, [OVS_METER_ATTR_MAX_BANDS] = { .type = NLA_U32 }, }; static const struct nla_policy band_policy[OVS_BAND_ATTR_MAX + 1] = { [OVS_BAND_ATTR_TYPE] = { .type = NLA_U32, }, [OVS_BAND_ATTR_RATE] = { .type = NLA_U32, }, [OVS_BAND_ATTR_BURST] = { .type = NLA_U32, }, [OVS_BAND_ATTR_STATS] = { .len = sizeof(struct ovs_flow_stats) }, }; static u32 meter_hash(struct dp_meter_instance *ti, u32 id) { return id % ti->n_meters; } static void ovs_meter_free(struct dp_meter *meter) { if (!meter) return; kfree_rcu(meter, rcu); } /* Call with ovs_mutex or RCU read lock. */ static struct dp_meter *lookup_meter(const struct dp_meter_table *tbl, u32 meter_id) { struct dp_meter_instance *ti = rcu_dereference_ovsl(tbl->ti); u32 hash = meter_hash(ti, meter_id); struct dp_meter *meter; meter = rcu_dereference_ovsl(ti->dp_meters[hash]); if (meter && likely(meter->id == meter_id)) return meter; return NULL; } static struct dp_meter_instance *dp_meter_instance_alloc(const u32 size) { struct dp_meter_instance *ti; ti = kvzalloc(sizeof(*ti) + sizeof(struct dp_meter *) * size, GFP_KERNEL); if (!ti) return NULL; ti->n_meters = size; return ti; } static void dp_meter_instance_free(struct dp_meter_instance *ti) { kvfree(ti); } static void dp_meter_instance_free_rcu(struct rcu_head *rcu) { struct dp_meter_instance *ti; ti = container_of(rcu, struct dp_meter_instance, rcu); kvfree(ti); } static int dp_meter_instance_realloc(struct dp_meter_table *tbl, u32 size) { struct dp_meter_instance *ti = rcu_dereference_ovsl(tbl->ti); int n_meters = min(size, ti->n_meters); struct dp_meter_instance *new_ti; int i; new_ti = dp_meter_instance_alloc(size); if (!new_ti) return -ENOMEM; for (i = 0; i < n_meters; i++) if (rcu_dereference_ovsl(ti->dp_meters[i])) new_ti->dp_meters[i] = ti->dp_meters[i]; rcu_assign_pointer(tbl->ti, new_ti); call_rcu(&ti->rcu, dp_meter_instance_free_rcu); return 0; } static void dp_meter_instance_insert(struct dp_meter_instance *ti, struct dp_meter *meter) { u32 hash; hash = meter_hash(ti, meter->id); rcu_assign_pointer(ti->dp_meters[hash], meter); } static void dp_meter_instance_remove(struct dp_meter_instance *ti, struct dp_meter *meter) { u32 hash; hash = meter_hash(ti, meter->id); RCU_INIT_POINTER(ti->dp_meters[hash], NULL); } static int attach_meter(struct dp_meter_table *tbl, struct dp_meter *meter) { struct dp_meter_instance *ti = rcu_dereference_ovsl(tbl->ti); u32 hash = meter_hash(ti, meter->id); int err; /* In generally, slots selected should be empty, because * OvS uses id-pool to fetch a available id. */ if (unlikely(rcu_dereference_ovsl(ti->dp_meters[hash]))) return -EBUSY; dp_meter_instance_insert(ti, meter); /* That function is thread-safe. */ tbl->count++; if (tbl->count >= tbl->max_meters_allowed) { err = -EFBIG; goto attach_err; } if (tbl->count >= ti->n_meters && dp_meter_instance_realloc(tbl, ti->n_meters * 2)) { err = -ENOMEM; goto attach_err; } return 0; attach_err: dp_meter_instance_remove(ti, meter); tbl->count--; return err; } static int detach_meter(struct dp_meter_table *tbl, struct dp_meter *meter) { struct dp_meter_instance *ti; ASSERT_OVSL(); if (!meter) return 0; ti = rcu_dereference_ovsl(tbl->ti); dp_meter_instance_remove(ti, meter); tbl->count--; /* Shrink the meter array if necessary. */ if (ti->n_meters > DP_METER_ARRAY_SIZE_MIN && tbl->count <= (ti->n_meters / 4)) { int half_size = ti->n_meters / 2; int i; /* Avoid hash collision, don't move slots to other place. * Make sure there are no references of meters in array * which will be released. */ for (i = half_size; i < ti->n_meters; i++) if (rcu_dereference_ovsl(ti->dp_meters[i])) goto out; if (dp_meter_instance_realloc(tbl, half_size)) goto shrink_err; } out: return 0; shrink_err: dp_meter_instance_insert(ti, meter); tbl->count++; return -ENOMEM; } static struct sk_buff * ovs_meter_cmd_reply_start(struct genl_info *info, u8 cmd, struct ovs_header **ovs_reply_header) { struct sk_buff *skb; struct ovs_header *ovs_header = info->userhdr; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return ERR_PTR(-ENOMEM); *ovs_reply_header = genlmsg_put(skb, info->snd_portid, info->snd_seq, &dp_meter_genl_family, 0, cmd); if (!*ovs_reply_header) { nlmsg_free(skb); return ERR_PTR(-EMSGSIZE); } (*ovs_reply_header)->dp_ifindex = ovs_header->dp_ifindex; return skb; } static int ovs_meter_cmd_reply_stats(struct sk_buff *reply, u32 meter_id, struct dp_meter *meter) { struct nlattr *nla; struct dp_meter_band *band; u16 i; if (nla_put_u32(reply, OVS_METER_ATTR_ID, meter_id)) goto error; if (nla_put(reply, OVS_METER_ATTR_STATS, sizeof(struct ovs_flow_stats), &meter->stats)) goto error; if (nla_put_u64_64bit(reply, OVS_METER_ATTR_USED, meter->used, OVS_METER_ATTR_PAD)) goto error; nla = nla_nest_start_noflag(reply, OVS_METER_ATTR_BANDS); if (!nla) goto error; band = meter->bands; for (i = 0; i < meter->n_bands; ++i, ++band) { struct nlattr *band_nla; band_nla = nla_nest_start_noflag(reply, OVS_BAND_ATTR_UNSPEC); if (!band_nla || nla_put(reply, OVS_BAND_ATTR_STATS, sizeof(struct ovs_flow_stats), &band->stats)) goto error; nla_nest_end(reply, band_nla); } nla_nest_end(reply, nla); return 0; error: return -EMSGSIZE; } static int ovs_meter_cmd_features(struct sk_buff *skb, struct genl_info *info) { struct ovs_header *ovs_header = info->userhdr; struct ovs_header *ovs_reply_header; struct nlattr *nla, *band_nla; struct sk_buff *reply; struct datapath *dp; int err = -EMSGSIZE; reply = ovs_meter_cmd_reply_start(info, OVS_METER_CMD_FEATURES, &ovs_reply_header); if (IS_ERR(reply)) return PTR_ERR(reply); ovs_lock(); dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex); if (!dp) { err = -ENODEV; goto exit_unlock; } if (nla_put_u32(reply, OVS_METER_ATTR_MAX_METERS, dp->meter_tbl.max_meters_allowed)) goto exit_unlock; ovs_unlock(); if (nla_put_u32(reply, OVS_METER_ATTR_MAX_BANDS, DP_MAX_BANDS)) goto nla_put_failure; nla = nla_nest_start_noflag(reply, OVS_METER_ATTR_BANDS); if (!nla) goto nla_put_failure; band_nla = nla_nest_start_noflag(reply, OVS_BAND_ATTR_UNSPEC); if (!band_nla) goto nla_put_failure; /* Currently only DROP band type is supported. */ if (nla_put_u32(reply, OVS_BAND_ATTR_TYPE, OVS_METER_BAND_TYPE_DROP)) goto nla_put_failure; nla_nest_end(reply, band_nla); nla_nest_end(reply, nla); genlmsg_end(reply, ovs_reply_header); return genlmsg_reply(reply, info); exit_unlock: ovs_unlock(); nla_put_failure: nlmsg_free(reply); return err; } static struct dp_meter *dp_meter_create(struct nlattr **a) { struct nlattr *nla; int rem; u16 n_bands = 0; struct dp_meter *meter; struct dp_meter_band *band; int err; /* Validate attributes, count the bands. */ if (!a[OVS_METER_ATTR_BANDS]) return ERR_PTR(-EINVAL); nla_for_each_nested(nla, a[OVS_METER_ATTR_BANDS], rem) if (++n_bands > DP_MAX_BANDS) return ERR_PTR(-EINVAL); /* Allocate and set up the meter before locking anything. */ meter = kzalloc(struct_size(meter, bands, n_bands), GFP_KERNEL); if (!meter) return ERR_PTR(-ENOMEM); meter->id = nla_get_u32(a[OVS_METER_ATTR_ID]); meter->used = div_u64(ktime_get_ns(), 1000 * 1000); meter->kbps = a[OVS_METER_ATTR_KBPS] ? 1 : 0; meter->keep_stats = !a[OVS_METER_ATTR_CLEAR]; spin_lock_init(&meter->lock); if (meter->keep_stats && a[OVS_METER_ATTR_STATS]) { meter->stats = *(struct ovs_flow_stats *) nla_data(a[OVS_METER_ATTR_STATS]); } meter->n_bands = n_bands; /* Set up meter bands. */ band = meter->bands; nla_for_each_nested(nla, a[OVS_METER_ATTR_BANDS], rem) { struct nlattr *attr[OVS_BAND_ATTR_MAX + 1]; u32 band_max_delta_t; err = nla_parse_deprecated((struct nlattr **)&attr, OVS_BAND_ATTR_MAX, nla_data(nla), nla_len(nla), band_policy, NULL); if (err) goto exit_free_meter; if (!attr[OVS_BAND_ATTR_TYPE] || !attr[OVS_BAND_ATTR_RATE] || !attr[OVS_BAND_ATTR_BURST]) { err = -EINVAL; goto exit_free_meter; } band->type = nla_get_u32(attr[OVS_BAND_ATTR_TYPE]); band->rate = nla_get_u32(attr[OVS_BAND_ATTR_RATE]); if (band->rate == 0) { err = -EINVAL; goto exit_free_meter; } band->burst_size = nla_get_u32(attr[OVS_BAND_ATTR_BURST]); /* Figure out max delta_t that is enough to fill any bucket. * Keep max_delta_t size to the bucket units: * pkts => 1/1000 packets, kilobits => bits. * * Start with a full bucket. */ band->bucket = band->burst_size * 1000ULL; band_max_delta_t = div_u64(band->bucket, band->rate); if (band_max_delta_t > meter->max_delta_t) meter->max_delta_t = band_max_delta_t; band++; } return meter; exit_free_meter: kfree(meter); return ERR_PTR(err); } static int ovs_meter_cmd_set(struct sk_buff *skb, struct genl_info *info) { struct nlattr **a = info->attrs; struct dp_meter *meter, *old_meter; struct sk_buff *reply; struct ovs_header *ovs_reply_header; struct ovs_header *ovs_header = info->userhdr; struct dp_meter_table *meter_tbl; struct datapath *dp; int err; u32 meter_id; bool failed; if (!a[OVS_METER_ATTR_ID]) return -EINVAL; meter = dp_meter_create(a); if (IS_ERR(meter)) return PTR_ERR(meter); reply = ovs_meter_cmd_reply_start(info, OVS_METER_CMD_SET, &ovs_reply_header); if (IS_ERR(reply)) { err = PTR_ERR(reply); goto exit_free_meter; } ovs_lock(); dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex); if (!dp) { err = -ENODEV; goto exit_unlock; } meter_tbl = &dp->meter_tbl; meter_id = nla_get_u32(a[OVS_METER_ATTR_ID]); old_meter = lookup_meter(meter_tbl, meter_id); err = detach_meter(meter_tbl, old_meter); if (err) goto exit_unlock; err = attach_meter(meter_tbl, meter); if (err) goto exit_unlock; ovs_unlock(); /* Build response with the meter_id and stats from * the old meter, if any. */ failed = nla_put_u32(reply, OVS_METER_ATTR_ID, meter_id); WARN_ON(failed); if (old_meter) { spin_lock_bh(&old_meter->lock); if (old_meter->keep_stats) { err = ovs_meter_cmd_reply_stats(reply, meter_id, old_meter); WARN_ON(err); } spin_unlock_bh(&old_meter->lock); ovs_meter_free(old_meter); } genlmsg_end(reply, ovs_reply_header); return genlmsg_reply(reply, info); exit_unlock: ovs_unlock(); nlmsg_free(reply); exit_free_meter: kfree(meter); return err; } static int ovs_meter_cmd_get(struct sk_buff *skb, struct genl_info *info) { struct ovs_header *ovs_header = info->userhdr; struct ovs_header *ovs_reply_header; struct nlattr **a = info->attrs; struct dp_meter *meter; struct sk_buff *reply; struct datapath *dp; u32 meter_id; int err; if (!a[OVS_METER_ATTR_ID]) return -EINVAL; meter_id = nla_get_u32(a[OVS_METER_ATTR_ID]); reply = ovs_meter_cmd_reply_start(info, OVS_METER_CMD_GET, &ovs_reply_header); if (IS_ERR(reply)) return PTR_ERR(reply); ovs_lock(); dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex); if (!dp) { err = -ENODEV; goto exit_unlock; } /* Locate meter, copy stats. */ meter = lookup_meter(&dp->meter_tbl, meter_id); if (!meter) { err = -ENOENT; goto exit_unlock; } spin_lock_bh(&meter->lock); err = ovs_meter_cmd_reply_stats(reply, meter_id, meter); spin_unlock_bh(&meter->lock); if (err) goto exit_unlock; ovs_unlock(); genlmsg_end(reply, ovs_reply_header); return genlmsg_reply(reply, info); exit_unlock: ovs_unlock(); nlmsg_free(reply); return err; } static int ovs_meter_cmd_del(struct sk_buff *skb, struct genl_info *info) { struct ovs_header *ovs_header = info->userhdr; struct ovs_header *ovs_reply_header; struct nlattr **a = info->attrs; struct dp_meter *old_meter; struct sk_buff *reply; struct datapath *dp; u32 meter_id; int err; if (!a[OVS_METER_ATTR_ID]) return -EINVAL; reply = ovs_meter_cmd_reply_start(info, OVS_METER_CMD_DEL, &ovs_reply_header); if (IS_ERR(reply)) return PTR_ERR(reply); ovs_lock(); dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex); if (!dp) { err = -ENODEV; goto exit_unlock; } meter_id = nla_get_u32(a[OVS_METER_ATTR_ID]); old_meter = lookup_meter(&dp->meter_tbl, meter_id); if (old_meter) { spin_lock_bh(&old_meter->lock); err = ovs_meter_cmd_reply_stats(reply, meter_id, old_meter); WARN_ON(err); spin_unlock_bh(&old_meter->lock); err = detach_meter(&dp->meter_tbl, old_meter); if (err) goto exit_unlock; } ovs_unlock(); ovs_meter_free(old_meter); genlmsg_end(reply, ovs_reply_header); return genlmsg_reply(reply, info); exit_unlock: ovs_unlock(); nlmsg_free(reply); return err; } /* Meter action execution. * * Return true 'meter_id' drop band is triggered. The 'skb' should be * dropped by the caller'. */ bool ovs_meter_execute(struct datapath *dp, struct sk_buff *skb, struct sw_flow_key *key, u32 meter_id) { long long int now_ms = div_u64(ktime_get_ns(), 1000 * 1000); long long int long_delta_ms; struct dp_meter_band *band; struct dp_meter *meter; int i, band_exceeded_max = -1; u32 band_exceeded_rate = 0; u32 delta_ms; u32 cost; meter = lookup_meter(&dp->meter_tbl, meter_id); /* Do not drop the packet when there is no meter. */ if (!meter) return false; /* Lock the meter while using it. */ spin_lock(&meter->lock); long_delta_ms = (now_ms - meter->used); /* ms */ if (long_delta_ms < 0) { /* This condition means that we have several threads fighting * for a meter lock, and the one who received the packets a * bit later wins. Assuming that all racing threads received * packets at the same time to avoid overflow. */ long_delta_ms = 0; } /* Make sure delta_ms will not be too large, so that bucket will not * wrap around below. */ delta_ms = (long_delta_ms > (long long int)meter->max_delta_t) ? meter->max_delta_t : (u32)long_delta_ms; /* Update meter statistics. */ meter->used = now_ms; meter->stats.n_packets += 1; meter->stats.n_bytes += skb->len; /* Bucket rate is either in kilobits per second, or in packets per * second. We maintain the bucket in the units of either bits or * 1/1000th of a packet, correspondingly. * Then, when rate is multiplied with milliseconds, we get the * bucket units: * msec * kbps = bits, and * msec * packets/sec = 1/1000 packets. * * 'cost' is the number of bucket units in this packet. */ cost = (meter->kbps) ? skb->len * 8 : 1000; /* Update all bands and find the one hit with the highest rate. */ for (i = 0; i < meter->n_bands; ++i) { long long int max_bucket_size; band = &meter->bands[i]; max_bucket_size = band->burst_size * 1000LL; band->bucket += delta_ms * band->rate; if (band->bucket > max_bucket_size) band->bucket = max_bucket_size; if (band->bucket >= cost) { band->bucket -= cost; } else if (band->rate > band_exceeded_rate) { band_exceeded_rate = band->rate; band_exceeded_max = i; } } if (band_exceeded_max >= 0) { /* Update band statistics. */ band = &meter->bands[band_exceeded_max]; band->stats.n_packets += 1; band->stats.n_bytes += skb->len; /* Drop band triggered, let the caller drop the 'skb'. */ if (band->type == OVS_METER_BAND_TYPE_DROP) { spin_unlock(&meter->lock); return true; } } spin_unlock(&meter->lock); return false; } static const struct genl_small_ops dp_meter_genl_ops[] = { { .cmd = OVS_METER_CMD_FEATURES, .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP, .flags = 0, /* OK for unprivileged users. */ .doit = ovs_meter_cmd_features }, { .cmd = OVS_METER_CMD_SET, .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP, .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN * privilege. */ .doit = ovs_meter_cmd_set, }, { .cmd = OVS_METER_CMD_GET, .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP, .flags = 0, /* OK for unprivileged users. */ .doit = ovs_meter_cmd_get, }, { .cmd = OVS_METER_CMD_DEL, .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP, .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN * privilege. */ .doit = ovs_meter_cmd_del }, }; static const struct genl_multicast_group ovs_meter_multicast_group = { .name = OVS_METER_MCGROUP, }; struct genl_family dp_meter_genl_family __ro_after_init = { .hdrsize = sizeof(struct ovs_header), .name = OVS_METER_FAMILY, .version = OVS_METER_VERSION, .maxattr = OVS_METER_ATTR_MAX, .policy = meter_policy, .netnsok = true, .parallel_ops = true, .small_ops = dp_meter_genl_ops, .n_small_ops = ARRAY_SIZE(dp_meter_genl_ops), .mcgrps = &ovs_meter_multicast_group, .n_mcgrps = 1, .module = THIS_MODULE, }; int ovs_meters_init(struct datapath *dp) { struct dp_meter_table *tbl = &dp->meter_tbl; struct dp_meter_instance *ti; unsigned long free_mem_bytes; ti = dp_meter_instance_alloc(DP_METER_ARRAY_SIZE_MIN); if (!ti) return -ENOMEM; /* Allow meters in a datapath to use ~3.12% of physical memory. */ free_mem_bytes = nr_free_buffer_pages() * (PAGE_SIZE >> 5); tbl->max_meters_allowed = min(free_mem_bytes / sizeof(struct dp_meter), DP_METER_NUM_MAX); if (!tbl->max_meters_allowed) goto out_err; rcu_assign_pointer(tbl->ti, ti); tbl->count = 0; return 0; out_err: dp_meter_instance_free(ti); return -ENOMEM; } void ovs_meters_exit(struct datapath *dp) { struct dp_meter_table *tbl = &dp->meter_tbl; struct dp_meter_instance *ti = rcu_dereference_raw(tbl->ti); int i; for (i = 0; i < ti->n_meters; i++) ovs_meter_free(rcu_dereference_raw(ti->dp_meters[i])); dp_meter_instance_free(ti); }
|
__label__pos
| 0.999468 |
The Algorithms logo
The Algorithms
AboutDonate
Check Anagrams
A
I
M
T
s
A
"""
wiki: https://en.wikipedia.org/wiki/Anagram
"""
from collections import defaultdict
from typing import DefaultDict
def check_anagrams(first_str: str, second_str: str) -> bool:
"""
Two strings are anagrams if they are made up of the same letters but are
arranged differently (ignoring the case).
>>> check_anagrams('Silent', 'Listen')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_anagrams('There', 'Their')
False
"""
first_str = first_str.lower().strip()
second_str = second_str.lower().strip()
# Remove whitespace
first_str = first_str.replace(" ", "")
second_str = second_str.replace(" ", "")
# Strings of different lengths are not anagrams
if len(first_str) != len(second_str):
return False
# Default values for count should be 0
count: DefaultDict[str, int] = defaultdict(int)
# For each character in input strings,
# increment count in the corresponding
for i in range(len(first_str)):
count[first_str[i]] += 1
count[second_str[i]] -= 1
for _count in count.values():
if _count != 0:
return False
return True
if __name__ == "__main__":
from doctest import testmod
testmod()
input_A = input("Enter the first string ").strip()
input_B = input("Enter the second string ").strip()
status = check_anagrams(input_A, input_B)
print(f"{input_A} and {input_B} are {'' if status else 'not '}anagrams.")
|
__label__pos
| 0.978611 |
Untitled
[email protected] avatar
unknown
plain_text
7 months ago
5.0 kB
3
Indexable
Never
using System;
using System.Collections;
namespace zadanie04_szuplewska
{
/* Napisz implementację listy typu array list (lista tablic) w wybranym przez siebie obiektowym języku programowania.
Implementacja ma być rekurencyjna z maksymalną hermetyzacją. */
public class ArrayListRek
{
private ArrayList arrayList;
public ArrayListRek()
{
arrayList = new ArrayList();
}
public void Dodawanie(object item)
{
DodawanieRek(arrayList, item);
}
public object Get(int indeks)
{
return GetRek(arrayList, indeks);
}
public void Set(int indeks, object wartosc)
{
SetRek(arrayList, indeks, wartosc);
}
public void Usuwanie(int indeks)
{
UsuwanieRek(arrayList, indeks);
}
public int LicznikRek()
{
return LicznikRek(arrayList);
}
public void Miejsca()
{
Miejsca_Rek(arrayList);
}
private int LicznikRek(ArrayList list)
{
int licznik = 0;
foreach (var item in list)
{
if (item is ArrayList)
{
licznik += LicznikRek((ArrayList)item);
}
else
{
licznik++;
}
}
return licznik;
}
private void DodawanieRek(ArrayList list, object item)
{
if (LicznikRek(list) > 0 && list[list.Count - 1] is ArrayList)
{
DodawanieRek((ArrayList)list[list.Count - 1], item);
}
else
{
list.Add(item);
}
}
private object GetRek(ArrayList list, int indeks2)
{
foreach (var item in list)
{
if (item is ArrayList)
{
var wynik = GetRek((ArrayList)item, indeks2);
if (wynik != null)
{
return wynik;
}
}
else
{
if (indeks2 == 0)
{
return item;
}
indeks2--;
}
}
return null;
}
private void SetRek(ArrayList list, int indeks2, object wartosc)
{
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
if (item is ArrayList)
{
SetRek((ArrayList)item, indeks2, wartosc);
}
else
{
if (indeks2 == 0)
{
list[i] = wartosc;
return;
}
indeks2--;
}
}
}
private void UsuwanieRek(ArrayList list, int indeks2)
{
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
if (item is ArrayList)
{
UsuwanieRek((ArrayList)item, indeks2);
}
else
{
if (indeks2 == 0)
{
list.RemoveAt(i);
return;
}
indeks2--;
}
}
}
private void Miejsca_Rek(ArrayList list)
{
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
if (item is ArrayList)
{
Miejsca_Rek((ArrayList)item);
}
else
{
Console.WriteLine($"Indeks {i}: {item}");
}
}
}
}
class Program
{
static void Main()
{
ArrayListRek arrayListRek = new ArrayListRek();
//dodawanie elementów
arrayListRek.Dodawanie(87);
arrayListRek.Dodawanie("Hello");
arrayListRek.Dodawanie(2.96);
//wyświetlanie zawartości
Console.WriteLine($"Licznik: {arrayListRek.LicznikRek()}");
arrayListRek.Miejsca();
//zmiana wartości
arrayListRek.Set(1, "World");
//usuwanie elementu
arrayListRek.Usuwanie(0);
//wyświetlanie zmienionej zawartości
Console.WriteLine("\nPo zmianach:");
Console.WriteLine($"Licznik: {arrayListRek.LicznikRek()}");
arrayListRek.Miejsca();
Console.ReadKey();
}
}
}
Leave a Comment
|
__label__pos
| 0.999847 |
Ethereum PHP
PHP interface to Ethereum JSON-RPC API.
EthS.php
Go to the documentation of this file.
1 <?php
2
3 namespace Ethereum\DataType;
4
6
7
13 class EthS extends EthBytes
14 {
22 public function validate($val, array $params)
23 {
24 $return = null;
25 // Decode
26 if ($this->hasHexPrefix($val)) {
27 // Hex encoded string.
28 $return = $this->hexToStr($val);
29 }
30 else {
31 $return = $val;
32 }
33
34 // Validate.
35 if (is_string((string)$return) && $this->checkUtf8($return)) {
36 return $return;
37 }
38 else {
39 throw new \InvalidArgumentException('Can not decode value: ' . $val);
40 }
41 }
42
43
49 public static function cretateFromRLP($hexVal)
50 {
51 $rlpItem = Rlp::decode($hexVal);
52 return new EthS(self::ensureHexPrefix($rlpItem[0]->get()));
53 }
54
61 public function rlpVal()
62 {
63 // @todo ???
64 return Rlp::encode($this->strToHex($this->value));
65 }
66
70 public function hexVal()
71 {
72 return $this->ensureHexPrefix($this->strToHex($this->value));
73 }
74
78 public function encodedHexVal()
79 {
80 return $this->rlpVal();
81 }
82
86 public function val()
87 {
88 return $this->value;
89 }
90
91
102 private function checkUtf8($str)
103 {
104 if (preg_match('%^(?:
105 [\x09\x0A\x0D\x20-\x7E] # ASCII
106 | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
107 | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
108 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
109 | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
110 | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
111 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
112 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
113 )*$%xs', $str)) {
114 return true;
115 }
116 return false;
117 }
118
128 public static function strToHex($string)
129 {
130 $hex = unpack('H*', $string);
131 return array_shift($hex);
132 }
133
147 public static function hexToStr($string)
148 {
149 return pack('H*', self::removeHexPrefix($string));
150 }
151
152 }
static cretateFromRLP($hexVal)
Definition: EthS.php:49
static hexToStr($string)
Definition: EthS.php:147
static strToHex($string)
Definition: EthS.php:128
validate($val, array $params)
Definition: EthS.php:22
static decode(string $hexVal)
Definition: Rlp.php:100
static encode(string $val)
Definition: Rlp.php:43
|
__label__pos
| 0.891977 |
Follow
How to run SQL commands on a Translation Memory or a Termbase
This ensures that the SQL command you have written follows the "rules" of SQL: that the commands are spelled correctly, and that things are written in the right order. However, it cannot ensure that the command you have written will do exactly what you meant it to.
Déjà Vu X3 allows you to use SQL commands to modify Translation Memories and Termbases. By using SQL commands you can make direct changes to the underlying structure of the database. This means that you can make almost any conceivable changes to the information contained in the database. Using SQL commands to modify the databases also allows you to make changes to many entries in the databases at once, thus saving you very much time, compared to making the changes by hand.
Warning: by modifying the underlying structure of a Déjà Vu database directly, it is possible to make changes that render a database unusable in Déjà Vu. For this reason, we strongly recommend that you make a backup of any database you are going to edit before doing anything else; this way, you can restore the backup if you make any mistakes.
You must also remember to repair a Translation Memory after you finish editing it, so that the index files will be updated to reflect your changes, otherwise the Translation Memory may not work correctly in Déjà Vu.
You can run SQL commands on a Translation Memory or a Termbase by opening the database in Déjà Vu X3, and then using the Execute SQL dialog.
Opening the Execute SQL dialog
First, open the database that you wish to run SQL commands on. Then, open the Execute SQL dialog:
1. Access the Home section of the ribbon, and then click on the button Execute SQL.
2. The Execute SQL dialog appears:
The Execute SQL dialog
The Execute SQL dialog has several components:
• The SQL Statement textbox. This is where you type the commands that will be executed.
• The Available Fields combo box. This will show a list of fields that exist in the database; this saves you from having to type the names of the fields, which may be difficult to remember in some cases.
• The Statement Name textbox. You can use this to load SQL commands that you have saved beforehand, as well as save an SQL command you have already typed in the SQL Statement textbox.
Typing the SQL commands
You can type an SQL command into the SQL Statement textbox, or copy a command from somewhere else and paste it into the textbox. While you are typing the command, you can use the Available Fields combo box to help you:
By clicking on the combo box, you will see a list of the names of the fields that exist in the current database. If you click on one of those names, Déjà Vu X3 will insert the name of the field into the SQL Statement textbox, thus saving you from having to type the name.
When you have finished typing the command you want to run, you should ask Déjà Vu X3 to validate it. Validating means that Déjà Vu X3 will check the syntax of the command you have typed to make sure that it is validnote. To validate the command you have written, click on Validate. Déjà Vu X3 will check the commands you have written and let you know if they are correct:
Or incorrect:
When you are ready to run the command, click Execute.
Saving an SQL command
Déjà Vu X3 allows you to save the command you have typed into the SQL Statement textbox, so that you can easily use the same command again later. This can save you a lot of time if you use a few commands very often.
To save the command:
1. Type the name you want to give the saved command in the Statement Name textbox:
2. Click Save.
Loading a saved SQL command
To load a saved SQL command:
1. Click on the downward pointing arrow in the Statement Name textbox:
2. Click on the name of the saved SQL command that you want to run:
3. The saved command will be inserted in the SQL Statement textbox. You can modify it if necessary, or just run it by clicking Execute:
Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request
Comments
Powered by Zendesk
|
__label__pos
| 0.975546 |
comment exporter un vecteur depuis illustrator ?
Comment exporter un vecteur d’Illustrator vers Photoshop ?
Il existe plusieurs façons d’exporter des graphiques vectoriels d’Illustrator vers Photoshop. Une façon consiste à utiliser l’option de menu “Exporter sous” dans Illustrator, puis à sélectionner “Photoshop EPS”. Une autre méthode consiste à utiliser l’option de menu “Exporter sous” dans Photoshop, puis à sélectionner “PDF.
Dans quel format enregistrez-vous un fichier vectoriel dans Illustrator ?
J’enregistre mes fichiers vectoriels dans Adobe Illustrator au format PDF.
Comment enregistrer un fichier vectoriel au format PNG dans Illustrator ?
Pour enregistrer un fichier vectoriel au format PNG dans Illustrator, ouvrez d’abord le fichier vectoriel dans Illustrator, puis cliquez sur le bouton Enregistrer sous.
Comment exporter un fichier vectoriel dans Illustrator ?
Il existe plusieurs façons d’exporter des fichiers vectoriels dans Illustrator. Vous pouvez utiliser la commande Exporter sous… pour créer un fichier PDF ou EPS, ou vous pouvez utiliser la commande Enregistrer sous… pour enregistrer le fichier au format JPEG ou PNG.
Pouvez-vous convertir Illustrator en Photoshop ?
Illustrator est un éditeur de graphiques vectoriels et Photoshop est un programme de retouche photo.
Comment exporter un vecteur d’Illustrator vers After Effects ?
Il existe plusieurs façons d’exporter des images vectorielles d’Illustrator vers After Effects. Une façon consiste à utiliser la commande Exporter sous…. Une autre méthode consiste à utiliser la commande Enregistrer sous….
Comment transformer un fichier en vecteur ?
Il existe plusieurs façons de transformer un fichier en vecteur :
-Utilisez la fonction Vecteur dans Excel pour créer des vecteurs à partir de données.
Utilisez la fonction Plage pour sélectionner une plage de données et la convertir en vecteurs.
Utilisez la fonction ToVec dans MATLAB pour créer des vecteurs à partir de données.
Un fichier EPS est-il un fichier vectoriel ?
Les fichiers EPS ne sont pas des vecteurs.
Un SVG est-il un fichier vectoriel ?
Oui, SVG est un fichier vectoriel.
Est-ce qu’un PNG est un fichier vectoriel ?
Les PNG ne sont pas des vecteurs, mais ils peuvent être utilisés pour créer des fichiers vectoriels.
Comment convertir un JPEG en image vectorielle ?
Il existe plusieurs façons de convertir des JPEG en vecteurs. Le moyen le plus courant est d’utiliser le logiciel gratuit GIMP.
Comment transformer un PDF en fichier vectoriel ?
Il existe plusieurs façons de transformer des PDF en fichiers vectoriels. Le moyen le plus courant consiste à utiliser Adobe Acrobat Reader. Vous pouvez trouver le programme Acrobat Reader sur le site Web d’Adobe. Après avoir installé Acrobat Reader, ouvrez le menu « Fichier » et sélectionnez « Ouvrir avec… ». Sélectionnez ensuite « PDF » dans la liste et cliquez sur le bouton « Ouvrir ».
Un fichier Illustrator est-il un fichier vectoriel ?
Non, un fichier Illustrator est un fichier vectoriel.
Un fichier PDF est-il un fichier vectoriel ?
Oui, un fichier PDF est un fichier vectoriel.
JPEG est-il un vecteur ou un raster ?
JPEG est un format d’image vectorielle.
À propos de admin
Voir aussi
Comment éteindre un ordinateur portable HP
Les ordinateurs portables HP sont l’un des modèles les plus populaires, ce qui en fait …
Laisser un commentaire
Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *
x
|
__label__pos
| 0.986498 |
Exceljet
Quick, clean, and to the point
Count cells that contain either x or y
Excel formula: Count cells that contain either x or y
Generic formula
=SUMPRODUCT(--((ISNUMBER(FIND("abc",rng)) + ISNUMBER(FIND("def",rng)))>0))
Summary
To count cells that contain either x or y, you can use a formula based on the SUMPRODUCT function. In the example shown, the formula in cell F5 is:
=SUMPRODUCT(--((ISNUMBER(FIND("abc",B5:B11))+ISNUMBER(FIND("def",B5:B11)))>0))
This is the single cell formula solution, explained below. It is also possible to use a simpler formula based on a helper column, also explained below.
Explanation
When you count cells with "OR logic", you need to be careful not to double count. For example, if you are counting cells that contain "abc" or "def", you can't just add together two COUNTIF functions, because you may double count cells that contain both "abc" and "def".
Single cell solution
For a single formula, you can use SUMPRODUCT with ISNUMBER + FIND. The formula in F5 is:
=SUMPRODUCT(--((ISNUMBER(FIND("abc",B5:B11)) + ISNUMBER(FIND("def",B5:B11)))>0))
This formula is based on the formula explained here that locates text inside of a cell:
ISNUMBER(FIND("abc",B5:B11)
When given a range of cells, this snippet will return an array of TRUE/FALSE values, one value for each cell the range. Since we are using this twice (once for "abc" and once for "def"), we'll get two arrays.
Next, we add these arrays together (with +), which creates a new single array of numbers. Each number in this array is the result of adding the TRUE and FALSE values in the original two arrays together. In the example shown, the resulting array looks like this:
{2;0;2;0;1;0;2}
We need to add these numbers up, but we don't want to double count. So we need to make sure any value greater than zero is just counted once. To do that, we force all values to TRUE or FALSE with ">0", then force to 1/0 with the double-negative (--).
Finally, SUMPRODUCT returns the sum of all values in the array.
Helper column solution
With a helper column to check each cell individually, the problem is less complex. We can use COUNTIF with two values (provided as an "array constant"). The formula in C5 is:
=--(SUM(COUNTIF(B5,{"*abc*","*def*"}))>0)
Check if cell contains either x or y with COUNTIF
COUNTIF will return an array that contains two items: a count for "abc" and a count for "def". To prevent double counting, we add the items up and then force the result to TRUE/FALSE with ">0". Finally, we convert the TRUE/FALSE values to 1's and 0's with a double negative (--).
The final result is either 1 or 0 for each cell. To get a total for all cells in the range, simply sum the helper column.
Author
Dave Bruns
Excel Formula Training
Formulas are the key to getting things done in Excel. In this accelerated training, you'll learn how to use formulas to manipulate text, work with dates and times, lookup values with VLOOKUP and INDEX & MATCH, count and sum with criteria, dynamically rank values, and create dynamic ranges. You'll also learn how to troubleshoot, trace errors, and fix problems. Instant access. See details here.
Download 200+ Excel Shortcuts
Get over 200 Excel shortcuts for Windows and Mac in one handy PDF.
|
__label__pos
| 0.974686 |
.. SPDX-License-Identifier: BSD-3-Clause Copyright 2016 The DPDK contributors DPDK Release 16.07 ================== New Features ------------ * **Removed the mempool cache memory if caching is not being used.** The size of the mempool structure is reduced if the per-lcore cache is disabled. * **Added mempool external cache for non-EAL thread.** Added new functions to create, free or flush a user-owned mempool cache for non-EAL threads. Previously the caching was always disabled on these threads. * **Changed the memory allocation scheme in the mempool library.** * Added the ability to allocate a large mempool in fragmented virtual memory. * Added new APIs to populate a mempool with memory. * Added an API to free a mempool. * Modified the API of the ``rte_mempool_obj_iter()`` function. * Dropped the specific Xen Dom0 code. * Dropped the specific anonymous mempool code in testpmd. * **Added a new driver for Broadcom NetXtreme-C devices.** Added the new bnxt driver for Broadcom NetXtreme-C devices. See the "Network Interface Controller Drivers" document for more details on this new driver. * **Added a new driver for ThunderX nicvf devices.** Added the new thunderx net driver for ThunderX nicvf devices. See the "Network Interface Controller Drivers" document for more details on this new driver. * **Added mailbox interrupt support for ixgbe and igb VFs.** When the physical NIC link comes up or down, the PF driver will send a mailbox message to notify each VF. To handle this link up/down event, support have been added for a mailbox interrupt to receive the message and allow the application to register a callback for it. * **Updated the ixgbe base driver.** The ixgbe base driver was updated with changes including the following: * Added sgmii link for X550. * Added MAC link setup for X550a SFP and SFP+. * Added KR support for X550em_a. * Added new PHY definitions for M88E1500. * Added support for the VLVF to be bypassed when adding/removing a VFTA entry. * Added X550a flow control auto negotiation support. * **Updated the i40e base driver.** Updated the i40e base driver including support for new devices IDs. * **Updated the enic driver.** The enic driver was updated with changes including the following: * Optimized the Tx function. * Added Scattered Rx capability. * Improved packet type identification. * Added MTU update in non Scattered Rx mode and enabled MTU of up to 9208 with UCS Software release 2.2 on 1300 series VICs. * **Updated the mlx5 driver.** The mlx5 driver was updated with changes including the following: * Data path was refactored to bypass Verbs to improve RX and TX performance. * Removed compilation parameters for inline send, ``MLX5_MAX_INLINE``, and added command line parameter instead, ``txq_inline``. * Improved TX scatter gather support: Removed compilation parameter ``MLX5_PMD_SGE_WR_N``. Scatter-gather elements is set to the maximum value the NIC supports. Removed linearization logic, this decreases the memory consumption of the PMD. * Improved jumbo frames support, by dynamically setting RX scatter gather elements according to the MTU and mbuf size, no need for compilation parameter ``MLX5_PMD_SGE_WR_N`` * **Added support for virtio on IBM POWER8.** The ioports are mapped in memory when using Linux UIO. * **Added support for Virtio in containers.** Add a new virtual device, named virtio_user, to support virtio for containers. Known limitations: * Control queue and multi-queue are not supported yet. * Doesn't work with ``--huge-unlink``. * Doesn't work with ``--no-huge``. * Doesn't work when there are more than ``VHOST_MEMORY_MAX_NREGIONS(8)`` hugepages. * Root privilege is required for sorting hugepages by physical address. * Can only be used with the vhost user backend. * **Added vhost-user client mode.** DPDK vhost-user now supports client mode as well as server mode. Client mode is enabled when the ``RTE_VHOST_USER_CLIENT`` flag is set while calling ``rte_vhost_driver_register``. When DPDK vhost-user restarts from an normal or abnormal exit (such as a crash), the client mode allows DPDK to establish the connection again. Note that QEMU version v2.7 or above is required for this feature. DPDK vhost-user will also try to reconnect by default when: * The first connect fails (for example when QEMU is not started yet). * The connection is broken (for example when QEMU restarts). It can be turned off by setting the ``RTE_VHOST_USER_NO_RECONNECT`` flag. * **Added NSH packet recognition in i40e.** * **Added AES-CTR support to AESNI MB PMD.** Now AESNI MB PMD supports 128/192/256-bit counter mode AES encryption and decryption. * **Added AES counter mode support for Intel QuickAssist devices.** Enabled support for the AES CTR algorithm for Intel QuickAssist devices. Provided support for algorithm-chaining operations. * **Added KASUMI SW PMD.** A new Crypto PMD has been added, which provides KASUMI F8 (UEA1) ciphering and KASUMI F9 (UIA1) hashing. * **Added multi-writer support for RTE Hash with Intel TSX.** The following features/modifications have been added to rte_hash library: * Enabled application developers to use an extra flag for ``rte_hash`` creation to specify default behavior (multi-thread safe/unsafe) with the ``rte_hash_add_key`` function. * Changed the Cuckoo Hash Search algorithm to breadth first search for multi-writer routines and split Cuckoo Hash Search and Move operations in order to reduce transactional code region and improve TSX performance. * Added a hash multi-writer test case to the test app. * **Improved IP Pipeline Application.** The following features have been added to the ip_pipeline application: * Configure the MAC address in the routing pipeline and automatic route updates with change in link state. * Enable RSS per network interface through the configuration file. * Streamline the CLI code. * **Added keepalive enhancements.** Added support for reporting of core states other than "dead" to monitoring applications, enabling the support of broader liveness reporting to external processes. * **Added packet capture framework.** * A new library ``librte_pdump`` is added to provide a packet capture API. * A new ``app/pdump`` tool is added to demonstrate capture packets in DPDK. * **Added floating VEB support for i40e PF driver.** A "floating VEB" is a special Virtual Ethernet Bridge (VEB) which does not have an upload port, but instead is used for switching traffic between virtual functions (VFs) on a port. For information on this feature, please see the "I40E Poll Mode Driver" section of the "Network Interface Controller Drivers" document. * **Added support for live migration of a VM with SRIOV VF.** Live migration of a VM with Virtio and VF PMD's using the bonding PMD. Resolved Issues --------------- EAL ~~~ * **igb_uio: Fixed possible mmap failure for Linux >= 4.5.** The mmapping of the iomem range of the PCI device fails for kernels that enabled the ``CONFIG_IO_STRICT_DEVMEM`` option. The error seen by the user is as similar to the following:: EAL: pci_map_resource(): cannot mmap(39, 0x7f1c51800000, 0x100000, 0x0): Invalid argument (0xffffffffffffffff) The ``CONFIG_IO_STRICT_DEVMEM`` kernel option was introduced in Linux v4.5. The issues was resolve by updating ``igb_uio`` to stop reserving PCI memory resources. From the kernel point of view the iomem region looks like idle and mmap works again. This matches the ``uio_pci_generic`` usage. Drivers ~~~~~~~ * **i40e: Fixed vlan stripping from inner header.** Previously, for tunnel packets, such as VXLAN/NVGRE, the vlan tags of the inner header will be stripped without putting vlan info to descriptor. Now this issue is fixed by disabling vlan stripping from inner header. * **i40e: Fixed the type issue of a single VLAN type.** Currently, if a single VLAN header is added in a packet, it's treated as inner VLAN. But generally, a single VLAN header is treated as the outer VLAN header. This issue is fixed by changing corresponding register for single VLAN. * **enic: Fixed several issues when stopping then restarting ports and queues.** Fixed several crashes related to stopping then restarting ports and queues. Fixed possible crash when re-configuring the number of Rx queue descriptors. * **enic: Fixed Rx data mis-alignment if mbuf data offset modified.** Fixed possible Rx corruption when mbufs were returned to a pool with data offset other than RTE_PKTMBUF_HEADROOM. * **enic: Fixed Tx IP/UDP/TCP checksum offload and VLAN insertion.** * **enic: Fixed Rx error and missed counters.** Libraries ~~~~~~~~~ * **mbuf: Fixed refcnt update when detaching.** Fix the ``rte_pktmbuf_detach()`` function to decrement the direct mbuf's reference counter. The previous behavior was not to affect the reference counter. This lead to a memory leak of the direct mbuf. API Changes ----------- * The following counters are removed from the ``rte_eth_stats`` structure: * ``ibadcrc`` * ``ibadlen`` * ``imcasts`` * ``fdirmatch`` * ``fdirmiss`` * ``tx_pause_xon`` * ``rx_pause_xon`` * ``tx_pause_xoff`` * ``rx_pause_xoff`` * The extended statistics are fetched by ids with ``rte_eth_xstats_get`` after a lookup by name ``rte_eth_xstats_get_names``. * The function ``rte_eth_dev_info_get`` fill the new fields ``nb_rx_queues`` and ``nb_tx_queues`` in the structure ``rte_eth_dev_info``. * The vhost function ``rte_vring_available_entries`` is renamed to ``rte_vhost_avail_entries``. * All existing vhost APIs and callbacks with ``virtio_net`` struct pointer as the parameter have been changed due to the ABI refactoring described below. It is replaced by ``int vid``. * The function ``rte_vhost_enqueue_burst`` no longer supports concurrent enqueuing packets to the same queue. * The function ``rte_eth_dev_set_mtu`` adds a new return value ``-EBUSY``, which indicates the operation is forbidden because the port is running. * The script ``dpdk_nic_bind.py`` is renamed to ``dpdk-devbind.py``. And the script ``setup.sh`` is renamed to ``dpdk-setup.sh``. ABI Changes ----------- * The ``rte_port_source_params`` structure has new fields to support PCAP files. It was already in release 16.04 with ``RTE_NEXT_ABI`` flag. * The ``rte_eth_dev_info`` structure has new fields ``nb_rx_queues`` and ``nb_tx_queues`` to support the number of queues configured by software. * A Vhost ABI refactoring has been made: the ``virtio_net`` structure is no longer exported directly to the application. Instead, a handle, ``vid``, has been used to represent this structure internally. Shared Library Versions ----------------------- The libraries prepended with a plus sign were incremented in this version. .. code-block:: diff + libethdev.so.4 librte_acl.so.2 librte_cfgfile.so.2 librte_cmdline.so.2 librte_cryptodev.so.1 librte_distributor.so.1 librte_eal.so.2 librte_hash.so.2 librte_ip_frag.so.1 librte_ivshmem.so.1 librte_jobstats.so.1 librte_kni.so.2 librte_kvargs.so.1 librte_lpm.so.2 librte_mbuf.so.2 + librte_mempool.so.2 librte_meter.so.1 librte_pdump.so.1 librte_pipeline.so.3 librte_pmd_bond.so.1 librte_pmd_ring.so.2 + librte_port.so.3 librte_power.so.1 librte_reorder.so.1 librte_ring.so.1 librte_sched.so.1 librte_table.so.2 librte_timer.so.1 + librte_vhost.so.3 Tested Platforms ---------------- #. SuperMicro 1U - BIOS: 1.0c - Processor: Intel(R) Atom(TM) CPU C2758 @ 2.40GHz #. SuperMicro 1U - BIOS: 1.0a - Processor: Intel(R) Xeon(R) CPU D-1540 @ 2.00GHz - Onboard NIC: Intel(R) X552/X557-AT (2x10G) - Firmware-version: 0x800001cf - Device ID (PF/VF): 8086:15ad /8086:15a8 - kernel driver version: 4.2.5 (ixgbe) #. SuperMicro 2U - BIOS: 1.0a - Processor: Intel(R) Xeon(R) CPU E5-4667 v3 @ 2.00GHz #. Intel(R) Server board S2600GZ - BIOS: SE5C600.86B.02.02.0002.122320131210 - Processor: Intel(R) Xeon(R) CPU E5-2680 v2 @ 2.80GHz #. Intel(R) Server board W2600CR - BIOS: SE5C600.86B.02.01.0002.082220131453 - Processor: Intel(R) Xeon(R) CPU E5-2680 v2 @ 2.80GHz #. Intel(R) Server board S2600CWT - BIOS: SE5C610.86B.01.01.0009.060120151350 - Processor: Intel(R) Xeon(R) CPU E5-2699 v3 @ 2.30GHz #. Intel(R) Server board S2600WTT - BIOS: SE5C610.86B.01.01.0005.101720141054 - Processor: Intel(R) Xeon(R) CPU E5-2699 v3 @ 2.30GHz #. Intel(R) Server board S2600WTT - BIOS: SE5C610.86B.11.01.0044.090120151156 - Processor: Intel(R) Xeon(R) CPU E5-2695 v4 @ 2.10GHz Tested NICs ----------- #. Intel(R) Ethernet Controller X540-AT2 - Firmware version: 0x80000389 - Device id (pf): 8086:1528 - Driver version: 3.23.2 (ixgbe) #. Intel(R) 82599ES 10 Gigabit Ethernet Controller - Firmware version: 0x61bf0001 - Device id (pf/vf): 8086:10fb / 8086:10ed - Driver version: 4.0.1-k (ixgbe) #. Intel(R) Corporation Ethernet Connection X552/X557-AT 10GBASE-T - Firmware version: 0x800001cf - Device id (pf/vf): 8086:15ad / 8086:15a8 - Driver version: 4.2.5 (ixgbe) #. Intel(R) Ethernet Converged Network Adapter X710-DA4 (4x10G) - Firmware version: 5.04 - Device id (pf/vf): 8086:1572 / 8086:154c - Driver version: 1.4.26 (i40e) #. Intel(R) Ethernet Converged Network Adapter X710-DA2 (2x10G) - Firmware version: 5.04 - Device id (pf/vf): 8086:1572 / 8086:154c - Driver version: 1.4.25 (i40e) #. Intel(R) Ethernet Converged Network Adapter XL710-QDA1 (1x40G) - Firmware version: 5.04 - Device id (pf/vf): 8086:1584 / 8086:154c - Driver version: 1.4.25 (i40e) #. Intel(R) Ethernet Converged Network Adapter XL710-QDA2 (2X40G) - Firmware version: 5.04 - Device id (pf/vf): 8086:1583 / 8086:154c - Driver version: 1.4.25 (i40e) #. Intel(R) Corporation I350 Gigabit Network Connection - Firmware version: 1.48, 0x800006e7 - Device id (pf/vf): 8086:1521 / 8086:1520 - Driver version: 5.2.13-k (igb) #. Intel(R) Ethernet Multi-host Controller FM10000 - Firmware version: N/A - Device id (pf/vf): 8086:15d0 - Driver version: 0.17.0.9 (fm10k) Tested OSes ----------- - CentOS 7.0 - Fedora 23 - Fedora 24 - FreeBSD 10.3 - Red Hat Enterprise Linux 7.2 - SUSE Enterprise Linux 12 - Ubuntu 15.10 - Ubuntu 16.04 LTS - Wind River Linux 8
|
__label__pos
| 0.878347 |
Memory ALIVE:ness
At first, when we got cell phones, we remarked at how we didn’t have to remember phone numbers anymore. Now we don’t have to remember faces. Now we don’t even have to remember the things that happen to us. Our Timelines do that for us, our instagrams and videos and Soundclouds do that for us—memories recorded as soon as the moment falls, as the moment falls, so instantaneously, that sometimes we are hardly there, hardly present. Recorded in a sound bite that makes it “universal” and accessible, already an instance of an arm of humanity, recorded with the tools that take care of memory for us. Categorize it. Is it a “key event”? A moment of sadness? An instance of success? Please, choose a label lest we find no place for it in our collective electronic file cabinet.
I do not even have to remember the date of my birth anymore. It is already on my Facebook Timeline, and a hundred people remember it for me because they are told to wish me a happy birthday. They comply. And though I still can remember my own birthday without checking, I hardly need to, and, after all, is my birthday really more important than yours? Weren’t a thousand people dying the day I was born and another thousand born as well? Are my key memories really more important than yours, or even all that different from yours? Why remember anything that happened to ME and not to YOU? Why remember anything at all?
Though I hyperbolize there is a kernel of truth that has taken me to another place. Memories, when recorded, become static. Writers experience this when we write memoir—the memory becomes static in the version that gets written, while prior to the writing the memory remains an amorphous and dynamic cesspool of influence and input. Once written, it’s taken care of, allows for putting on the shelf, allows for letting go. Writing can be therapeutic in this way, though sometimes, deceptive if our memory stagnates with the stamp of writing.
Now by our instantaneous recording and capturing of memories in an Instagram or summarizing character-limited Tweet, we fix our memories and let them go much sooner. Not to say we remember nothing, but is it possible that our modern circumstance actually is changing the functioning of our brains so that our brains learn to capture and retain information differently?
I know that our new forms of communication are changing my memory and brain functioning, much as waitressing did—though it may seem to be a petty comparison—it required a different length of memory capture, retain and recall than ordinary social interaction. I certainly shouldn’t remember what every table the entire night through wants for the entire duration of the night—that would become confusing—rather I should remember a table’s wishes just long enough to recall in its proper time.
Now we find there is so much more information to absorb and remember that it seems our brains have more work to do to choose WHAT to retain. “Naturally,” we have prioritized our own memories over the things that happened to US (collectively, e.g. as a people, as a nation); certainly we’ve prioritized our memories over memories that happened to others (read: not US), but now, in this post binary stage, it is becoming harder to decide who and what to remember and our experiences are becoming much more mixed into the memory soup. Was that his status or mine? Her tweet or mine? RT RT HER TWEET OR MINE? Does it matter at all? I am on a train from Malmö to Stockholm, but I could be just as easily on a train from Detroit to Chicago. No one really cares—both have been done countless times before by some member of the human race. And perhaps—there is progress in this theoretical soup of experience.
Perhaps what I am saying sounds callous, automaton, even frightening, but we have a choice about how to perceive our digital age and how to utilize our tools. Up until now we have been preoccupied with measurements of time and size and distance. We are preoccupied with modernist ideas like development and progress. “Things get better with time.” Work is improved and made more efficient with development over time. The answer could be in downsizing or upgrading. We grapple with questions like, how is society adapting to the way that our technological tools are growing smaller? Will they live as a chip under our skin? Some have lamented the increasingly shortened length of communication from letter to fax to email to tweet. (In any case, I still write long emails like letters; many people do). But this change of message format is only lamentable when we think of history as linear, of progress as quantitative. Some have suggested that we will catch our memory recall growing so short and our tools of memory growing so small that finally we will decide to “back track”—in any number of countless ways; that more people will be buying books instead of Kindls, that we’ll hunger for the phone with a long cord attached to the wall. Many have suggested that at some point we will rebel and decide that we need to back to the days of giant mobile phones, for example, or that we’ll simply buy larger cars or want for large pieces of information. We speak of our distances as being shorter (because we can fly a plane there in an hour, or perhaps because we can skype with our friends so easily, watch them live.) We speak of time as being minimized because we are constant receivers of messages from far away lands, and we can reply in the blink of an eye.
I can’t help but think that, while these questions of measurement may be quite fascinating, they are not quite getting us to the transformative place. They may have to do with “progress” but do they have to do with “transformation,” with “transgression”?
It would seem that size, distance, time, all these forms of measurement are merely relative questions. If we consider our own size, we realize quite easily that there are billions of things—literally billions of things—smaller than us. Perhaps there are even “worlds” living in an atom, worlds we cannot see. Certainly as well we already know that we are on one planet in a galaxy of millions of stars. We are one galaxy in a million galaxies. There are billions of things larger than us. Are we right in the “middle” or are we merely somewhere in an infinite continuum? Scientists speak of “parallel” universes or other universes. In this meta-space, certainly the size of a cellular phone versus a wall phone is irrelevant. Surely the length of a human life, in relation to the life of the universe, is irrelevant. Surely the distance from my house to yours, is irrelevant when we consider the distance from the sun to a sun in a far distant galaxy. This is not to say there is no real distance, but rather to say, we are located somewhere on a great infinite span of what we think of as “distance” or “time”, but measurement is surely only a relative perspective from our limited eye. Is it a great indicator? What if the decreasing size of a mobile phone, of a computer, of a thought, of a memory, is merely a convenient kind of illusion? When we think of their size relative to the size of the universe, are they any size at all? Shall we grow nostalgic based on size?
And perhaps rather than thinking that we will either grow smaller, or grow larger, we could imagine that we will jump into something else entirely. Telepathy. Human interaction. Spirituality. Loss of ego.
What if we think not of the size of our writings—how long or short they are—or the ownership of our memories—who they belong or don’t belong to—but realize their collectivity? Not that we will forget who we love or the day our child was born, but … All those babies online, all those dates and those and pictures and numbers … If we take it to hyperbole, the sense that we do have a collective memory could be a strong lesson for our ego // we are ONE human, we are one human experience, we are the cyborg and finally we are realizing our true insignificance as individuals (our true smallness). And through this limitless smallness… the possibility for significance as living life?
Listening to a podcast about Story Corps brings to mind on the one hand how special, unique and sacred our memories are, how each voice is different and worth hearing, and yet these voices are also touching because they are “universal,” recognizable.
In this way we really walk this balance between experiencing a collective memory and experiencing an individual one. Once all these unique voices are compiled in the Library of Congress, who’s to say my memory is not that of an immigrant, a slave, a mother, a factory worker, a business man, a politician, a train engineer.
“Every voice matters”—Story Corps says—and yet every voice doesn’t matter, not in the history of the universe. And yet again, every voice matters. And yet mine is like yours. Practically speaking the same as yours. And yet “different,” if we inspect the minutia, what lies in the details. This is the paradox that life is constantly revealing to us.
We’ve spent years fighting appropriation, identifying ownership, obsessed with authenticity of voice, of story, of experience, but if the story EXISTS, if the memory EXISTS, what does it matter to whom it belongs? Our planet, as large as it is, is one of billions of planets. We might as well be one human on one planet. One human memory. One human birth date. One human death.
How can we use this hyperbole to help us find identification with all stories, to let go our ownership, to find aliveness in all lives, to relating to all lives?
16 February 2012
The far snowy field from Malmö to Stockholm
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.734349 |
Don't like ads? PRO users don't see any ads ;-)
Guest
Untitled
By: a guest on May 10th, 2010 | syntax: Objective C | size: 2.53 KB | hits: 653 | expires: Never
download | raw | embed | report abuse | print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. codec = avcodec_find_encoder(CODEC_ID_MSMPEG4V1);
2.
3. if (!codec)
4. {
5. NSLog("Couldn't init codec");
6. abort();
7. }
8.
9. codecContext = avcodec_alloc_context();
10. codecContext->bit_rate = 384000;
11. codecContext->width = FRAME_WIDTH;
12. codecContext->height = FRAME_HEIGHT;
13. codecContext->time_base = (AVRational) {
14. 1,
15. FPS
16. };
17.
18. codecContext->pix_fmt = PIX_FMT_YUV420P;
19.
20. int codec_open_result = avcodec_open(codecContext, codec);
21.
22. if (codec_open_result < 0)
23. {
24. NSLog(@"Couldn't open codec");
25. abort();
26. }
27.
28. /* previously defined
29. #define FRAME_WIDTH 320
30. #define FRAME_HEIGHT 480
31. */
32.
33. uint8_t *rgb_data = buffer + (frameSize * ((*totalCaptured - 1) % BUFFER_FRAME_MAX_COUNT));
34.
35. uint8_t *rgb_src[3] = {
36. rgb_data,
37. NULL,
38. NULL
39. };
40.
41. int rgb_stride[3] = {
42. 4 * FRAME_WIDTH,
43. 0,
44. 0
45. };
46.
47. uint8_t *src[4] = {
48. scaleBuffer,
49. scaleBuffer + FRAME_WIDTH * FRAME_HEIGHT,
50. scaleBuffer + ( FRAME_WIDTH * FRAME_HEIGHT ) + ( FRAME_WIDTH * FRAME_HEIGHT / 4 ),
51. NULL
52. };
53.
54. int stride[4] = {
55. FRAME_WIDTH,
56. FRAME_WIDTH / 2,
57. FRAME_WIDTH / 2,
58. 0
59. };
60.
61. struct SwsContext *sws;
62.
63. sws = sws_getContext(FRAME_WIDTH, // src width
64. FRAME_HEIGHT, // src height
65. PIX_FMT_RGB32, // src pixel format ,
66. FRAME_WIDTH, // dest width
67. FRAME_HEIGHT, // dest height
68. PIX_FMT_YUV420P, // dest pix format
69. SWS_BILINEAR, // FLAGS
70. NULL,
71. NULL,
72. NULL);
73.
74.
75. int sliceHeight = sws_scale(sws,
76. rgb_src,
77. rgb_stride,
78. 0,
79. FRAME_HEIGHT,
80. src,
81. stride);
82.
83. // the "sliceHeight" variable evaluates to 480 in GDB at this point, which seems correct
84.
85. if (sliceHeight <= 0)
86. {
87. NSLog(@"couldn't scale");
88. abort();
89. }
90.
91. sws_freeContext(sws);
92.
93. currentPicture->data[0] = src[0];
94. currentPicture->data[1] = src[1];
95. currentPicture->data[2] = src[2];
96. currentPicture->data[3] = src[3];
97.
98. currentPicture->linesize[0] = stride[0];
99. currentPicture->linesize[1] = stride[1];
100. currentPicture->linesize[2] = stride[2];
101. currentPicture->linesize[3] = stride[3];
102.
103. int out_size = avcodec_encode_video(codecContext, encodeBuffer, frameSize, currentPicture);
104.
105. // the "out_size" variable evaluates to 4 in GDB, which seems incorrect
|
__label__pos
| 0.999965 |
/[pcre]/code/trunk/pcre_exec.c
ViewVC logotype
Contents of /code/trunk/pcre_exec.c
Parent Directory Parent Directory | Revision Log Revision Log
Revision 527 - (show annotations)
Sat May 29 15:50:39 2010 UTC (9 years, 5 months ago) by ph10
File MIME type: text/plain
File size: 184892 byte(s)
Error occurred while calculating annotation data.
Fix oversight for no-recurse version.
1 /*************************************************
2 * Perl-Compatible Regular Expressions *
3 *************************************************/
4
5 /* PCRE is a library of functions to support regular expressions whose syntax
6 and semantics are as close as possible to those of the Perl 5 language.
7
8 Written by Philip Hazel
9 Copyright (c) 1997-2010 University of Cambridge
10
11 -----------------------------------------------------------------------------
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are met:
14
15 * Redistributions of source code must retain the above copyright notice,
16 this list of conditions and the following disclaimer.
17
18 * Redistributions in binary form must reproduce the above copyright
19 notice, this list of conditions and the following disclaimer in the
20 documentation and/or other materials provided with the distribution.
21
22 * Neither the name of the University of Cambridge nor the names of its
23 contributors may be used to endorse or promote products derived from
24 this software without specific prior written permission.
25
26 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 POSSIBILITY OF SUCH DAMAGE.
37 -----------------------------------------------------------------------------
38 */
39
40
41 /* This module contains pcre_exec(), the externally visible function that does
42 pattern matching using an NFA algorithm, trying to mimic Perl as closely as
43 possible. There are also some static supporting functions. */
44
45 #ifdef HAVE_CONFIG_H
46 #include "config.h"
47 #endif
48
49 #define NLBLOCK md /* Block containing newline information */
50 #define PSSTART start_subject /* Field containing processed string start */
51 #define PSEND end_subject /* Field containing processed string end */
52
53 #include "pcre_internal.h"
54
55 /* Undefine some potentially clashing cpp symbols */
56
57 #undef min
58 #undef max
59
60 /* Flag bits for the match() function */
61
62 #define match_condassert 0x01 /* Called to check a condition assertion */
63 #define match_cbegroup 0x02 /* Could-be-empty unlimited repeat group */
64
65 /* Non-error returns from the match() function. Error returns are externally
66 defined PCRE_ERROR_xxx codes, which are all negative. */
67
68 #define MATCH_MATCH 1
69 #define MATCH_NOMATCH 0
70
71 /* Special internal returns from the match() function. Make them sufficiently
72 negative to avoid the external error codes. */
73
74 #define MATCH_ACCEPT (-999)
75 #define MATCH_COMMIT (-998)
76 #define MATCH_PRUNE (-997)
77 #define MATCH_SKIP (-996)
78 #define MATCH_SKIP_ARG (-995)
79 #define MATCH_THEN (-994)
80
81 /* This is a convenience macro for code that occurs many times. */
82
83 #define MRRETURN(ra) \
84 { \
85 md->mark = markptr; \
86 RRETURN(ra); \
87 }
88
89 /* Maximum number of ints of offset to save on the stack for recursive calls.
90 If the offset vector is bigger, malloc is used. This should be a multiple of 3,
91 because the offset vector is always a multiple of 3 long. */
92
93 #define REC_STACK_SAVE_MAX 30
94
95 /* Min and max values for the common repeats; for the maxima, 0 => infinity */
96
97 static const char rep_min[] = { 0, 0, 1, 1, 0, 0 };
98 static const char rep_max[] = { 0, 0, 0, 0, 1, 1 };
99
100
101
102 #ifdef PCRE_DEBUG
103 /*************************************************
104 * Debugging function to print chars *
105 *************************************************/
106
107 /* Print a sequence of chars in printable format, stopping at the end of the
108 subject if the requested.
109
110 Arguments:
111 p points to characters
112 length number to print
113 is_subject TRUE if printing from within md->start_subject
114 md pointer to matching data block, if is_subject is TRUE
115
116 Returns: nothing
117 */
118
119 static void
120 pchars(const uschar *p, int length, BOOL is_subject, match_data *md)
121 {
122 unsigned int c;
123 if (is_subject && length > md->end_subject - p) length = md->end_subject - p;
124 while (length-- > 0)
125 if (isprint(c = *(p++))) printf("%c", c); else printf("\\x%02x", c);
126 }
127 #endif
128
129
130
131 /*************************************************
132 * Match a back-reference *
133 *************************************************/
134
135 /* If a back reference hasn't been set, the length that is passed is greater
136 than the number of characters left in the string, so the match fails.
137
138 Arguments:
139 offset index into the offset vector
140 eptr points into the subject
141 length length to be matched
142 md points to match data block
143 ims the ims flags
144
145 Returns: TRUE if matched
146 */
147
148 static BOOL
149 match_ref(int offset, register USPTR eptr, int length, match_data *md,
150 unsigned long int ims)
151 {
152 USPTR p = md->start_subject + md->offset_vector[offset];
153
154 #ifdef PCRE_DEBUG
155 if (eptr >= md->end_subject)
156 printf("matching subject <null>");
157 else
158 {
159 printf("matching subject ");
160 pchars(eptr, length, TRUE, md);
161 }
162 printf(" against backref ");
163 pchars(p, length, FALSE, md);
164 printf("\n");
165 #endif
166
167 /* Always fail if not enough characters left */
168
169 if (length > md->end_subject - eptr) return FALSE;
170
171 /* Separate the caseless case for speed. In UTF-8 mode we can only do this
172 properly if Unicode properties are supported. Otherwise, we can check only
173 ASCII characters. */
174
175 if ((ims & PCRE_CASELESS) != 0)
176 {
177 #ifdef SUPPORT_UTF8
178 #ifdef SUPPORT_UCP
179 if (md->utf8)
180 {
181 USPTR endptr = eptr + length;
182 while (eptr < endptr)
183 {
184 int c, d;
185 GETCHARINC(c, eptr);
186 GETCHARINC(d, p);
187 if (c != d && c != UCD_OTHERCASE(d)) return FALSE;
188 }
189 }
190 else
191 #endif
192 #endif
193
194 /* The same code works when not in UTF-8 mode and in UTF-8 mode when there
195 is no UCP support. */
196
197 while (length-- > 0)
198 { if (md->lcc[*p++] != md->lcc[*eptr++]) return FALSE; }
199 }
200
201 /* In the caseful case, we can just compare the bytes, whether or not we
202 are in UTF-8 mode. */
203
204 else
205 { while (length-- > 0) if (*p++ != *eptr++) return FALSE; }
206
207 return TRUE;
208 }
209
210
211
212 /***************************************************************************
213 ****************************************************************************
214 RECURSION IN THE match() FUNCTION
215
216 The match() function is highly recursive, though not every recursive call
217 increases the recursive depth. Nevertheless, some regular expressions can cause
218 it to recurse to a great depth. I was writing for Unix, so I just let it call
219 itself recursively. This uses the stack for saving everything that has to be
220 saved for a recursive call. On Unix, the stack can be large, and this works
221 fine.
222
223 It turns out that on some non-Unix-like systems there are problems with
224 programs that use a lot of stack. (This despite the fact that every last chip
225 has oodles of memory these days, and techniques for extending the stack have
226 been known for decades.) So....
227
228 There is a fudge, triggered by defining NO_RECURSE, which avoids recursive
229 calls by keeping local variables that need to be preserved in blocks of memory
230 obtained from malloc() instead instead of on the stack. Macros are used to
231 achieve this so that the actual code doesn't look very different to what it
232 always used to.
233
234 The original heap-recursive code used longjmp(). However, it seems that this
235 can be very slow on some operating systems. Following a suggestion from Stan
236 Switzer, the use of longjmp() has been abolished, at the cost of having to
237 provide a unique number for each call to RMATCH. There is no way of generating
238 a sequence of numbers at compile time in C. I have given them names, to make
239 them stand out more clearly.
240
241 Crude tests on x86 Linux show a small speedup of around 5-8%. However, on
242 FreeBSD, avoiding longjmp() more than halves the time taken to run the standard
243 tests. Furthermore, not using longjmp() means that local dynamic variables
244 don't have indeterminate values; this has meant that the frame size can be
245 reduced because the result can be "passed back" by straight setting of the
246 variable instead of being passed in the frame.
247 ****************************************************************************
248 ***************************************************************************/
249
250 /* Numbers for RMATCH calls. When this list is changed, the code at HEAP_RETURN
251 below must be updated in sync. */
252
253 enum { RM1=1, RM2, RM3, RM4, RM5, RM6, RM7, RM8, RM9, RM10,
254 RM11, RM12, RM13, RM14, RM15, RM16, RM17, RM18, RM19, RM20,
255 RM21, RM22, RM23, RM24, RM25, RM26, RM27, RM28, RM29, RM30,
256 RM31, RM32, RM33, RM34, RM35, RM36, RM37, RM38, RM39, RM40,
257 RM41, RM42, RM43, RM44, RM45, RM46, RM47, RM48, RM49, RM50,
258 RM51, RM52, RM53, RM54, RM55, RM56, RM57, RM58, RM59, RM60,
259 RM61, RM62 };
260
261 /* These versions of the macros use the stack, as normal. There are debugging
262 versions and production versions. Note that the "rw" argument of RMATCH isn't
263 actually used in this definition. */
264
265 #ifndef NO_RECURSE
266 #define REGISTER register
267
268 #ifdef PCRE_DEBUG
269 #define RMATCH(ra,rb,rc,rd,re,rf,rg,rw) \
270 { \
271 printf("match() called in line %d\n", __LINE__); \
272 rrc = match(ra,rb,mstart,markptr,rc,rd,re,rf,rg,rdepth+1); \
273 printf("to line %d\n", __LINE__); \
274 }
275 #define RRETURN(ra) \
276 { \
277 printf("match() returned %d from line %d ", ra, __LINE__); \
278 return ra; \
279 }
280 #else
281 #define RMATCH(ra,rb,rc,rd,re,rf,rg,rw) \
282 rrc = match(ra,rb,mstart,markptr,rc,rd,re,rf,rg,rdepth+1)
283 #define RRETURN(ra) return ra
284 #endif
285
286 #else
287
288
289 /* These versions of the macros manage a private stack on the heap. Note that
290 the "rd" argument of RMATCH isn't actually used in this definition. It's the md
291 argument of match(), which never changes. */
292
293 #define REGISTER
294
295 #define RMATCH(ra,rb,rc,rd,re,rf,rg,rw)\
296 {\
297 heapframe *newframe = (pcre_stack_malloc)(sizeof(heapframe));\
298 frame->Xwhere = rw; \
299 newframe->Xeptr = ra;\
300 newframe->Xecode = rb;\
301 newframe->Xmstart = mstart;\
302 newframe->Xmarkptr = markptr;\
303 newframe->Xoffset_top = rc;\
304 newframe->Xims = re;\
305 newframe->Xeptrb = rf;\
306 newframe->Xflags = rg;\
307 newframe->Xrdepth = frame->Xrdepth + 1;\
308 newframe->Xprevframe = frame;\
309 frame = newframe;\
310 DPRINTF(("restarting from line %d\n", __LINE__));\
311 goto HEAP_RECURSE;\
312 L_##rw:\
313 DPRINTF(("jumped back to line %d\n", __LINE__));\
314 }
315
316 #define RRETURN(ra)\
317 {\
318 heapframe *oldframe = frame;\
319 frame = oldframe->Xprevframe;\
320 (pcre_stack_free)(oldframe);\
321 if (frame != NULL)\
322 {\
323 rrc = ra;\
324 goto HEAP_RETURN;\
325 }\
326 return ra;\
327 }
328
329
330 /* Structure for remembering the local variables in a private frame */
331
332 typedef struct heapframe {
333 struct heapframe *Xprevframe;
334
335 /* Function arguments that may change */
336
337 USPTR Xeptr;
338 const uschar *Xecode;
339 USPTR Xmstart;
340 USPTR Xmarkptr;
341 int Xoffset_top;
342 long int Xims;
343 eptrblock *Xeptrb;
344 int Xflags;
345 unsigned int Xrdepth;
346
347 /* Function local variables */
348
349 USPTR Xcallpat;
350 #ifdef SUPPORT_UTF8
351 USPTR Xcharptr;
352 #endif
353 USPTR Xdata;
354 USPTR Xnext;
355 USPTR Xpp;
356 USPTR Xprev;
357 USPTR Xsaved_eptr;
358
359 recursion_info Xnew_recursive;
360
361 BOOL Xcur_is_word;
362 BOOL Xcondition;
363 BOOL Xprev_is_word;
364
365 unsigned long int Xoriginal_ims;
366
367 #ifdef SUPPORT_UCP
368 int Xprop_type;
369 int Xprop_value;
370 int Xprop_fail_result;
371 int Xprop_category;
372 int Xprop_chartype;
373 int Xprop_script;
374 int Xoclength;
375 uschar Xocchars[8];
376 #endif
377
378 int Xcodelink;
379 int Xctype;
380 unsigned int Xfc;
381 int Xfi;
382 int Xlength;
383 int Xmax;
384 int Xmin;
385 int Xnumber;
386 int Xoffset;
387 int Xop;
388 int Xsave_capture_last;
389 int Xsave_offset1, Xsave_offset2, Xsave_offset3;
390 int Xstacksave[REC_STACK_SAVE_MAX];
391
392 eptrblock Xnewptrb;
393
394 /* Where to jump back to */
395
396 int Xwhere;
397
398 } heapframe;
399
400 #endif
401
402
403 /***************************************************************************
404 ***************************************************************************/
405
406
407
408 /*************************************************
409 * Match from current position *
410 *************************************************/
411
412 /* This function is called recursively in many circumstances. Whenever it
413 returns a negative (error) response, the outer incarnation must also return the
414 same response. */
415
416 /* These macros pack up tests that are used for partial matching, and which
417 appears several times in the code. We set the "hit end" flag if the pointer is
418 at the end of the subject and also past the start of the subject (i.e.
419 something has been matched). For hard partial matching, we then return
420 immediately. The second one is used when we already know we are past the end of
421 the subject. */
422
423 #define CHECK_PARTIAL()\
424 if (md->partial != 0 && eptr >= md->end_subject && eptr > mstart)\
425 {\
426 md->hitend = TRUE;\
427 if (md->partial > 1) MRRETURN(PCRE_ERROR_PARTIAL);\
428 }
429
430 #define SCHECK_PARTIAL()\
431 if (md->partial != 0 && eptr > mstart)\
432 {\
433 md->hitend = TRUE;\
434 if (md->partial > 1) MRRETURN(PCRE_ERROR_PARTIAL);\
435 }
436
437
438 /* Performance note: It might be tempting to extract commonly used fields from
439 the md structure (e.g. utf8, end_subject) into individual variables to improve
440 performance. Tests using gcc on a SPARC disproved this; in the first case, it
441 made performance worse.
442
443 Arguments:
444 eptr pointer to current character in subject
445 ecode pointer to current position in compiled code
446 mstart pointer to the current match start position (can be modified
447 by encountering \K)
448 markptr pointer to the most recent MARK name, or NULL
449 offset_top current top pointer
450 md pointer to "static" info for the match
451 ims current /i, /m, and /s options
452 eptrb pointer to chain of blocks containing eptr at start of
453 brackets - for testing for empty matches
454 flags can contain
455 match_condassert - this is an assertion condition
456 match_cbegroup - this is the start of an unlimited repeat
457 group that can match an empty string
458 rdepth the recursion depth
459
460 Returns: MATCH_MATCH if matched ) these values are >= 0
461 MATCH_NOMATCH if failed to match )
462 a negative MATCH_xxx value for PRUNE, SKIP, etc
463 a negative PCRE_ERROR_xxx value if aborted by an error condition
464 (e.g. stopped by repeated call or recursion limit)
465 */
466
467 static int
468 match(REGISTER USPTR eptr, REGISTER const uschar *ecode, USPTR mstart,
469 const uschar *markptr, int offset_top, match_data *md, unsigned long int ims,
470 eptrblock *eptrb, int flags, unsigned int rdepth)
471 {
472 /* These variables do not need to be preserved over recursion in this function,
473 so they can be ordinary variables in all cases. Mark some of them with
474 "register" because they are used a lot in loops. */
475
476 register int rrc; /* Returns from recursive calls */
477 register int i; /* Used for loops not involving calls to RMATCH() */
478 register unsigned int c; /* Character values not kept over RMATCH() calls */
479 register BOOL utf8; /* Local copy of UTF-8 flag for speed */
480
481 BOOL minimize, possessive; /* Quantifier options */
482 int condcode;
483
484 /* When recursion is not being used, all "local" variables that have to be
485 preserved over calls to RMATCH() are part of a "frame" which is obtained from
486 heap storage. Set up the top-level frame here; others are obtained from the
487 heap whenever RMATCH() does a "recursion". See the macro definitions above. */
488
489 #ifdef NO_RECURSE
490 heapframe *frame = (pcre_stack_malloc)(sizeof(heapframe));
491 frame->Xprevframe = NULL; /* Marks the top level */
492
493 /* Copy in the original argument variables */
494
495 frame->Xeptr = eptr;
496 frame->Xecode = ecode;
497 frame->Xmstart = mstart;
498 frame->Xmarkptr = markptr;
499 frame->Xoffset_top = offset_top;
500 frame->Xims = ims;
501 frame->Xeptrb = eptrb;
502 frame->Xflags = flags;
503 frame->Xrdepth = rdepth;
504
505 /* This is where control jumps back to to effect "recursion" */
506
507 HEAP_RECURSE:
508
509 /* Macros make the argument variables come from the current frame */
510
511 #define eptr frame->Xeptr
512 #define ecode frame->Xecode
513 #define mstart frame->Xmstart
514 #define markptr frame->Xmarkptr
515 #define offset_top frame->Xoffset_top
516 #define ims frame->Xims
517 #define eptrb frame->Xeptrb
518 #define flags frame->Xflags
519 #define rdepth frame->Xrdepth
520
521 /* Ditto for the local variables */
522
523 #ifdef SUPPORT_UTF8
524 #define charptr frame->Xcharptr
525 #endif
526 #define callpat frame->Xcallpat
527 #define codelink frame->Xcodelink
528 #define data frame->Xdata
529 #define next frame->Xnext
530 #define pp frame->Xpp
531 #define prev frame->Xprev
532 #define saved_eptr frame->Xsaved_eptr
533
534 #define new_recursive frame->Xnew_recursive
535
536 #define cur_is_word frame->Xcur_is_word
537 #define condition frame->Xcondition
538 #define prev_is_word frame->Xprev_is_word
539
540 #define original_ims frame->Xoriginal_ims
541
542 #ifdef SUPPORT_UCP
543 #define prop_type frame->Xprop_type
544 #define prop_value frame->Xprop_value
545 #define prop_fail_result frame->Xprop_fail_result
546 #define prop_category frame->Xprop_category
547 #define prop_chartype frame->Xprop_chartype
548 #define prop_script frame->Xprop_script
549 #define oclength frame->Xoclength
550 #define occhars frame->Xocchars
551 #endif
552
553 #define ctype frame->Xctype
554 #define fc frame->Xfc
555 #define fi frame->Xfi
556 #define length frame->Xlength
557 #define max frame->Xmax
558 #define min frame->Xmin
559 #define number frame->Xnumber
560 #define offset frame->Xoffset
561 #define op frame->Xop
562 #define save_capture_last frame->Xsave_capture_last
563 #define save_offset1 frame->Xsave_offset1
564 #define save_offset2 frame->Xsave_offset2
565 #define save_offset3 frame->Xsave_offset3
566 #define stacksave frame->Xstacksave
567
568 #define newptrb frame->Xnewptrb
569
570 /* When recursion is being used, local variables are allocated on the stack and
571 get preserved during recursion in the normal way. In this environment, fi and
572 i, and fc and c, can be the same variables. */
573
574 #else /* NO_RECURSE not defined */
575 #define fi i
576 #define fc c
577
578
579 #ifdef SUPPORT_UTF8 /* Many of these variables are used only */
580 const uschar *charptr; /* in small blocks of the code. My normal */
581 #endif /* style of coding would have declared */
582 const uschar *callpat; /* them within each of those blocks. */
583 const uschar *data; /* However, in order to accommodate the */
584 const uschar *next; /* version of this code that uses an */
585 USPTR pp; /* external "stack" implemented on the */
586 const uschar *prev; /* heap, it is easier to declare them all */
587 USPTR saved_eptr; /* here, so the declarations can be cut */
588 /* out in a block. The only declarations */
589 recursion_info new_recursive; /* within blocks below are for variables */
590 /* that do not have to be preserved over */
591 BOOL cur_is_word; /* a recursive call to RMATCH(). */
592 BOOL condition;
593 BOOL prev_is_word;
594
595 unsigned long int original_ims;
596
597 #ifdef SUPPORT_UCP
598 int prop_type;
599 int prop_value;
600 int prop_fail_result;
601 int prop_category;
602 int prop_chartype;
603 int prop_script;
604 int oclength;
605 uschar occhars[8];
606 #endif
607
608 int codelink;
609 int ctype;
610 int length;
611 int max;
612 int min;
613 int number;
614 int offset;
615 int op;
616 int save_capture_last;
617 int save_offset1, save_offset2, save_offset3;
618 int stacksave[REC_STACK_SAVE_MAX];
619
620 eptrblock newptrb;
621 #endif /* NO_RECURSE */
622
623 /* These statements are here to stop the compiler complaining about unitialized
624 variables. */
625
626 #ifdef SUPPORT_UCP
627 prop_value = 0;
628 prop_fail_result = 0;
629 #endif
630
631
632 /* This label is used for tail recursion, which is used in a few cases even
633 when NO_RECURSE is not defined, in order to reduce the amount of stack that is
634 used. Thanks to Ian Taylor for noticing this possibility and sending the
635 original patch. */
636
637 TAIL_RECURSE:
638
639 /* OK, now we can get on with the real code of the function. Recursive calls
640 are specified by the macro RMATCH and RRETURN is used to return. When
641 NO_RECURSE is *not* defined, these just turn into a recursive call to match()
642 and a "return", respectively (possibly with some debugging if PCRE_DEBUG is
643 defined). However, RMATCH isn't like a function call because it's quite a
644 complicated macro. It has to be used in one particular way. This shouldn't,
645 however, impact performance when true recursion is being used. */
646
647 #ifdef SUPPORT_UTF8
648 utf8 = md->utf8; /* Local copy of the flag */
649 #else
650 utf8 = FALSE;
651 #endif
652
653 /* First check that we haven't called match() too many times, or that we
654 haven't exceeded the recursive call limit. */
655
656 if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT);
657 if (rdepth >= md->match_limit_recursion) RRETURN(PCRE_ERROR_RECURSIONLIMIT);
658
659 original_ims = ims; /* Save for resetting on ')' */
660
661 /* At the start of a group with an unlimited repeat that may match an empty
662 string, the match_cbegroup flag is set. When this is the case, add the current
663 subject pointer to the chain of such remembered pointers, to be checked when we
664 hit the closing ket, in order to break infinite loops that match no characters.
665 When match() is called in other circumstances, don't add to the chain. The
666 match_cbegroup flag must NOT be used with tail recursion, because the memory
667 block that is used is on the stack, so a new one may be required for each
668 match(). */
669
670 if ((flags & match_cbegroup) != 0)
671 {
672 newptrb.epb_saved_eptr = eptr;
673 newptrb.epb_prev = eptrb;
674 eptrb = &newptrb;
675 }
676
677 /* Now start processing the opcodes. */
678
679 for (;;)
680 {
681 minimize = possessive = FALSE;
682 op = *ecode;
683
684 switch(op)
685 {
686 case OP_MARK:
687 markptr = ecode + 2;
688 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode] + ecode[1], offset_top, md,
689 ims, eptrb, flags, RM55);
690
691 /* A return of MATCH_SKIP_ARG means that matching failed at SKIP with an
692 argument, and we must check whether that argument matches this MARK's
693 argument. It is passed back in md->start_match_ptr (an overloading of that
694 variable). If it does match, we reset that variable to the current subject
695 position and return MATCH_SKIP. Otherwise, pass back the return code
696 unaltered. */
697
698 if (rrc == MATCH_SKIP_ARG &&
699 strcmp((char *)markptr, (char *)(md->start_match_ptr)) == 0)
700 {
701 md->start_match_ptr = eptr;
702 RRETURN(MATCH_SKIP);
703 }
704
705 if (md->mark == NULL) md->mark = markptr;
706 RRETURN(rrc);
707
708 case OP_FAIL:
709 MRRETURN(MATCH_NOMATCH);
710
711 case OP_COMMIT:
712 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md,
713 ims, eptrb, flags, RM52);
714 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
715 MRRETURN(MATCH_COMMIT);
716
717 case OP_PRUNE:
718 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md,
719 ims, eptrb, flags, RM51);
720 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
721 MRRETURN(MATCH_PRUNE);
722
723 case OP_PRUNE_ARG:
724 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode] + ecode[1], offset_top, md,
725 ims, eptrb, flags, RM56);
726 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
727 md->mark = ecode + 2;
728 RRETURN(MATCH_PRUNE);
729
730 case OP_SKIP:
731 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md,
732 ims, eptrb, flags, RM53);
733 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
734 md->start_match_ptr = eptr; /* Pass back current position */
735 MRRETURN(MATCH_SKIP);
736
737 case OP_SKIP_ARG:
738 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode] + ecode[1], offset_top, md,
739 ims, eptrb, flags, RM57);
740 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
741
742 /* Pass back the current skip name by overloading md->start_match_ptr and
743 returning the special MATCH_SKIP_ARG return code. This will either be
744 caught by a matching MARK, or get to the top, where it is treated the same
745 as PRUNE. */
746
747 md->start_match_ptr = ecode + 2;
748 RRETURN(MATCH_SKIP_ARG);
749
750 case OP_THEN:
751 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md,
752 ims, eptrb, flags, RM54);
753 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
754 MRRETURN(MATCH_THEN);
755
756 case OP_THEN_ARG:
757 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode] + ecode[1], offset_top, md,
758 ims, eptrb, flags, RM58);
759 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
760 md->mark = ecode + 2;
761 RRETURN(MATCH_THEN);
762
763 /* Handle a capturing bracket. If there is space in the offset vector, save
764 the current subject position in the working slot at the top of the vector.
765 We mustn't change the current values of the data slot, because they may be
766 set from a previous iteration of this group, and be referred to by a
767 reference inside the group.
768
769 If the bracket fails to match, we need to restore this value and also the
770 values of the final offsets, in case they were set by a previous iteration
771 of the same bracket.
772
773 If there isn't enough space in the offset vector, treat this as if it were
774 a non-capturing bracket. Don't worry about setting the flag for the error
775 case here; that is handled in the code for KET. */
776
777 case OP_CBRA:
778 case OP_SCBRA:
779 number = GET2(ecode, 1+LINK_SIZE);
780 offset = number << 1;
781
782 #ifdef PCRE_DEBUG
783 printf("start bracket %d\n", number);
784 printf("subject=");
785 pchars(eptr, 16, TRUE, md);
786 printf("\n");
787 #endif
788
789 if (offset < md->offset_max)
790 {
791 save_offset1 = md->offset_vector[offset];
792 save_offset2 = md->offset_vector[offset+1];
793 save_offset3 = md->offset_vector[md->offset_end - number];
794 save_capture_last = md->capture_last;
795
796 DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3));
797 md->offset_vector[md->offset_end - number] = eptr - md->start_subject;
798
799 flags = (op == OP_SCBRA)? match_cbegroup : 0;
800 do
801 {
802 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md,
803 ims, eptrb, flags, RM1);
804 if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) RRETURN(rrc);
805 md->capture_last = save_capture_last;
806 ecode += GET(ecode, 1);
807 }
808 while (*ecode == OP_ALT);
809
810 DPRINTF(("bracket %d failed\n", number));
811
812 md->offset_vector[offset] = save_offset1;
813 md->offset_vector[offset+1] = save_offset2;
814 md->offset_vector[md->offset_end - number] = save_offset3;
815
816 if (rrc != MATCH_THEN) md->mark = markptr;
817 RRETURN(MATCH_NOMATCH);
818 }
819
820 /* FALL THROUGH ... Insufficient room for saving captured contents. Treat
821 as a non-capturing bracket. */
822
823 /* VVVVVVVVVVVVVVVVVVVVVVVVV */
824 /* VVVVVVVVVVVVVVVVVVVVVVVVV */
825
826 DPRINTF(("insufficient capture room: treat as non-capturing\n"));
827
828 /* VVVVVVVVVVVVVVVVVVVVVVVVV */
829 /* VVVVVVVVVVVVVVVVVVVVVVVVV */
830
831 /* Non-capturing bracket. Loop for all the alternatives. When we get to the
832 final alternative within the brackets, we would return the result of a
833 recursive call to match() whatever happened. We can reduce stack usage by
834 turning this into a tail recursion, except in the case when match_cbegroup
835 is set.*/
836
837 case OP_BRA:
838 case OP_SBRA:
839 DPRINTF(("start non-capturing bracket\n"));
840 flags = (op >= OP_SBRA)? match_cbegroup : 0;
841 for (;;)
842 {
843 if (ecode[GET(ecode, 1)] != OP_ALT) /* Final alternative */
844 {
845 if (flags == 0) /* Not a possibly empty group */
846 {
847 ecode += _pcre_OP_lengths[*ecode];
848 DPRINTF(("bracket 0 tail recursion\n"));
849 goto TAIL_RECURSE;
850 }
851
852 /* Possibly empty group; can't use tail recursion. */
853
854 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md, ims,
855 eptrb, flags, RM48);
856 if (rrc == MATCH_NOMATCH) md->mark = markptr;
857 RRETURN(rrc);
858 }
859
860 /* For non-final alternatives, continue the loop for a NOMATCH result;
861 otherwise return. */
862
863 RMATCH(eptr, ecode + _pcre_OP_lengths[*ecode], offset_top, md, ims,
864 eptrb, flags, RM2);
865 if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) RRETURN(rrc);
866 ecode += GET(ecode, 1);
867 }
868 /* Control never reaches here. */
869
870 /* Conditional group: compilation checked that there are no more than
871 two branches. If the condition is false, skipping the first branch takes us
872 past the end if there is only one branch, but that's OK because that is
873 exactly what going to the ket would do. As there is only one branch to be
874 obeyed, we can use tail recursion to avoid using another stack frame. */
875
876 case OP_COND:
877 case OP_SCOND:
878 codelink= GET(ecode, 1);
879
880 /* Because of the way auto-callout works during compile, a callout item is
881 inserted between OP_COND and an assertion condition. */
882
883 if (ecode[LINK_SIZE+1] == OP_CALLOUT)
884 {
885 if (pcre_callout != NULL)
886 {
887 pcre_callout_block cb;
888 cb.version = 1; /* Version 1 of the callout block */
889 cb.callout_number = ecode[LINK_SIZE+2];
890 cb.offset_vector = md->offset_vector;
891 cb.subject = (PCRE_SPTR)md->start_subject;
892 cb.subject_length = md->end_subject - md->start_subject;
893 cb.start_match = mstart - md->start_subject;
894 cb.current_position = eptr - md->start_subject;
895 cb.pattern_position = GET(ecode, LINK_SIZE + 3);
896 cb.next_item_length = GET(ecode, 3 + 2*LINK_SIZE);
897 cb.capture_top = offset_top/2;
898 cb.capture_last = md->capture_last;
899 cb.callout_data = md->callout_data;
900 if ((rrc = (*pcre_callout)(&cb)) > 0) MRRETURN(MATCH_NOMATCH);
901 if (rrc < 0) RRETURN(rrc);
902 }
903 ecode += _pcre_OP_lengths[OP_CALLOUT];
904 }
905
906 condcode = ecode[LINK_SIZE+1];
907
908 /* Now see what the actual condition is */
909
910 if (condcode == OP_RREF || condcode == OP_NRREF) /* Recursion test */
911 {
912 if (md->recursive == NULL) /* Not recursing => FALSE */
913 {
914 condition = FALSE;
915 ecode += GET(ecode, 1);
916 }
917 else
918 {
919 int recno = GET2(ecode, LINK_SIZE + 2); /* Recursion group number*/
920 condition = (recno == RREF_ANY || recno == md->recursive->group_num);
921
922 /* If the test is for recursion into a specific subpattern, and it is
923 false, but the test was set up by name, scan the table to see if the
924 name refers to any other numbers, and test them. The condition is true
925 if any one is set. */
926
927 if (!condition && condcode == OP_NRREF && recno != RREF_ANY)
928 {
929 uschar *slotA = md->name_table;
930 for (i = 0; i < md->name_count; i++)
931 {
932 if (GET2(slotA, 0) == recno) break;
933 slotA += md->name_entry_size;
934 }
935
936 /* Found a name for the number - there can be only one; duplicate
937 names for different numbers are allowed, but not vice versa. First
938 scan down for duplicates. */
939
940 if (i < md->name_count)
941 {
942 uschar *slotB = slotA;
943 while (slotB > md->name_table)
944 {
945 slotB -= md->name_entry_size;
946 if (strcmp((char *)slotA + 2, (char *)slotB + 2) == 0)
947 {
948 condition = GET2(slotB, 0) == md->recursive->group_num;
949 if (condition) break;
950 }
951 else break;
952 }
953
954 /* Scan up for duplicates */
955
956 if (!condition)
957 {
958 slotB = slotA;
959 for (i++; i < md->name_count; i++)
960 {
961 slotB += md->name_entry_size;
962 if (strcmp((char *)slotA + 2, (char *)slotB + 2) == 0)
963 {
964 condition = GET2(slotB, 0) == md->recursive->group_num;
965 if (condition) break;
966 }
967 else break;
968 }
969 }
970 }
971 }
972
973 /* Chose branch according to the condition */
974
975 ecode += condition? 3 : GET(ecode, 1);
976 }
977 }
978
979 else if (condcode == OP_CREF || condcode == OP_NCREF) /* Group used test */
980 {
981 offset = GET2(ecode, LINK_SIZE+2) << 1; /* Doubled ref number */
982 condition = offset < offset_top && md->offset_vector[offset] >= 0;
983
984 /* If the numbered capture is unset, but the reference was by name,
985 scan the table to see if the name refers to any other numbers, and test
986 them. The condition is true if any one is set. This is tediously similar
987 to the code above, but not close enough to try to amalgamate. */
988
989 if (!condition && condcode == OP_NCREF)
990 {
991 int refno = offset >> 1;
992 uschar *slotA = md->name_table;
993
994 for (i = 0; i < md->name_count; i++)
995 {
996 if (GET2(slotA, 0) == refno) break;
997 slotA += md->name_entry_size;
998 }
999
1000 /* Found a name for the number - there can be only one; duplicate names
1001 for different numbers are allowed, but not vice versa. First scan down
1002 for duplicates. */
1003
1004 if (i < md->name_count)
1005 {
1006 uschar *slotB = slotA;
1007 while (slotB > md->name_table)
1008 {
1009 slotB -= md->name_entry_size;
1010 if (strcmp((char *)slotA + 2, (char *)slotB + 2) == 0)
1011 {
1012 offset = GET2(slotB, 0) << 1;
1013 condition = offset < offset_top &&
1014 md->offset_vector[offset] >= 0;
1015 if (condition) break;
1016 }
1017 else break;
1018 }
1019
1020 /* Scan up for duplicates */
1021
1022 if (!condition)
1023 {
1024 slotB = slotA;
1025 for (i++; i < md->name_count; i++)
1026 {
1027 slotB += md->name_entry_size;
1028 if (strcmp((char *)slotA + 2, (char *)slotB + 2) == 0)
1029 {
1030 offset = GET2(slotB, 0) << 1;
1031 condition = offset < offset_top &&
1032 md->offset_vector[offset] >= 0;
1033 if (condition) break;
1034 }
1035 else break;
1036 }
1037 }
1038 }
1039 }
1040
1041 /* Chose branch according to the condition */
1042
1043 ecode += condition? 3 : GET(ecode, 1);
1044 }
1045
1046 else if (condcode == OP_DEF) /* DEFINE - always false */
1047 {
1048 condition = FALSE;
1049 ecode += GET(ecode, 1);
1050 }
1051
1052 /* The condition is an assertion. Call match() to evaluate it - setting
1053 the final argument match_condassert causes it to stop at the end of an
1054 assertion. */
1055
1056 else
1057 {
1058 RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL,
1059 match_condassert, RM3);
1060 if (rrc == MATCH_MATCH)
1061 {
1062 condition = TRUE;
1063 ecode += 1 + LINK_SIZE + GET(ecode, LINK_SIZE + 2);
1064 while (*ecode == OP_ALT) ecode += GET(ecode, 1);
1065 }
1066 else if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN)
1067 {
1068 RRETURN(rrc); /* Need braces because of following else */
1069 }
1070 else
1071 {
1072 condition = FALSE;
1073 ecode += codelink;
1074 }
1075 }
1076
1077 /* We are now at the branch that is to be obeyed. As there is only one,
1078 we can use tail recursion to avoid using another stack frame, except when
1079 match_cbegroup is required for an unlimited repeat of a possibly empty
1080 group. If the second alternative doesn't exist, we can just plough on. */
1081
1082 if (condition || *ecode == OP_ALT)
1083 {
1084 ecode += 1 + LINK_SIZE;
1085 if (op == OP_SCOND) /* Possibly empty group */
1086 {
1087 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, match_cbegroup, RM49);
1088 RRETURN(rrc);
1089 }
1090 else /* Group must match something */
1091 {
1092 flags = 0;
1093 goto TAIL_RECURSE;
1094 }
1095 }
1096 else /* Condition false & no alternative */
1097 {
1098 ecode += 1 + LINK_SIZE;
1099 }
1100 break;
1101
1102
1103 /* Before OP_ACCEPT there may be any number of OP_CLOSE opcodes,
1104 to close any currently open capturing brackets. */
1105
1106 case OP_CLOSE:
1107 number = GET2(ecode, 1);
1108 offset = number << 1;
1109
1110 #ifdef PCRE_DEBUG
1111 printf("end bracket %d at *ACCEPT", number);
1112 printf("\n");
1113 #endif
1114
1115 md->capture_last = number;
1116 if (offset >= md->offset_max) md->offset_overflow = TRUE; else
1117 {
1118 md->offset_vector[offset] =
1119 md->offset_vector[md->offset_end - number];
1120 md->offset_vector[offset+1] = eptr - md->start_subject;
1121 if (offset_top <= offset) offset_top = offset + 2;
1122 }
1123 ecode += 3;
1124 break;
1125
1126
1127 /* End of the pattern, either real or forced. If we are in a top-level
1128 recursion, we should restore the offsets appropriately and continue from
1129 after the call. */
1130
1131 case OP_ACCEPT:
1132 case OP_END:
1133 if (md->recursive != NULL && md->recursive->group_num == 0)
1134 {
1135 recursion_info *rec = md->recursive;
1136 DPRINTF(("End of pattern in a (?0) recursion\n"));
1137 md->recursive = rec->prevrec;
1138 memmove(md->offset_vector, rec->offset_save,
1139 rec->saved_max * sizeof(int));
1140 offset_top = rec->save_offset_top;
1141 ims = original_ims;
1142 ecode = rec->after_call;
1143 break;
1144 }
1145
1146 /* Otherwise, if we have matched an empty string, fail if PCRE_NOTEMPTY is
1147 set, or if PCRE_NOTEMPTY_ATSTART is set and we have matched at the start of
1148 the subject. In both cases, backtracking will then try other alternatives,
1149 if any. */
1150
1151 if (eptr == mstart &&
1152 (md->notempty ||
1153 (md->notempty_atstart &&
1154 mstart == md->start_subject + md->start_offset)))
1155 MRRETURN(MATCH_NOMATCH);
1156
1157 /* Otherwise, we have a match. */
1158
1159 md->end_match_ptr = eptr; /* Record where we ended */
1160 md->end_offset_top = offset_top; /* and how many extracts were taken */
1161 md->start_match_ptr = mstart; /* and the start (\K can modify) */
1162
1163 /* For some reason, the macros don't work properly if an expression is
1164 given as the argument to MRRETURN when the heap is in use. */
1165
1166 rrc = (op == OP_END)? MATCH_MATCH : MATCH_ACCEPT;
1167 MRRETURN(rrc);
1168
1169 /* Change option settings */
1170
1171 case OP_OPT:
1172 ims = ecode[1];
1173 ecode += 2;
1174 DPRINTF(("ims set to %02lx\n", ims));
1175 break;
1176
1177 /* Assertion brackets. Check the alternative branches in turn - the
1178 matching won't pass the KET for an assertion. If any one branch matches,
1179 the assertion is true. Lookbehind assertions have an OP_REVERSE item at the
1180 start of each branch to move the current point backwards, so the code at
1181 this level is identical to the lookahead case. */
1182
1183 case OP_ASSERT:
1184 case OP_ASSERTBACK:
1185 do
1186 {
1187 RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, 0,
1188 RM4);
1189 if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT)
1190 {
1191 mstart = md->start_match_ptr; /* In case \K reset it */
1192 break;
1193 }
1194 if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) RRETURN(rrc);
1195 ecode += GET(ecode, 1);
1196 }
1197 while (*ecode == OP_ALT);
1198 if (*ecode == OP_KET) MRRETURN(MATCH_NOMATCH);
1199
1200 /* If checking an assertion for a condition, return MATCH_MATCH. */
1201
1202 if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH);
1203
1204 /* Continue from after the assertion, updating the offsets high water
1205 mark, since extracts may have been taken during the assertion. */
1206
1207 do ecode += GET(ecode,1); while (*ecode == OP_ALT);
1208 ecode += 1 + LINK_SIZE;
1209 offset_top = md->end_offset_top;
1210 continue;
1211
1212 /* Negative assertion: all branches must fail to match. Encountering SKIP,
1213 PRUNE, or COMMIT means we must assume failure without checking subsequent
1214 branches. */
1215
1216 case OP_ASSERT_NOT:
1217 case OP_ASSERTBACK_NOT:
1218 do
1219 {
1220 RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, 0,
1221 RM5);
1222 if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) MRRETURN(MATCH_NOMATCH);
1223 if (rrc == MATCH_SKIP || rrc == MATCH_PRUNE || rrc == MATCH_COMMIT)
1224 {
1225 do ecode += GET(ecode,1); while (*ecode == OP_ALT);
1226 break;
1227 }
1228 if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) RRETURN(rrc);
1229 ecode += GET(ecode,1);
1230 }
1231 while (*ecode == OP_ALT);
1232
1233 if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH);
1234
1235 ecode += 1 + LINK_SIZE;
1236 continue;
1237
1238 /* Move the subject pointer back. This occurs only at the start of
1239 each branch of a lookbehind assertion. If we are too close to the start to
1240 move back, this match function fails. When working with UTF-8 we move
1241 back a number of characters, not bytes. */
1242
1243 case OP_REVERSE:
1244 #ifdef SUPPORT_UTF8
1245 if (utf8)
1246 {
1247 i = GET(ecode, 1);
1248 while (i-- > 0)
1249 {
1250 eptr--;
1251 if (eptr < md->start_subject) MRRETURN(MATCH_NOMATCH);
1252 BACKCHAR(eptr);
1253 }
1254 }
1255 else
1256 #endif
1257
1258 /* No UTF-8 support, or not in UTF-8 mode: count is byte count */
1259
1260 {
1261 eptr -= GET(ecode, 1);
1262 if (eptr < md->start_subject) MRRETURN(MATCH_NOMATCH);
1263 }
1264
1265 /* Save the earliest consulted character, then skip to next op code */
1266
1267 if (eptr < md->start_used_ptr) md->start_used_ptr = eptr;
1268 ecode += 1 + LINK_SIZE;
1269 break;
1270
1271 /* The callout item calls an external function, if one is provided, passing
1272 details of the match so far. This is mainly for debugging, though the
1273 function is able to force a failure. */
1274
1275 case OP_CALLOUT:
1276 if (pcre_callout != NULL)
1277 {
1278 pcre_callout_block cb;
1279 cb.version = 1; /* Version 1 of the callout block */
1280 cb.callout_number = ecode[1];
1281 cb.offset_vector = md->offset_vector;
1282 cb.subject = (PCRE_SPTR)md->start_subject;
1283 cb.subject_length = md->end_subject - md->start_subject;
1284 cb.start_match = mstart - md->start_subject;
1285 cb.current_position = eptr - md->start_subject;
1286 cb.pattern_position = GET(ecode, 2);
1287 cb.next_item_length = GET(ecode, 2 + LINK_SIZE);
1288 cb.capture_top = offset_top/2;
1289 cb.capture_last = md->capture_last;
1290 cb.callout_data = md->callout_data;
1291 if ((rrc = (*pcre_callout)(&cb)) > 0) MRRETURN(MATCH_NOMATCH);
1292 if (rrc < 0) RRETURN(rrc);
1293 }
1294 ecode += 2 + 2*LINK_SIZE;
1295 break;
1296
1297 /* Recursion either matches the current regex, or some subexpression. The
1298 offset data is the offset to the starting bracket from the start of the
1299 whole pattern. (This is so that it works from duplicated subpatterns.)
1300
1301 If there are any capturing brackets started but not finished, we have to
1302 save their starting points and reinstate them after the recursion. However,
1303 we don't know how many such there are (offset_top records the completed
1304 total) so we just have to save all the potential data. There may be up to
1305 65535 such values, which is too large to put on the stack, but using malloc
1306 for small numbers seems expensive. As a compromise, the stack is used when
1307 there are no more than REC_STACK_SAVE_MAX values to store; otherwise malloc
1308 is used. A problem is what to do if the malloc fails ... there is no way of
1309 returning to the top level with an error. Save the top REC_STACK_SAVE_MAX
1310 values on the stack, and accept that the rest may be wrong.
1311
1312 There are also other values that have to be saved. We use a chained
1313 sequence of blocks that actually live on the stack. Thanks to Robin Houston
1314 for the original version of this logic. */
1315
1316 case OP_RECURSE:
1317 {
1318 callpat = md->start_code + GET(ecode, 1);
1319 new_recursive.group_num = (callpat == md->start_code)? 0 :
1320 GET2(callpat, 1 + LINK_SIZE);
1321
1322 /* Add to "recursing stack" */
1323
1324 new_recursive.prevrec = md->recursive;
1325 md->recursive = &new_recursive;
1326
1327 /* Find where to continue from afterwards */
1328
1329 ecode += 1 + LINK_SIZE;
1330 new_recursive.after_call = ecode;
1331
1332 /* Now save the offset data. */
1333
1334 new_recursive.saved_max = md->offset_end;
1335 if (new_recursive.saved_max <= REC_STACK_SAVE_MAX)
1336 new_recursive.offset_save = stacksave;
1337 else
1338 {
1339 new_recursive.offset_save =
1340 (int *)(pcre_malloc)(new_recursive.saved_max * sizeof(int));
1341 if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY);
1342 }
1343
1344 memcpy(new_recursive.offset_save, md->offset_vector,
1345 new_recursive.saved_max * sizeof(int));
1346 new_recursive.save_offset_top = offset_top;
1347
1348 /* OK, now we can do the recursion. For each top-level alternative we
1349 restore the offset and recursion data. */
1350
1351 DPRINTF(("Recursing into group %d\n", new_recursive.group_num));
1352 flags = (*callpat >= OP_SBRA)? match_cbegroup : 0;
1353 do
1354 {
1355 RMATCH(eptr, callpat + _pcre_OP_lengths[*callpat], offset_top,
1356 md, ims, eptrb, flags, RM6);
1357 if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT)
1358 {
1359 DPRINTF(("Recursion matched\n"));
1360 md->recursive = new_recursive.prevrec;
1361 if (new_recursive.offset_save != stacksave)
1362 (pcre_free)(new_recursive.offset_save);
1363 MRRETURN(MATCH_MATCH);
1364 }
1365 else if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN)
1366 {
1367 DPRINTF(("Recursion gave error %d\n", rrc));
1368 if (new_recursive.offset_save != stacksave)
1369 (pcre_free)(new_recursive.offset_save);
1370 RRETURN(rrc);
1371 }
1372
1373 md->recursive = &new_recursive;
1374 memcpy(md->offset_vector, new_recursive.offset_save,
1375 new_recursive.saved_max * sizeof(int));
1376 callpat += GET(callpat, 1);
1377 }
1378 while (*callpat == OP_ALT);
1379
1380 DPRINTF(("Recursion didn't match\n"));
1381 md->recursive = new_recursive.prevrec;
1382 if (new_recursive.offset_save != stacksave)
1383 (pcre_free)(new_recursive.offset_save);
1384 MRRETURN(MATCH_NOMATCH);
1385 }
1386 /* Control never reaches here */
1387
1388 /* "Once" brackets are like assertion brackets except that after a match,
1389 the point in the subject string is not moved back. Thus there can never be
1390 a move back into the brackets. Friedl calls these "atomic" subpatterns.
1391 Check the alternative branches in turn - the matching won't pass the KET
1392 for this kind of subpattern. If any one branch matches, we carry on as at
1393 the end of a normal bracket, leaving the subject pointer, but resetting
1394 the start-of-match value in case it was changed by \K. */
1395
1396 case OP_ONCE:
1397 prev = ecode;
1398 saved_eptr = eptr;
1399
1400 do
1401 {
1402 RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, 0, RM7);
1403 if (rrc == MATCH_MATCH) /* Note: _not_ MATCH_ACCEPT */
1404 {
1405 mstart = md->start_match_ptr;
1406 break;
1407 }
1408 if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) RRETURN(rrc);
1409 ecode += GET(ecode,1);
1410 }
1411 while (*ecode == OP_ALT);
1412
1413 /* If hit the end of the group (which could be repeated), fail */
1414
1415 if (*ecode != OP_ONCE && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH);
1416
1417 /* Continue as from after the assertion, updating the offsets high water
1418 mark, since extracts may have been taken. */
1419
1420 do ecode += GET(ecode, 1); while (*ecode == OP_ALT);
1421
1422 offset_top = md->end_offset_top;
1423 eptr = md->end_match_ptr;
1424
1425 /* For a non-repeating ket, just continue at this level. This also
1426 happens for a repeating ket if no characters were matched in the group.
1427 This is the forcible breaking of infinite loops as implemented in Perl
1428 5.005. If there is an options reset, it will get obeyed in the normal
1429 course of events. */
1430
1431 if (*ecode == OP_KET || eptr == saved_eptr)
1432 {
1433 ecode += 1+LINK_SIZE;
1434 break;
1435 }
1436
1437 /* The repeating kets try the rest of the pattern or restart from the
1438 preceding bracket, in the appropriate order. The second "call" of match()
1439 uses tail recursion, to avoid using another stack frame. We need to reset
1440 any options that changed within the bracket before re-running it, so
1441 check the next opcode. */
1442
1443 if (ecode[1+LINK_SIZE] == OP_OPT)
1444 {
1445 ims = (ims & ~PCRE_IMS) | ecode[4];
1446 DPRINTF(("ims set to %02lx at group repeat\n", ims));
1447 }
1448
1449 if (*ecode == OP_KETRMIN)
1450 {
1451 RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, 0, RM8);
1452 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
1453 ecode = prev;
1454 flags = 0;
1455 goto TAIL_RECURSE;
1456 }
1457 else /* OP_KETRMAX */
1458 {
1459 RMATCH(eptr, prev, offset_top, md, ims, eptrb, match_cbegroup, RM9);
1460 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
1461 ecode += 1 + LINK_SIZE;
1462 flags = 0;
1463 goto TAIL_RECURSE;
1464 }
1465 /* Control never gets here */
1466
1467 /* An alternation is the end of a branch; scan along to find the end of the
1468 bracketed group and go to there. */
1469
1470 case OP_ALT:
1471 do ecode += GET(ecode,1); while (*ecode == OP_ALT);
1472 break;
1473
1474 /* BRAZERO, BRAMINZERO and SKIPZERO occur just before a bracket group,
1475 indicating that it may occur zero times. It may repeat infinitely, or not
1476 at all - i.e. it could be ()* or ()? or even (){0} in the pattern. Brackets
1477 with fixed upper repeat limits are compiled as a number of copies, with the
1478 optional ones preceded by BRAZERO or BRAMINZERO. */
1479
1480 case OP_BRAZERO:
1481 {
1482 next = ecode+1;
1483 RMATCH(eptr, next, offset_top, md, ims, eptrb, 0, RM10);
1484 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
1485 do next += GET(next,1); while (*next == OP_ALT);
1486 ecode = next + 1 + LINK_SIZE;
1487 }
1488 break;
1489
1490 case OP_BRAMINZERO:
1491 {
1492 next = ecode+1;
1493 do next += GET(next, 1); while (*next == OP_ALT);
1494 RMATCH(eptr, next + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0, RM11);
1495 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
1496 ecode++;
1497 }
1498 break;
1499
1500 case OP_SKIPZERO:
1501 {
1502 next = ecode+1;
1503 do next += GET(next,1); while (*next == OP_ALT);
1504 ecode = next + 1 + LINK_SIZE;
1505 }
1506 break;
1507
1508 /* End of a group, repeated or non-repeating. */
1509
1510 case OP_KET:
1511 case OP_KETRMIN:
1512 case OP_KETRMAX:
1513 prev = ecode - GET(ecode, 1);
1514
1515 /* If this was a group that remembered the subject start, in order to break
1516 infinite repeats of empty string matches, retrieve the subject start from
1517 the chain. Otherwise, set it NULL. */
1518
1519 if (*prev >= OP_SBRA)
1520 {
1521 saved_eptr = eptrb->epb_saved_eptr; /* Value at start of group */
1522 eptrb = eptrb->epb_prev; /* Backup to previous group */
1523 }
1524 else saved_eptr = NULL;
1525
1526 /* If we are at the end of an assertion group or an atomic group, stop
1527 matching and return MATCH_MATCH, but record the current high water mark for
1528 use by positive assertions. We also need to record the match start in case
1529 it was changed by \K. */
1530
1531 if (*prev == OP_ASSERT || *prev == OP_ASSERT_NOT ||
1532 *prev == OP_ASSERTBACK || *prev == OP_ASSERTBACK_NOT ||
1533 *prev == OP_ONCE)
1534 {
1535 md->end_match_ptr = eptr; /* For ONCE */
1536 md->end_offset_top = offset_top;
1537 md->start_match_ptr = mstart;
1538 MRRETURN(MATCH_MATCH);
1539 }
1540
1541 /* For capturing groups we have to check the group number back at the start
1542 and if necessary complete handling an extraction by setting the offsets and
1543 bumping the high water mark. Note that whole-pattern recursion is coded as
1544 a recurse into group 0, so it won't be picked up here. Instead, we catch it
1545 when the OP_END is reached. Other recursion is handled here. */
1546
1547 if (*prev == OP_CBRA || *prev == OP_SCBRA)
1548 {
1549 number = GET2(prev, 1+LINK_SIZE);
1550 offset = number << 1;
1551
1552 #ifdef PCRE_DEBUG
1553 printf("end bracket %d", number);
1554 printf("\n");
1555 #endif
1556
1557 md->capture_last = number;
1558 if (offset >= md->offset_max) md->offset_overflow = TRUE; else
1559 {
1560 md->offset_vector[offset] =
1561 md->offset_vector[md->offset_end - number];
1562 md->offset_vector[offset+1] = eptr - md->start_subject;
1563 if (offset_top <= offset) offset_top = offset + 2;
1564 }
1565
1566 /* Handle a recursively called group. Restore the offsets
1567 appropriately and continue from after the call. */
1568
1569 if (md->recursive != NULL && md->recursive->group_num == number)
1570 {
1571 recursion_info *rec = md->recursive;
1572 DPRINTF(("Recursion (%d) succeeded - continuing\n", number));
1573 md->recursive = rec->prevrec;
1574 memcpy(md->offset_vector, rec->offset_save,
1575 rec->saved_max * sizeof(int));
1576 offset_top = rec->save_offset_top;
1577 ecode = rec->after_call;
1578 ims = original_ims;
1579 break;
1580 }
1581 }
1582
1583 /* For both capturing and non-capturing groups, reset the value of the ims
1584 flags, in case they got changed during the group. */
1585
1586 ims = original_ims;
1587 DPRINTF(("ims reset to %02lx\n", ims));
1588
1589 /* For a non-repeating ket, just continue at this level. This also
1590 happens for a repeating ket if no characters were matched in the group.
1591 This is the forcible breaking of infinite loops as implemented in Perl
1592 5.005. If there is an options reset, it will get obeyed in the normal
1593 course of events. */
1594
1595 if (*ecode == OP_KET || eptr == saved_eptr)
1596 {
1597 ecode += 1 + LINK_SIZE;
1598 break;
1599 }
1600
1601 /* The repeating kets try the rest of the pattern or restart from the
1602 preceding bracket, in the appropriate order. In the second case, we can use
1603 tail recursion to avoid using another stack frame, unless we have an
1604 unlimited repeat of a group that can match an empty string. */
1605
1606 flags = (*prev >= OP_SBRA)? match_cbegroup : 0;
1607
1608 if (*ecode == OP_KETRMIN)
1609 {
1610 RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, 0, RM12);
1611 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
1612 if (flags != 0) /* Could match an empty string */
1613 {
1614 RMATCH(eptr, prev, offset_top, md, ims, eptrb, flags, RM50);
1615 RRETURN(rrc);
1616 }
1617 ecode = prev;
1618 goto TAIL_RECURSE;
1619 }
1620 else /* OP_KETRMAX */
1621 {
1622 RMATCH(eptr, prev, offset_top, md, ims, eptrb, flags, RM13);
1623 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
1624 ecode += 1 + LINK_SIZE;
1625 flags = 0;
1626 goto TAIL_RECURSE;
1627 }
1628 /* Control never gets here */
1629
1630 /* Start of subject unless notbol, or after internal newline if multiline */
1631
1632 case OP_CIRC:
1633 if (md->notbol && eptr == md->start_subject) MRRETURN(MATCH_NOMATCH);
1634 if ((ims & PCRE_MULTILINE) != 0)
1635 {
1636 if (eptr != md->start_subject &&
1637 (eptr == md->end_subject || !WAS_NEWLINE(eptr)))
1638 MRRETURN(MATCH_NOMATCH);
1639 ecode++;
1640 break;
1641 }
1642 /* ... else fall through */
1643
1644 /* Start of subject assertion */
1645
1646 case OP_SOD:
1647 if (eptr != md->start_subject) MRRETURN(MATCH_NOMATCH);
1648 ecode++;
1649 break;
1650
1651 /* Start of match assertion */
1652
1653 case OP_SOM:
1654 if (eptr != md->start_subject + md->start_offset) MRRETURN(MATCH_NOMATCH);
1655 ecode++;
1656 break;
1657
1658 /* Reset the start of match point */
1659
1660 case OP_SET_SOM:
1661 mstart = eptr;
1662 ecode++;
1663 break;
1664
1665 /* Assert before internal newline if multiline, or before a terminating
1666 newline unless endonly is set, else end of subject unless noteol is set. */
1667
1668 case OP_DOLL:
1669 if ((ims & PCRE_MULTILINE) != 0)
1670 {
1671 if (eptr < md->end_subject)
1672 { if (!IS_NEWLINE(eptr)) MRRETURN(MATCH_NOMATCH); }
1673 else
1674 { if (md->noteol) MRRETURN(MATCH_NOMATCH); }
1675 ecode++;
1676 break;
1677 }
1678 else
1679 {
1680 if (md->noteol) MRRETURN(MATCH_NOMATCH);
1681 if (!md->endonly)
1682 {
1683 if (eptr != md->end_subject &&
1684 (!IS_NEWLINE(eptr) || eptr != md->end_subject - md->nllen))
1685 MRRETURN(MATCH_NOMATCH);
1686 ecode++;
1687 break;
1688 }
1689 }
1690 /* ... else fall through for endonly */
1691
1692 /* End of subject assertion (\z) */
1693
1694 case OP_EOD:
1695 if (eptr < md->end_subject) MRRETURN(MATCH_NOMATCH);
1696 ecode++;
1697 break;
1698
1699 /* End of subject or ending \n assertion (\Z) */
1700
1701 case OP_EODN:
1702 if (eptr != md->end_subject &&
1703 (!IS_NEWLINE(eptr) || eptr != md->end_subject - md->nllen))
1704 MRRETURN(MATCH_NOMATCH);
1705 ecode++;
1706 break;
1707
1708 /* Word boundary assertions */
1709
1710 case OP_NOT_WORD_BOUNDARY:
1711 case OP_WORD_BOUNDARY:
1712 {
1713
1714 /* Find out if the previous and current characters are "word" characters.
1715 It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to
1716 be "non-word" characters. Remember the earliest consulted character for
1717 partial matching. */
1718
1719 #ifdef SUPPORT_UTF8
1720 if (utf8)
1721 {
1722 /* Get status of previous character */
1723
1724 if (eptr == md->start_subject) prev_is_word = FALSE; else
1725 {
1726 USPTR lastptr = eptr - 1;
1727 while((*lastptr & 0xc0) == 0x80) lastptr--;
1728 if (lastptr < md->start_used_ptr) md->start_used_ptr = lastptr;
1729 GETCHAR(c, lastptr);
1730 #ifdef SUPPORT_UCP
1731 if (md->use_ucp)
1732 {
1733 if (c == '_') prev_is_word = TRUE; else
1734 {
1735 int cat = UCD_CATEGORY(c);
1736 prev_is_word = (cat == ucp_L || cat == ucp_N);
1737 }
1738 }
1739 else
1740 #endif
1741 prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0;
1742 }
1743
1744 /* Get status of next character */
1745
1746 if (eptr >= md->end_subject)
1747 {
1748 SCHECK_PARTIAL();
1749 cur_is_word = FALSE;
1750 }
1751 else
1752 {
1753 GETCHAR(c, eptr);
1754 #ifdef SUPPORT_UCP
1755 if (md->use_ucp)
1756 {
1757 if (c == '_') cur_is_word = TRUE; else
1758 {
1759 int cat = UCD_CATEGORY(c);
1760 cur_is_word = (cat == ucp_L || cat == ucp_N);
1761 }
1762 }
1763 else
1764 #endif
1765 cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0;
1766 }
1767 }
1768 else
1769 #endif
1770
1771 /* Not in UTF-8 mode, but we may still have PCRE_UCP set, and for
1772 consistency with the behaviour of \w we do use it in this case. */
1773
1774 {
1775 /* Get status of previous character */
1776
1777 if (eptr == md->start_subject) prev_is_word = FALSE; else
1778 {
1779 if (eptr <= md->start_used_ptr) md->start_used_ptr = eptr - 1;
1780 #ifdef SUPPORT_UCP
1781 if (md->use_ucp)
1782 {
1783 c = eptr[-1];
1784 if (c == '_') prev_is_word = TRUE; else
1785 {
1786 int cat = UCD_CATEGORY(c);
1787 prev_is_word = (cat == ucp_L || cat == ucp_N);
1788 }
1789 }
1790 else
1791 #endif
1792 prev_is_word = ((md->ctypes[eptr[-1]] & ctype_word) != 0);
1793 }
1794
1795 /* Get status of next character */
1796
1797 if (eptr >= md->end_subject)
1798 {
1799 SCHECK_PARTIAL();
1800 cur_is_word = FALSE;
1801 }
1802 else
1803 #ifdef SUPPORT_UCP
1804 if (md->use_ucp)
1805 {
1806 c = *eptr;
1807 if (c == '_') cur_is_word = TRUE; else
1808 {
1809 int cat = UCD_CATEGORY(c);
1810 cur_is_word = (cat == ucp_L || cat == ucp_N);
1811 }
1812 }
1813 else
1814 #endif
1815 cur_is_word = ((md->ctypes[*eptr] & ctype_word) != 0);
1816 }
1817
1818 /* Now see if the situation is what we want */
1819
1820 if ((*ecode++ == OP_WORD_BOUNDARY)?
1821 cur_is_word == prev_is_word : cur_is_word != prev_is_word)
1822 MRRETURN(MATCH_NOMATCH);
1823 }
1824 break;
1825
1826 /* Match a single character type; inline for speed */
1827
1828 case OP_ANY:
1829 if (IS_NEWLINE(eptr)) MRRETURN(MATCH_NOMATCH);
1830 /* Fall through */
1831
1832 case OP_ALLANY:
1833 if (eptr++ >= md->end_subject)
1834 {
1835 SCHECK_PARTIAL();
1836 MRRETURN(MATCH_NOMATCH);
1837 }
1838 if (utf8) while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++;
1839 ecode++;
1840 break;
1841
1842 /* Match a single byte, even in UTF-8 mode. This opcode really does match
1843 any byte, even newline, independent of the setting of PCRE_DOTALL. */
1844
1845 case OP_ANYBYTE:
1846 if (eptr++ >= md->end_subject)
1847 {
1848 SCHECK_PARTIAL();
1849 MRRETURN(MATCH_NOMATCH);
1850 }
1851 ecode++;
1852 break;
1853
1854 case OP_NOT_DIGIT:
1855 if (eptr >= md->end_subject)
1856 {
1857 SCHECK_PARTIAL();
1858 MRRETURN(MATCH_NOMATCH);
1859 }
1860 GETCHARINCTEST(c, eptr);
1861 if (
1862 #ifdef SUPPORT_UTF8
1863 c < 256 &&
1864 #endif
1865 (md->ctypes[c] & ctype_digit) != 0
1866 )
1867 MRRETURN(MATCH_NOMATCH);
1868 ecode++;
1869 break;
1870
1871 case OP_DIGIT:
1872 if (eptr >= md->end_subject)
1873 {
1874 SCHECK_PARTIAL();
1875 MRRETURN(MATCH_NOMATCH);
1876 }
1877 GETCHARINCTEST(c, eptr);
1878 if (
1879 #ifdef SUPPORT_UTF8
1880 c >= 256 ||
1881 #endif
1882 (md->ctypes[c] & ctype_digit) == 0
1883 )
1884 MRRETURN(MATCH_NOMATCH);
1885 ecode++;
1886 break;
1887
1888 case OP_NOT_WHITESPACE:
1889 if (eptr >= md->end_subject)
1890 {
1891 SCHECK_PARTIAL();
1892 MRRETURN(MATCH_NOMATCH);
1893 }
1894 GETCHARINCTEST(c, eptr);
1895 if (
1896 #ifdef SUPPORT_UTF8
1897 c < 256 &&
1898 #endif
1899 (md->ctypes[c] & ctype_space) != 0
1900 )
1901 MRRETURN(MATCH_NOMATCH);
1902 ecode++;
1903 break;
1904
1905 case OP_WHITESPACE:
1906 if (eptr >= md->end_subject)
1907 {
1908 SCHECK_PARTIAL();
1909 MRRETURN(MATCH_NOMATCH);
1910 }
1911 GETCHARINCTEST(c, eptr);
1912 if (
1913 #ifdef SUPPORT_UTF8
1914 c >= 256 ||
1915 #endif
1916 (md->ctypes[c] & ctype_space) == 0
1917 )
1918 MRRETURN(MATCH_NOMATCH);
1919 ecode++;
1920 break;
1921
1922 case OP_NOT_WORDCHAR:
1923 if (eptr >= md->end_subject)
1924 {
1925 SCHECK_PARTIAL();
1926 MRRETURN(MATCH_NOMATCH);
1927 }
1928 GETCHARINCTEST(c, eptr);
1929 if (
1930 #ifdef SUPPORT_UTF8
1931 c < 256 &&
1932 #endif
1933 (md->ctypes[c] & ctype_word) != 0
1934 )
1935 MRRETURN(MATCH_NOMATCH);
1936 ecode++;
1937 break;
1938
1939 case OP_WORDCHAR:
1940 if (eptr >= md->end_subject)
1941 {
1942 SCHECK_PARTIAL();
1943 MRRETURN(MATCH_NOMATCH);
1944 }
1945 GETCHARINCTEST(c, eptr);
1946 if (
1947 #ifdef SUPPORT_UTF8
1948 c >= 256 ||
1949 #endif
1950 (md->ctypes[c] & ctype_word) == 0
1951 )
1952 MRRETURN(MATCH_NOMATCH);
1953 ecode++;
1954 break;
1955
1956 case OP_ANYNL:
1957 if (eptr >= md->end_subject)
1958 {
1959 SCHECK_PARTIAL();
1960 MRRETURN(MATCH_NOMATCH);
1961 }
1962 GETCHARINCTEST(c, eptr);
1963 switch(c)
1964 {
1965 default: MRRETURN(MATCH_NOMATCH);
1966 case 0x000d:
1967 if (eptr < md->end_subject && *eptr == 0x0a) eptr++;
1968 break;
1969
1970 case 0x000a:
1971 break;
1972
1973 case 0x000b:
1974 case 0x000c:
1975 case 0x0085:
1976 case 0x2028:
1977 case 0x2029:
1978 if (md->bsr_anycrlf) MRRETURN(MATCH_NOMATCH);
1979 break;
1980 }
1981 ecode++;
1982 break;
1983
1984 case OP_NOT_HSPACE:
1985 if (eptr >= md->end_subject)
1986 {
1987 SCHECK_PARTIAL();
1988 MRRETURN(MATCH_NOMATCH);
1989 }
1990 GETCHARINCTEST(c, eptr);
1991 switch(c)
1992 {
1993 default: break;
1994 case 0x09: /* HT */
1995 case 0x20: /* SPACE */
1996 case 0xa0: /* NBSP */
1997 case 0x1680: /* OGHAM SPACE MARK */
1998 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
1999 case 0x2000: /* EN QUAD */
2000 case 0x2001: /* EM QUAD */
2001 case 0x2002: /* EN SPACE */
2002 case 0x2003: /* EM SPACE */
2003 case 0x2004: /* THREE-PER-EM SPACE */
2004 case 0x2005: /* FOUR-PER-EM SPACE */
2005 case 0x2006: /* SIX-PER-EM SPACE */
2006 case 0x2007: /* FIGURE SPACE */
2007 case 0x2008: /* PUNCTUATION SPACE */
2008 case 0x2009: /* THIN SPACE */
2009 case 0x200A: /* HAIR SPACE */
2010 case 0x202f: /* NARROW NO-BREAK SPACE */
2011 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
2012 case 0x3000: /* IDEOGRAPHIC SPACE */
2013 MRRETURN(MATCH_NOMATCH);
2014 }
2015 ecode++;
2016 break;
2017
2018 case OP_HSPACE:
2019 if (eptr >= md->end_subject)
2020 {
2021 SCHECK_PARTIAL();
2022 MRRETURN(MATCH_NOMATCH);
2023 }
2024 GETCHARINCTEST(c, eptr);
2025 switch(c)
2026 {
2027 default: MRRETURN(MATCH_NOMATCH);
2028 case 0x09: /* HT */
2029 case 0x20: /* SPACE */
2030 case 0xa0: /* NBSP */
2031 case 0x1680: /* OGHAM SPACE MARK */
2032 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
2033 case 0x2000: /* EN QUAD */
2034 case 0x2001: /* EM QUAD */
2035 case 0x2002: /* EN SPACE */
2036 case 0x2003: /* EM SPACE */
2037 case 0x2004: /* THREE-PER-EM SPACE */
2038 case 0x2005: /* FOUR-PER-EM SPACE */
2039 case 0x2006: /* SIX-PER-EM SPACE */
2040 case 0x2007: /* FIGURE SPACE */
2041 case 0x2008: /* PUNCTUATION SPACE */
2042 case 0x2009: /* THIN SPACE */
2043 case 0x200A: /* HAIR SPACE */
2044 case 0x202f: /* NARROW NO-BREAK SPACE */
2045 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
2046 case 0x3000: /* IDEOGRAPHIC SPACE */
2047 break;
2048 }
2049 ecode++;
2050 break;
2051
2052 case OP_NOT_VSPACE:
2053 if (eptr >= md->end_subject)
2054 {
2055 SCHECK_PARTIAL();
2056 MRRETURN(MATCH_NOMATCH);
2057 }
2058 GETCHARINCTEST(c, eptr);
2059 switch(c)
2060 {
2061 default: break;
2062 case 0x0a: /* LF */
2063 case 0x0b: /* VT */
2064 case 0x0c: /* FF */
2065 case 0x0d: /* CR */
2066 case 0x85: /* NEL */
2067 case 0x2028: /* LINE SEPARATOR */
2068 case 0x2029: /* PARAGRAPH SEPARATOR */
2069 MRRETURN(MATCH_NOMATCH);
2070 }
2071 ecode++;
2072 break;
2073
2074 case OP_VSPACE:
2075 if (eptr >= md->end_subject)
2076 {
2077 SCHECK_PARTIAL();
2078 MRRETURN(MATCH_NOMATCH);
2079 }
2080 GETCHARINCTEST(c, eptr);
2081 switch(c)
2082 {
2083 default: MRRETURN(MATCH_NOMATCH);
2084 case 0x0a: /* LF */
2085 case 0x0b: /* VT */
2086 case 0x0c: /* FF */
2087 case 0x0d: /* CR */
2088 case 0x85: /* NEL */
2089 case 0x2028: /* LINE SEPARATOR */
2090 case 0x2029: /* PARAGRAPH SEPARATOR */
2091 break;
2092 }
2093 ecode++;
2094 break;
2095
2096 #ifdef SUPPORT_UCP
2097 /* Check the next character by Unicode property. We will get here only
2098 if the support is in the binary; otherwise a compile-time error occurs. */
2099
2100 case OP_PROP:
2101 case OP_NOTPROP:
2102 if (eptr >= md->end_subject)
2103 {
2104 SCHECK_PARTIAL();
2105 MRRETURN(MATCH_NOMATCH);
2106 }
2107 GETCHARINCTEST(c, eptr);
2108 {
2109 const ucd_record *prop = GET_UCD(c);
2110
2111 switch(ecode[1])
2112 {
2113 case PT_ANY:
2114 if (op == OP_NOTPROP) MRRETURN(MATCH_NOMATCH);
2115 break;
2116
2117 case PT_LAMP:
2118 if ((prop->chartype == ucp_Lu ||
2119 prop->chartype == ucp_Ll ||
2120 prop->chartype == ucp_Lt) == (op == OP_NOTPROP))
2121 MRRETURN(MATCH_NOMATCH);
2122 break;
2123
2124 case PT_GC:
2125 if ((ecode[2] != _pcre_ucp_gentype[prop->chartype]) == (op == OP_PROP))
2126 MRRETURN(MATCH_NOMATCH);
2127 break;
2128
2129 case PT_PC:
2130 if ((ecode[2] != prop->chartype) == (op == OP_PROP))
2131 MRRETURN(MATCH_NOMATCH);
2132 break;
2133
2134 case PT_SC:
2135 if ((ecode[2] != prop->script) == (op == OP_PROP))
2136 MRRETURN(MATCH_NOMATCH);
2137 break;
2138
2139 /* These are specials */
2140
2141 case PT_ALNUM:
2142 if ((_pcre_ucp_gentype[prop->chartype] == ucp_L ||
2143 _pcre_ucp_gentype[prop->chartype] == ucp_N) == (op == OP_NOTPROP))
2144 MRRETURN(MATCH_NOMATCH);
2145 break;
2146
2147 case PT_SPACE: /* Perl space */
2148 if ((_pcre_ucp_gentype[prop->chartype] == ucp_Z ||
2149 c == CHAR_HT || c == CHAR_NL || c == CHAR_FF || c == CHAR_CR)
2150 == (op == OP_NOTPROP))
2151 MRRETURN(MATCH_NOMATCH);
2152 break;
2153
2154 case PT_PXSPACE: /* POSIX space */
2155 if ((_pcre_ucp_gentype[prop->chartype] == ucp_Z ||
2156 c == CHAR_HT || c == CHAR_NL || c == CHAR_VT ||
2157 c == CHAR_FF || c == CHAR_CR)
2158 == (op == OP_NOTPROP))
2159 MRRETURN(MATCH_NOMATCH);
2160 break;
2161
2162 case PT_WORD:
2163 if ((_pcre_ucp_gentype[prop->chartype] == ucp_L ||
2164 _pcre_ucp_gentype[prop->chartype] == ucp_N ||
2165 c == CHAR_UNDERSCORE) == (op == OP_NOTPROP))
2166 MRRETURN(MATCH_NOMATCH);
2167 break;
2168
2169 /* This should never occur */
2170
2171 default:
2172 RRETURN(PCRE_ERROR_INTERNAL);
2173 }
2174
2175 ecode += 3;
2176 }
2177 break;
2178
2179 /* Match an extended Unicode sequence. We will get here only if the support
2180 is in the binary; otherwise a compile-time error occurs. */
2181
2182 case OP_EXTUNI:
2183 if (eptr >= md->end_subject)
2184 {
2185 SCHECK_PARTIAL();
2186 MRRETURN(MATCH_NOMATCH);
2187 }
2188 GETCHARINCTEST(c, eptr);
2189 {
2190 int category = UCD_CATEGORY(c);
2191 if (category == ucp_M) MRRETURN(MATCH_NOMATCH);
2192 while (eptr < md->end_subject)
2193 {
2194 int len = 1;
2195 if (!utf8) c = *eptr; else
2196 {
2197 GETCHARLEN(c, eptr, len);
2198 }
2199 category = UCD_CATEGORY(c);
2200 if (category != ucp_M) break;
2201 eptr += len;
2202 }
2203 }
2204 ecode++;
2205 break;
2206 #endif
2207
2208
2209 /* Match a back reference, possibly repeatedly. Look past the end of the
2210 item to see if there is repeat information following. The code is similar
2211 to that for character classes, but repeated for efficiency. Then obey
2212 similar code to character type repeats - written out again for speed.
2213 However, if the referenced string is the empty string, always treat
2214 it as matched, any number of times (otherwise there could be infinite
2215 loops). */
2216
2217 case OP_REF:
2218 {
2219 offset = GET2(ecode, 1) << 1; /* Doubled ref number */
2220 ecode += 3;
2221
2222 /* If the reference is unset, there are two possibilities:
2223
2224 (a) In the default, Perl-compatible state, set the length to be longer
2225 than the amount of subject left; this ensures that every attempt at a
2226 match fails. We can't just fail here, because of the possibility of
2227 quantifiers with zero minima.
2228
2229 (b) If the JavaScript compatibility flag is set, set the length to zero
2230 so that the back reference matches an empty string.
2231
2232 Otherwise, set the length to the length of what was matched by the
2233 referenced subpattern. */
2234
2235 if (offset >= offset_top || md->offset_vector[offset] < 0)
2236 length = (md->jscript_compat)? 0 : md->end_subject - eptr + 1;
2237 else
2238 length = md->offset_vector[offset+1] - md->offset_vector[offset];
2239
2240 /* Set up for repetition, or handle the non-repeated case */
2241
2242 switch (*ecode)
2243 {
2244 case OP_CRSTAR:
2245 case OP_CRMINSTAR:
2246 case OP_CRPLUS:
2247 case OP_CRMINPLUS:
2248 case OP_CRQUERY:
2249 case OP_CRMINQUERY:
2250 c = *ecode++ - OP_CRSTAR;
2251 minimize = (c & 1) != 0;
2252 min = rep_min[c]; /* Pick up values from tables; */
2253 max = rep_max[c]; /* zero for max => infinity */
2254 if (max == 0) max = INT_MAX;
2255 break;
2256
2257 case OP_CRRANGE:
2258 case OP_CRMINRANGE:
2259 minimize = (*ecode == OP_CRMINRANGE);
2260 min = GET2(ecode, 1);
2261 max = GET2(ecode, 3);
2262 if (max == 0) max = INT_MAX;
2263 ecode += 5;
2264 break;
2265
2266 default: /* No repeat follows */
2267 if (!match_ref(offset, eptr, length, md, ims))
2268 {
2269 CHECK_PARTIAL();
2270 MRRETURN(MATCH_NOMATCH);
2271 }
2272 eptr += length;
2273 continue; /* With the main loop */
2274 }
2275
2276 /* If the length of the reference is zero, just continue with the
2277 main loop. */
2278
2279 if (length == 0) continue;
2280
2281 /* First, ensure the minimum number of matches are present. We get back
2282 the length of the reference string explicitly rather than passing the
2283 address of eptr, so that eptr can be a register variable. */
2284
2285 for (i = 1; i <= min; i++)
2286 {
2287 if (!match_ref(offset, eptr, length, md, ims))
2288 {
2289 CHECK_PARTIAL();
2290 MRRETURN(MATCH_NOMATCH);
2291 }
2292 eptr += length;
2293 }
2294
2295 /* If min = max, continue at the same level without recursion.
2296 They are not both allowed to be zero. */
2297
2298 if (min == max) continue;
2299
2300 /* If minimizing, keep trying and advancing the pointer */
2301
2302 if (minimize)
2303 {
2304 for (fi = min;; fi++)
2305 {
2306 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM14);
2307 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2308 if (fi >= max) MRRETURN(MATCH_NOMATCH);
2309 if (!match_ref(offset, eptr, length, md, ims))
2310 {
2311 CHECK_PARTIAL();
2312 MRRETURN(MATCH_NOMATCH);
2313 }
2314 eptr += length;
2315 }
2316 /* Control never gets here */
2317 }
2318
2319 /* If maximizing, find the longest string and work backwards */
2320
2321 else
2322 {
2323 pp = eptr;
2324 for (i = min; i < max; i++)
2325 {
2326 if (!match_ref(offset, eptr, length, md, ims))
2327 {
2328 CHECK_PARTIAL();
2329 break;
2330 }
2331 eptr += length;
2332 }
2333 while (eptr >= pp)
2334 {
2335 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM15);
2336 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2337 eptr -= length;
2338 }
2339 MRRETURN(MATCH_NOMATCH);
2340 }
2341 }
2342 /* Control never gets here */
2343
2344 /* Match a bit-mapped character class, possibly repeatedly. This op code is
2345 used when all the characters in the class have values in the range 0-255,
2346 and either the matching is caseful, or the characters are in the range
2347 0-127 when UTF-8 processing is enabled. The only difference between
2348 OP_CLASS and OP_NCLASS occurs when a data character outside the range is
2349 encountered.
2350
2351 First, look past the end of the item to see if there is repeat information
2352 following. Then obey similar code to character type repeats - written out
2353 again for speed. */
2354
2355 case OP_NCLASS:
2356 case OP_CLASS:
2357 {
2358 data = ecode + 1; /* Save for matching */
2359 ecode += 33; /* Advance past the item */
2360
2361 switch (*ecode)
2362 {
2363 case OP_CRSTAR:
2364 case OP_CRMINSTAR:
2365 case OP_CRPLUS:
2366 case OP_CRMINPLUS:
2367 case OP_CRQUERY:
2368 case OP_CRMINQUERY:
2369 c = *ecode++ - OP_CRSTAR;
2370 minimize = (c & 1) != 0;
2371 min = rep_min[c]; /* Pick up values from tables; */
2372 max = rep_max[c]; /* zero for max => infinity */
2373 if (max == 0) max = INT_MAX;
2374 break;
2375
2376 case OP_CRRANGE:
2377 case OP_CRMINRANGE:
2378 minimize = (*ecode == OP_CRMINRANGE);
2379 min = GET2(ecode, 1);
2380 max = GET2(ecode, 3);
2381 if (max == 0) max = INT_MAX;
2382 ecode += 5;
2383 break;
2384
2385 default: /* No repeat follows */
2386 min = max = 1;
2387 break;
2388 }
2389
2390 /* First, ensure the minimum number of matches are present. */
2391
2392 #ifdef SUPPORT_UTF8
2393 /* UTF-8 mode */
2394 if (utf8)
2395 {
2396 for (i = 1; i <= min; i++)
2397 {
2398 if (eptr >= md->end_subject)
2399 {
2400 SCHECK_PARTIAL();
2401 MRRETURN(MATCH_NOMATCH);
2402 }
2403 GETCHARINC(c, eptr);
2404 if (c > 255)
2405 {
2406 if (op == OP_CLASS) MRRETURN(MATCH_NOMATCH);
2407 }
2408 else
2409 {
2410 if ((data[c/8] & (1 << (c&7))) == 0) MRRETURN(MATCH_NOMATCH);
2411 }
2412 }
2413 }
2414 else
2415 #endif
2416 /* Not UTF-8 mode */
2417 {
2418 for (i = 1; i <= min; i++)
2419 {
2420 if (eptr >= md->end_subject)
2421 {
2422 SCHECK_PARTIAL();
2423 MRRETURN(MATCH_NOMATCH);
2424 }
2425 c = *eptr++;
2426 if ((data[c/8] & (1 << (c&7))) == 0) MRRETURN(MATCH_NOMATCH);
2427 }
2428 }
2429
2430 /* If max == min we can continue with the main loop without the
2431 need to recurse. */
2432
2433 if (min == max) continue;
2434
2435 /* If minimizing, keep testing the rest of the expression and advancing
2436 the pointer while it matches the class. */
2437
2438 if (minimize)
2439 {
2440 #ifdef SUPPORT_UTF8
2441 /* UTF-8 mode */
2442 if (utf8)
2443 {
2444 for (fi = min;; fi++)
2445 {
2446 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM16);
2447 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2448 if (fi >= max) MRRETURN(MATCH_NOMATCH);
2449 if (eptr >= md->end_subject)
2450 {
2451 SCHECK_PARTIAL();
2452 MRRETURN(MATCH_NOMATCH);
2453 }
2454 GETCHARINC(c, eptr);
2455 if (c > 255)
2456 {
2457 if (op == OP_CLASS) MRRETURN(MATCH_NOMATCH);
2458 }
2459 else
2460 {
2461 if ((data[c/8] & (1 << (c&7))) == 0) MRRETURN(MATCH_NOMATCH);
2462 }
2463 }
2464 }
2465 else
2466 #endif
2467 /* Not UTF-8 mode */
2468 {
2469 for (fi = min;; fi++)
2470 {
2471 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM17);
2472 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2473 if (fi >= max) MRRETURN(MATCH_NOMATCH);
2474 if (eptr >= md->end_subject)
2475 {
2476 SCHECK_PARTIAL();
2477 MRRETURN(MATCH_NOMATCH);
2478 }
2479 c = *eptr++;
2480 if ((data[c/8] & (1 << (c&7))) == 0) MRRETURN(MATCH_NOMATCH);
2481 }
2482 }
2483 /* Control never gets here */
2484 }
2485
2486 /* If maximizing, find the longest possible run, then work backwards. */
2487
2488 else
2489 {
2490 pp = eptr;
2491
2492 #ifdef SUPPORT_UTF8
2493 /* UTF-8 mode */
2494 if (utf8)
2495 {
2496 for (i = min; i < max; i++)
2497 {
2498 int len = 1;
2499 if (eptr >= md->end_subject)
2500 {
2501 SCHECK_PARTIAL();
2502 break;
2503 }
2504 GETCHARLEN(c, eptr, len);
2505 if (c > 255)
2506 {
2507 if (op == OP_CLASS) break;
2508 }
2509 else
2510 {
2511 if ((data[c/8] & (1 << (c&7))) == 0) break;
2512 }
2513 eptr += len;
2514 }
2515 for (;;)
2516 {
2517 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM18);
2518 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2519 if (eptr-- == pp) break; /* Stop if tried at original pos */
2520 BACKCHAR(eptr);
2521 }
2522 }
2523 else
2524 #endif
2525 /* Not UTF-8 mode */
2526 {
2527 for (i = min; i < max; i++)
2528 {
2529 if (eptr >= md->end_subject)
2530 {
2531 SCHECK_PARTIAL();
2532 break;
2533 }
2534 c = *eptr;
2535 if ((data[c/8] & (1 << (c&7))) == 0) break;
2536 eptr++;
2537 }
2538 while (eptr >= pp)
2539 {
2540 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM19);
2541 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2542 eptr--;
2543 }
2544 }
2545
2546 MRRETURN(MATCH_NOMATCH);
2547 }
2548 }
2549 /* Control never gets here */
2550
2551
2552 /* Match an extended character class. This opcode is encountered only
2553 when UTF-8 mode mode is supported. Nevertheless, we may not be in UTF-8
2554 mode, because Unicode properties are supported in non-UTF-8 mode. */
2555
2556 #ifdef SUPPORT_UTF8
2557 case OP_XCLASS:
2558 {
2559 data = ecode + 1 + LINK_SIZE; /* Save for matching */
2560 ecode += GET(ecode, 1); /* Advance past the item */
2561
2562 switch (*ecode)
2563 {
2564 case OP_CRSTAR:
2565 case OP_CRMINSTAR:
2566 case OP_CRPLUS:
2567 case OP_CRMINPLUS:
2568 case OP_CRQUERY:
2569 case OP_CRMINQUERY:
2570 c = *ecode++ - OP_CRSTAR;
2571 minimize = (c & 1) != 0;
2572 min = rep_min[c]; /* Pick up values from tables; */
2573 max = rep_max[c]; /* zero for max => infinity */
2574 if (max == 0) max = INT_MAX;
2575 break;
2576
2577 case OP_CRRANGE:
2578 case OP_CRMINRANGE:
2579 minimize = (*ecode == OP_CRMINRANGE);
2580 min = GET2(ecode, 1);
2581 max = GET2(ecode, 3);
2582 if (max == 0) max = INT_MAX;
2583 ecode += 5;
2584 break;
2585
2586 default: /* No repeat follows */
2587 min = max = 1;
2588 break;
2589 }
2590
2591 /* First, ensure the minimum number of matches are present. */
2592
2593 for (i = 1; i <= min; i++)
2594 {
2595 if (eptr >= md->end_subject)
2596 {
2597 SCHECK_PARTIAL();
2598 MRRETURN(MATCH_NOMATCH);
2599 }
2600 GETCHARINCTEST(c, eptr);
2601 if (!_pcre_xclass(c, data)) MRRETURN(MATCH_NOMATCH);
2602 }
2603
2604 /* If max == min we can continue with the main loop without the
2605 need to recurse. */
2606
2607 if (min == max) continue;
2608
2609 /* If minimizing, keep testing the rest of the expression and advancing
2610 the pointer while it matches the class. */
2611
2612 if (minimize)
2613 {
2614 for (fi = min;; fi++)
2615 {
2616 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM20);
2617 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2618 if (fi >= max) MRRETURN(MATCH_NOMATCH);
2619 if (eptr >= md->end_subject)
2620 {
2621 SCHECK_PARTIAL();
2622 MRRETURN(MATCH_NOMATCH);
2623 }
2624 GETCHARINCTEST(c, eptr);
2625 if (!_pcre_xclass(c, data)) MRRETURN(MATCH_NOMATCH);
2626 }
2627 /* Control never gets here */
2628 }
2629
2630 /* If maximizing, find the longest possible run, then work backwards. */
2631
2632 else
2633 {
2634 pp = eptr;
2635 for (i = min; i < max; i++)
2636 {
2637 int len = 1;
2638 if (eptr >= md->end_subject)
2639 {
2640 SCHECK_PARTIAL();
2641 break;
2642 }
2643 GETCHARLENTEST(c, eptr, len);
2644 if (!_pcre_xclass(c, data)) break;
2645 eptr += len;
2646 }
2647 for(;;)
2648 {
2649 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM21);
2650 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2651 if (eptr-- == pp) break; /* Stop if tried at original pos */
2652 if (utf8) BACKCHAR(eptr);
2653 }
2654 MRRETURN(MATCH_NOMATCH);
2655 }
2656
2657 /* Control never gets here */
2658 }
2659 #endif /* End of XCLASS */
2660
2661 /* Match a single character, casefully */
2662
2663 case OP_CHAR:
2664 #ifdef SUPPORT_UTF8
2665 if (utf8)
2666 {
2667 length = 1;
2668 ecode++;
2669 GETCHARLEN(fc, ecode, length);
2670 if (length > md->end_subject - eptr)
2671 {
2672 CHECK_PARTIAL(); /* Not SCHECK_PARTIAL() */
2673 MRRETURN(MATCH_NOMATCH);
2674 }
2675 while (length-- > 0) if (*ecode++ != *eptr++) MRRETURN(MATCH_NOMATCH);
2676 }
2677 else
2678 #endif
2679
2680 /* Non-UTF-8 mode */
2681 {
2682 if (md->end_subject - eptr < 1)
2683 {
2684 SCHECK_PARTIAL(); /* This one can use SCHECK_PARTIAL() */
2685 MRRETURN(MATCH_NOMATCH);
2686 }
2687 if (ecode[1] != *eptr++) MRRETURN(MATCH_NOMATCH);
2688 ecode += 2;
2689 }
2690 break;
2691
2692 /* Match a single character, caselessly */
2693
2694 case OP_CHARNC:
2695 #ifdef SUPPORT_UTF8
2696 if (utf8)
2697 {
2698 length = 1;
2699 ecode++;
2700 GETCHARLEN(fc, ecode, length);
2701
2702 if (length > md->end_subject - eptr)
2703 {
2704 CHECK_PARTIAL(); /* Not SCHECK_PARTIAL() */
2705 MRRETURN(MATCH_NOMATCH);
2706 }
2707
2708 /* If the pattern character's value is < 128, we have only one byte, and
2709 can use the fast lookup table. */
2710
2711 if (fc < 128)
2712 {
2713 if (md->lcc[*ecode++] != md->lcc[*eptr++]) MRRETURN(MATCH_NOMATCH);
2714 }
2715
2716 /* Otherwise we must pick up the subject character */
2717
2718 else
2719 {
2720 unsigned int dc;
2721 GETCHARINC(dc, eptr);
2722 ecode += length;
2723
2724 /* If we have Unicode property support, we can use it to test the other
2725 case of the character, if there is one. */
2726
2727 if (fc != dc)
2728 {
2729 #ifdef SUPPORT_UCP
2730 if (dc != UCD_OTHERCASE(fc))
2731 #endif
2732 MRRETURN(MATCH_NOMATCH);
2733 }
2734 }
2735 }
2736 else
2737 #endif /* SUPPORT_UTF8 */
2738
2739 /* Non-UTF-8 mode */
2740 {
2741 if (md->end_subject - eptr < 1)
2742 {
2743 SCHECK_PARTIAL(); /* This one can use SCHECK_PARTIAL() */
2744 MRRETURN(MATCH_NOMATCH);
2745 }
2746 if (md->lcc[ecode[1]] != md->lcc[*eptr++]) MRRETURN(MATCH_NOMATCH);
2747 ecode += 2;
2748 }
2749 break;
2750
2751 /* Match a single character repeatedly. */
2752
2753 case OP_EXACT:
2754 min = max = GET2(ecode, 1);
2755 ecode += 3;
2756 goto REPEATCHAR;
2757
2758 case OP_POSUPTO:
2759 possessive = TRUE;
2760 /* Fall through */
2761
2762 case OP_UPTO:
2763 case OP_MINUPTO:
2764 min = 0;
2765 max = GET2(ecode, 1);
2766 minimize = *ecode == OP_MINUPTO;
2767 ecode += 3;
2768 goto REPEATCHAR;
2769
2770 case OP_POSSTAR:
2771 possessive = TRUE;
2772 min = 0;
2773 max = INT_MAX;
2774 ecode++;
2775 goto REPEATCHAR;
2776
2777 case OP_POSPLUS:
2778 possessive = TRUE;
2779 min = 1;
2780 max = INT_MAX;
2781 ecode++;
2782 goto REPEATCHAR;
2783
2784 case OP_POSQUERY:
2785 possessive = TRUE;
2786 min = 0;
2787 max = 1;
2788 ecode++;
2789 goto REPEATCHAR;
2790
2791 case OP_STAR:
2792 case OP_MINSTAR:
2793 case OP_PLUS:
2794 case OP_MINPLUS:
2795 case OP_QUERY:
2796 case OP_MINQUERY:
2797 c = *ecode++ - OP_STAR;
2798 minimize = (c & 1) != 0;
2799
2800 min = rep_min[c]; /* Pick up values from tables; */
2801 max = rep_max[c]; /* zero for max => infinity */
2802 if (max == 0) max = INT_MAX;
2803
2804 /* Common code for all repeated single-character matches. */
2805
2806 REPEATCHAR:
2807 #ifdef SUPPORT_UTF8
2808 if (utf8)
2809 {
2810 length = 1;
2811 charptr = ecode;
2812 GETCHARLEN(fc, ecode, length);
2813 ecode += length;
2814
2815 /* Handle multibyte character matching specially here. There is
2816 support for caseless matching if UCP support is present. */
2817
2818 if (length > 1)
2819 {
2820 #ifdef SUPPORT_UCP
2821 unsigned int othercase;
2822 if ((ims & PCRE_CASELESS) != 0 &&
2823 (othercase = UCD_OTHERCASE(fc)) != fc)
2824 oclength = _pcre_ord2utf8(othercase, occhars);
2825 else oclength = 0;
2826 #endif /* SUPPORT_UCP */
2827
2828 for (i = 1; i <= min; i++)
2829 {
2830 if (eptr <= md->end_subject - length &&
2831 memcmp(eptr, charptr, length) == 0) eptr += length;
2832 #ifdef SUPPORT_UCP
2833 else if (oclength > 0 &&
2834 eptr <= md->end_subject - oclength &&
2835 memcmp(eptr, occhars, oclength) == 0) eptr += oclength;
2836 #endif /* SUPPORT_UCP */
2837 else
2838 {
2839 CHECK_PARTIAL();
2840 MRRETURN(MATCH_NOMATCH);
2841 }
2842 }
2843
2844 if (min == max) continue;
2845
2846 if (minimize)
2847 {
2848 for (fi = min;; fi++)
2849 {
2850 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM22);
2851 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2852 if (fi >= max) MRRETURN(MATCH_NOMATCH);
2853 if (eptr <= md->end_subject - length &&
2854 memcmp(eptr, charptr, length) == 0) eptr += length;
2855 #ifdef SUPPORT_UCP
2856 else if (oclength > 0 &&
2857 eptr <= md->end_subject - oclength &&
2858 memcmp(eptr, occhars, oclength) == 0) eptr += oclength;
2859 #endif /* SUPPORT_UCP */
2860 else
2861 {
2862 CHECK_PARTIAL();
2863 MRRETURN(MATCH_NOMATCH);
2864 }
2865 }
2866 /* Control never gets here */
2867 }
2868
2869 else /* Maximize */
2870 {
2871 pp = eptr;
2872 for (i = min; i < max; i++)
2873 {
2874 if (eptr <= md->end_subject - length &&
2875 memcmp(eptr, charptr, length) == 0) eptr += length;
2876 #ifdef SUPPORT_UCP
2877 else if (oclength > 0 &&
2878 eptr <= md->end_subject - oclength &&
2879 memcmp(eptr, occhars, oclength) == 0) eptr += oclength;
2880 #endif /* SUPPORT_UCP */
2881 else
2882 {
2883 CHECK_PARTIAL();
2884 break;
2885 }
2886 }
2887
2888 if (possessive) continue;
2889
2890 for(;;)
2891 {
2892 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM23);
2893 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2894 if (eptr == pp) { MRRETURN(MATCH_NOMATCH); }
2895 #ifdef SUPPORT_UCP
2896 eptr--;
2897 BACKCHAR(eptr);
2898 #else /* without SUPPORT_UCP */
2899 eptr -= length;
2900 #endif /* SUPPORT_UCP */
2901 }
2902 }
2903 /* Control never gets here */
2904 }
2905
2906 /* If the length of a UTF-8 character is 1, we fall through here, and
2907 obey the code as for non-UTF-8 characters below, though in this case the
2908 value of fc will always be < 128. */
2909 }
2910 else
2911 #endif /* SUPPORT_UTF8 */
2912
2913 /* When not in UTF-8 mode, load a single-byte character. */
2914
2915 fc = *ecode++;
2916
2917 /* The value of fc at this point is always less than 256, though we may or
2918 may not be in UTF-8 mode. The code is duplicated for the caseless and
2919 caseful cases, for speed, since matching characters is likely to be quite
2920 common. First, ensure the minimum number of matches are present. If min =
2921 max, continue at the same level without recursing. Otherwise, if
2922 minimizing, keep trying the rest of the expression and advancing one
2923 matching character if failing, up to the maximum. Alternatively, if
2924 maximizing, find the maximum number of characters and work backwards. */
2925
2926 DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max,
2927 max, eptr));
2928
2929 if ((ims & PCRE_CASELESS) != 0)
2930 {
2931 fc = md->lcc[fc];
2932 for (i = 1; i <= min; i++)
2933 {
2934 if (eptr >= md->end_subject)
2935 {
2936 SCHECK_PARTIAL();
2937 MRRETURN(MATCH_NOMATCH);
2938 }
2939 if (fc != md->lcc[*eptr++]) MRRETURN(MATCH_NOMATCH);
2940 }
2941 if (min == max) continue;
2942 if (minimize)
2943 {
2944 for (fi = min;; fi++)
2945 {
2946 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM24);
2947 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2948 if (fi >= max) MRRETURN(MATCH_NOMATCH);
2949 if (eptr >= md->end_subject)
2950 {
2951 SCHECK_PARTIAL();
2952 MRRETURN(MATCH_NOMATCH);
2953 }
2954 if (fc != md->lcc[*eptr++]) MRRETURN(MATCH_NOMATCH);
2955 }
2956 /* Control never gets here */
2957 }
2958 else /* Maximize */
2959 {
2960 pp = eptr;
2961 for (i = min; i < max; i++)
2962 {
2963 if (eptr >= md->end_subject)
2964 {
2965 SCHECK_PARTIAL();
2966 break;
2967 }
2968 if (fc != md->lcc[*eptr]) break;
2969 eptr++;
2970 }
2971
2972 if (possessive) continue;
2973
2974 while (eptr >= pp)
2975 {
2976 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM25);
2977 eptr--;
2978 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
2979 }
2980 MRRETURN(MATCH_NOMATCH);
2981 }
2982 /* Control never gets here */
2983 }
2984
2985 /* Caseful comparisons (includes all multi-byte characters) */
2986
2987 else
2988 {
2989 for (i = 1; i <= min; i++)
2990 {
2991 if (eptr >= md->end_subject)
2992 {
2993 SCHECK_PARTIAL();
2994 MRRETURN(MATCH_NOMATCH);
2995 }
2996 if (fc != *eptr++) MRRETURN(MATCH_NOMATCH);
2997 }
2998
2999 if (min == max) continue;
3000
3001 if (minimize)
3002 {
3003 for (fi = min;; fi++)
3004 {
3005 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM26);
3006 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3007 if (fi >= max) MRRETURN(MATCH_NOMATCH);
3008 if (eptr >= md->end_subject)
3009 {
3010 SCHECK_PARTIAL();
3011 MRRETURN(MATCH_NOMATCH);
3012 }
3013 if (fc != *eptr++) MRRETURN(MATCH_NOMATCH);
3014 }
3015 /* Control never gets here */
3016 }
3017 else /* Maximize */
3018 {
3019 pp = eptr;
3020 for (i = min; i < max; i++)
3021 {
3022 if (eptr >= md->end_subject)
3023 {
3024 SCHECK_PARTIAL();
3025 break;
3026 }
3027 if (fc != *eptr) break;
3028 eptr++;
3029 }
3030 if (possessive) continue;
3031
3032 while (eptr >= pp)
3033 {
3034 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM27);
3035 eptr--;
3036 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3037 }
3038 MRRETURN(MATCH_NOMATCH);
3039 }
3040 }
3041 /* Control never gets here */
3042
3043 /* Match a negated single one-byte character. The character we are
3044 checking can be multibyte. */
3045
3046 case OP_NOT:
3047 if (eptr >= md->end_subject)
3048 {
3049 SCHECK_PARTIAL();
3050 MRRETURN(MATCH_NOMATCH);
3051 }
3052 ecode++;
3053 GETCHARINCTEST(c, eptr);
3054 if ((ims & PCRE_CASELESS) != 0)
3055 {
3056 #ifdef SUPPORT_UTF8
3057 if (c < 256)
3058 #endif
3059 c = md->lcc[c];
3060 if (md->lcc[*ecode++] == c) MRRETURN(MATCH_NOMATCH);
3061 }
3062 else
3063 {
3064 if (*ecode++ == c) MRRETURN(MATCH_NOMATCH);
3065 }
3066 break;
3067
3068 /* Match a negated single one-byte character repeatedly. This is almost a
3069 repeat of the code for a repeated single character, but I haven't found a
3070 nice way of commoning these up that doesn't require a test of the
3071 positive/negative option for each character match. Maybe that wouldn't add
3072 very much to the time taken, but character matching *is* what this is all
3073 about... */
3074
3075 case OP_NOTEXACT:
3076 min = max = GET2(ecode, 1);
3077 ecode += 3;
3078 goto REPEATNOTCHAR;
3079
3080 case OP_NOTUPTO:
3081 case OP_NOTMINUPTO:
3082 min = 0;
3083 max = GET2(ecode, 1);
3084 minimize = *ecode == OP_NOTMINUPTO;
3085 ecode += 3;
3086 goto REPEATNOTCHAR;
3087
3088 case OP_NOTPOSSTAR:
3089 possessive = TRUE;
3090 min = 0;
3091 max = INT_MAX;
3092 ecode++;
3093 goto REPEATNOTCHAR;
3094
3095 case OP_NOTPOSPLUS:
3096 possessive = TRUE;
3097 min = 1;
3098 max = INT_MAX;
3099 ecode++;
3100 goto REPEATNOTCHAR;
3101
3102 case OP_NOTPOSQUERY:
3103 possessive = TRUE;
3104 min = 0;
3105 max = 1;
3106 ecode++;
3107 goto REPEATNOTCHAR;
3108
3109 case OP_NOTPOSUPTO:
3110 possessive = TRUE;
3111 min = 0;
3112 max = GET2(ecode, 1);
3113 ecode += 3;
3114 goto REPEATNOTCHAR;
3115
3116 case OP_NOTSTAR:
3117 case OP_NOTMINSTAR:
3118 case OP_NOTPLUS:
3119 case OP_NOTMINPLUS:
3120 case OP_NOTQUERY:
3121 case OP_NOTMINQUERY:
3122 c = *ecode++ - OP_NOTSTAR;
3123 minimize = (c & 1) != 0;
3124 min = rep_min[c]; /* Pick up values from tables; */
3125 max = rep_max[c]; /* zero for max => infinity */
3126 if (max == 0) max = INT_MAX;
3127
3128 /* Common code for all repeated single-byte matches. */
3129
3130 REPEATNOTCHAR:
3131 fc = *ecode++;
3132
3133 /* The code is duplicated for the caseless and caseful cases, for speed,
3134 since matching characters is likely to be quite common. First, ensure the
3135 minimum number of matches are present. If min = max, continue at the same
3136 level without recursing. Otherwise, if minimizing, keep trying the rest of
3137 the expression and advancing one matching character if failing, up to the
3138 maximum. Alternatively, if maximizing, find the maximum number of
3139 characters and work backwards. */
3140
3141 DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max,
3142 max, eptr));
3143
3144 if ((ims & PCRE_CASELESS) != 0)
3145 {
3146 fc = md->lcc[fc];
3147
3148 #ifdef SUPPORT_UTF8
3149 /* UTF-8 mode */
3150 if (utf8)
3151 {
3152 register unsigned int d;
3153 for (i = 1; i <= min; i++)
3154 {
3155 if (eptr >= md->end_subject)
3156 {
3157 SCHECK_PARTIAL();
3158 MRRETURN(MATCH_NOMATCH);
3159 }
3160 GETCHARINC(d, eptr);
3161 if (d < 256) d = md->lcc[d];
3162 if (fc == d) MRRETURN(MATCH_NOMATCH);
3163 }
3164 }
3165 else
3166 #endif
3167
3168 /* Not UTF-8 mode */
3169 {
3170 for (i = 1; i <= min; i++)
3171 {
3172 if (eptr >= md->end_subject)
3173 {
3174 SCHECK_PARTIAL();
3175 MRRETURN(MATCH_NOMATCH);
3176 }
3177 if (fc == md->lcc[*eptr++]) MRRETURN(MATCH_NOMATCH);
3178 }
3179 }
3180
3181 if (min == max) continue;
3182
3183 if (minimize)
3184 {
3185 #ifdef SUPPORT_UTF8
3186 /* UTF-8 mode */
3187 if (utf8)
3188 {
3189 register unsigned int d;
3190 for (fi = min;; fi++)
3191 {
3192 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM28);
3193 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3194 if (fi >= max) MRRETURN(MATCH_NOMATCH);
3195 if (eptr >= md->end_subject)
3196 {
3197 SCHECK_PARTIAL();
3198 MRRETURN(MATCH_NOMATCH);
3199 }
3200 GETCHARINC(d, eptr);
3201 if (d < 256) d = md->lcc[d];
3202 if (fc == d) MRRETURN(MATCH_NOMATCH);
3203 }
3204 }
3205 else
3206 #endif
3207 /* Not UTF-8 mode */
3208 {
3209 for (fi = min;; fi++)
3210 {
3211 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM29);
3212 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3213 if (fi >= max) MRRETURN(MATCH_NOMATCH);
3214 if (eptr >= md->end_subject)
3215 {
3216 SCHECK_PARTIAL();
3217 MRRETURN(MATCH_NOMATCH);
3218 }
3219 if (fc == md->lcc[*eptr++]) MRRETURN(MATCH_NOMATCH);
3220 }
3221 }
3222 /* Control never gets here */
3223 }
3224
3225 /* Maximize case */
3226
3227 else
3228 {
3229 pp = eptr;
3230
3231 #ifdef SUPPORT_UTF8
3232 /* UTF-8 mode */
3233 if (utf8)
3234 {
3235 register unsigned int d;
3236 for (i = min; i < max; i++)
3237 {
3238 int len = 1;
3239 if (eptr >= md->end_subject)
3240 {
3241 SCHECK_PARTIAL();
3242 break;
3243 }
3244 GETCHARLEN(d, eptr, len);
3245 if (d < 256) d = md->lcc[d];
3246 if (fc == d) break;
3247 eptr += len;
3248 }
3249 if (possessive) continue;
3250 for(;;)
3251 {
3252 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM30);
3253 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3254 if (eptr-- == pp) break; /* Stop if tried at original pos */
3255 BACKCHAR(eptr);
3256 }
3257 }
3258 else
3259 #endif
3260 /* Not UTF-8 mode */
3261 {
3262 for (i = min; i < max; i++)
3263 {
3264 if (eptr >= md->end_subject)
3265 {
3266 SCHECK_PARTIAL();
3267 break;
3268 }
3269 if (fc == md->lcc[*eptr]) break;
3270 eptr++;
3271 }
3272 if (possessive) continue;
3273 while (eptr >= pp)
3274 {
3275 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM31);
3276 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3277 eptr--;
3278 }
3279 }
3280
3281 MRRETURN(MATCH_NOMATCH);
3282 }
3283 /* Control never gets here */
3284 }
3285
3286 /* Caseful comparisons */
3287
3288 else
3289 {
3290 #ifdef SUPPORT_UTF8
3291 /* UTF-8 mode */
3292 if (utf8)
3293 {
3294 register unsigned int d;
3295 for (i = 1; i <= min; i++)
3296 {
3297 if (eptr >= md->end_subject)
3298 {
3299 SCHECK_PARTIAL();
3300 MRRETURN(MATCH_NOMATCH);
3301 }
3302 GETCHARINC(d, eptr);
3303 if (fc == d) MRRETURN(MATCH_NOMATCH);
3304 }
3305 }
3306 else
3307 #endif
3308 /* Not UTF-8 mode */
3309 {
3310 for (i = 1; i <= min; i++)
3311 {
3312 if (eptr >= md->end_subject)
3313 {
3314 SCHECK_PARTIAL();
3315 MRRETURN(MATCH_NOMATCH);
3316 }
3317 if (fc == *eptr++) MRRETURN(MATCH_NOMATCH);
3318 }
3319 }
3320
3321 if (min == max) continue;
3322
3323 if (minimize)
3324 {
3325 #ifdef SUPPORT_UTF8
3326 /* UTF-8 mode */
3327 if (utf8)
3328 {
3329 register unsigned int d;
3330 for (fi = min;; fi++)
3331 {
3332 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM32);
3333 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3334 if (fi >= max) MRRETURN(MATCH_NOMATCH);
3335 if (eptr >= md->end_subject)
3336 {
3337 SCHECK_PARTIAL();
3338 MRRETURN(MATCH_NOMATCH);
3339 }
3340 GETCHARINC(d, eptr);
3341 if (fc == d) MRRETURN(MATCH_NOMATCH);
3342 }
3343 }
3344 else
3345 #endif
3346 /* Not UTF-8 mode */
3347 {
3348 for (fi = min;; fi++)
3349 {
3350 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM33);
3351 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3352 if (fi >= max) MRRETURN(MATCH_NOMATCH);
3353 if (eptr >= md->end_subject)
3354 {
3355 SCHECK_PARTIAL();
3356 MRRETURN(MATCH_NOMATCH);
3357 }
3358 if (fc == *eptr++) MRRETURN(MATCH_NOMATCH);
3359 }
3360 }
3361 /* Control never gets here */
3362 }
3363
3364 /* Maximize case */
3365
3366 else
3367 {
3368 pp = eptr;
3369
3370 #ifdef SUPPORT_UTF8
3371 /* UTF-8 mode */
3372 if (utf8)
3373 {
3374 register unsigned int d;
3375 for (i = min; i < max; i++)
3376 {
3377 int len = 1;
3378 if (eptr >= md->end_subject)
3379 {
3380 SCHECK_PARTIAL();
3381 break;
3382 }
3383 GETCHARLEN(d, eptr, len);
3384 if (fc == d) break;
3385 eptr += len;
3386 }
3387 if (possessive) continue;
3388 for(;;)
3389 {
3390 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM34);
3391 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3392 if (eptr-- == pp) break; /* Stop if tried at original pos */
3393 BACKCHAR(eptr);
3394 }
3395 }
3396 else
3397 #endif
3398 /* Not UTF-8 mode */
3399 {
3400 for (i = min; i < max; i++)
3401 {
3402 if (eptr >= md->end_subject)
3403 {
3404 SCHECK_PARTIAL();
3405 break;
3406 }
3407 if (fc == *eptr) break;
3408 eptr++;
3409 }
3410 if (possessive) continue;
3411 while (eptr >= pp)
3412 {
3413 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM35);
3414 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
3415 eptr--;
3416 }
3417 }
3418
3419 MRRETURN(MATCH_NOMATCH);
3420 }
3421 }
3422 /* Control never gets here */
3423
3424 /* Match a single character type repeatedly; several different opcodes
3425 share code. This is very similar to the code for single characters, but we
3426 repeat it in the interests of efficiency. */
3427
3428 case OP_TYPEEXACT:
3429 min = max = GET2(ecode, 1);
3430 minimize = TRUE;
3431 ecode += 3;
3432 goto REPEATTYPE;
3433
3434 case OP_TYPEUPTO:
3435 case OP_TYPEMINUPTO:
3436 min = 0;
3437 max = GET2(ecode, 1);
3438 minimize = *ecode == OP_TYPEMINUPTO;
3439 ecode += 3;
3440 goto REPEATTYPE;
3441
3442 case OP_TYPEPOSSTAR:
3443 possessive = TRUE;
3444 min = 0;
3445 max = INT_MAX;
3446 ecode++;
3447 goto REPEATTYPE;
3448
3449 case OP_TYPEPOSPLUS:
3450 possessive = TRUE;
3451 min = 1;
3452 max = INT_MAX;
3453 ecode++;
3454 goto REPEATTYPE;
3455
3456 case OP_TYPEPOSQUERY:
3457 possessive = TRUE;
3458 min = 0;
3459 max = 1;
3460 ecode++;
3461 goto REPEATTYPE;
3462
3463 case OP_TYPEPOSUPTO:
3464 possessive = TRUE;
3465 min = 0;
3466 max = GET2(ecode, 1);
3467 ecode += 3;
3468 goto REPEATTYPE;
3469
3470 case OP_TYPESTAR:
3471 case OP_TYPEMINSTAR:
3472 case OP_TYPEPLUS:
3473 case OP_TYPEMINPLUS:
3474 case OP_TYPEQUERY:
3475 case OP_TYPEMINQUERY:
3476 c = *ecode++ - OP_TYPESTAR;
3477 minimize = (c & 1) != 0;
3478 min = rep_min[c]; /* Pick up values from tables; */
3479 max = rep_max[c]; /* zero for max => infinity */
3480 if (max == 0) max = INT_MAX;
3481
3482 /* Common code for all repeated single character type matches. Note that
3483 in UTF-8 mode, '.' matches a character of any length, but for the other
3484 character types, the valid characters are all one-byte long. */
3485
3486 REPEATTYPE:
3487 ctype = *ecode++; /* Code for the character type */
3488
3489 #ifdef SUPPORT_UCP
3490 if (ctype == OP_PROP || ctype == OP_NOTPROP)
3491 {
3492 prop_fail_result = ctype == OP_NOTPROP;
3493 prop_type = *ecode++;
3494 prop_value = *ecode++;
3495 }
3496 else prop_type = -1;
3497 #endif
3498
3499 /* First, ensure the minimum number of matches are present. Use inline
3500 code for maximizing the speed, and do the type test once at the start
3501 (i.e. keep it out of the loop). Separate the UTF-8 code completely as that
3502 is tidier. Also separate the UCP code, which can be the same for both UTF-8
3503 and single-bytes. */
3504
3505 if (min > 0)
3506 {
3507 #ifdef SUPPORT_UCP
3508 if (prop_type >= 0)
3509 {
3510 switch(prop_type)
3511 {
3512 case PT_ANY:
3513 if (prop_fail_result) MRRETURN(MATCH_NOMATCH);
3514 for (i = 1; i <= min; i++)
3515 {
3516 if (eptr >= md->end_subject)
3517 {
3518 SCHECK_PARTIAL();
3519 MRRETURN(MATCH_NOMATCH);
3520 }
3521 GETCHARINCTEST(c, eptr);
3522 }
3523 break;
3524
3525 case PT_LAMP:
3526 for (i = 1; i <= min; i++)
3527 {
3528 if (eptr >= md->end_subject)
3529 {
3530 SCHECK_PARTIAL();
3531 MRRETURN(MATCH_NOMATCH);
3532 }
3533 GETCHARINCTEST(c, eptr);
3534 prop_chartype = UCD_CHARTYPE(c);
3535 if ((prop_chartype == ucp_Lu ||
3536 prop_chartype == ucp_Ll ||
3537 prop_chartype == ucp_Lt) == prop_fail_result)
3538 MRRETURN(MATCH_NOMATCH);
3539 }
3540 break;
3541
3542 case PT_GC:
3543 for (i = 1; i <= min; i++)
3544 {
3545 if (eptr >= md->end_subject)
3546 {
3547 SCHECK_PARTIAL();
3548 MRRETURN(MATCH_NOMATCH);
3549 }
3550 GETCHARINCTEST(c, eptr);
3551 prop_category = UCD_CATEGORY(c);
3552 if ((prop_category == prop_value) == prop_fail_result)
3553 MRRETURN(MATCH_NOMATCH);
3554 }
3555 break;
3556
3557 case PT_PC:
3558 for (i = 1; i <= min; i++)
3559 {
3560 if (eptr >= md->end_subject)
3561 {
3562 SCHECK_PARTIAL();
3563 MRRETURN(MATCH_NOMATCH);
3564 }
3565 GETCHARINCTEST(c, eptr);
3566 prop_chartype = UCD_CHARTYPE(c);
3567 if ((prop_chartype == prop_value) == prop_fail_result)
3568 MRRETURN(MATCH_NOMATCH);
3569 }
3570 break;
3571
3572 case PT_SC:
3573 for (i = 1; i <= min; i++)
3574 {
3575 if (eptr >= md->end_subject)
3576 {
3577 SCHECK_PARTIAL();
3578 MRRETURN(MATCH_NOMATCH);
3579 }
3580 GETCHARINCTEST(c, eptr);
3581 prop_script = UCD_SCRIPT(c);
3582 if ((prop_script == prop_value) == prop_fail_result)
3583 MRRETURN(MATCH_NOMATCH);
3584 }
3585 break;
3586
3587 case PT_ALNUM:
3588 for (i = 1; i <= min; i++)
3589 {
3590 if (eptr >= md->end_subject)
3591 {
3592 SCHECK_PARTIAL();
3593 MRRETURN(MATCH_NOMATCH);
3594 }
3595 GETCHARINCTEST(c, eptr);
3596 prop_category = UCD_CATEGORY(c);
3597 if ((prop_category == ucp_L || prop_category == ucp_N)
3598 == prop_fail_result)
3599 MRRETURN(MATCH_NOMATCH);
3600 }
3601 break;
3602
3603 case PT_SPACE: /* Perl space */
3604 for (i = 1; i <= min; i++)
3605 {
3606 if (eptr >= md->end_subject)
3607 {
3608 SCHECK_PARTIAL();
3609 MRRETURN(MATCH_NOMATCH);
3610 }
3611 GETCHARINCTEST(c, eptr);
3612 prop_category = UCD_CATEGORY(c);
3613 if ((prop_category == ucp_Z || c == CHAR_HT || c == CHAR_NL ||
3614 c == CHAR_FF || c == CHAR_CR)
3615 == prop_fail_result)
3616 MRRETURN(MATCH_NOMATCH);
3617 }
3618 break;
3619
3620 case PT_PXSPACE: /* POSIX space */
3621 for (i = 1; i <= min; i++)
3622 {
3623 if (eptr >= md->end_subject)
3624 {
3625 SCHECK_PARTIAL();
3626 MRRETURN(MATCH_NOMATCH);
3627 }
3628 GETCHARINCTEST(c, eptr);
3629 prop_category = UCD_CATEGORY(c);
3630 if ((prop_category == ucp_Z || c == CHAR_HT || c == CHAR_NL ||
3631 c == CHAR_VT || c == CHAR_FF || c == CHAR_CR)
3632 == prop_fail_result)
3633 MRRETURN(MATCH_NOMATCH);
3634 }
3635 break;
3636
3637 case PT_WORD:
3638 for (i = 1; i <= min; i++)
3639 {
3640 if (eptr >= md->end_subject)
3641 {
3642 SCHECK_PARTIAL();
3643 MRRETURN(MATCH_NOMATCH);
3644 }
3645 GETCHARINCTEST(c, eptr);
3646 prop_category = UCD_CATEGORY(c);
3647 if ((prop_category == ucp_L || prop_category == ucp_N ||
3648 c == CHAR_UNDERSCORE)
3649 == prop_fail_result)
3650 MRRETURN(MATCH_NOMATCH);
3651 }
3652 break;
3653
3654 /* This should not occur */
3655
3656 default:
3657 RRETURN(PCRE_ERROR_INTERNAL);
3658 }
3659 }
3660
3661 /* Match extended Unicode sequences. We will get here only if the
3662 support is in the binary; otherwise a compile-time error occurs. */
3663
3664 else if (ctype == OP_EXTUNI)
3665 {
3666 for (i = 1; i <= min; i++)
3667 {
3668 if (eptr >= md->end_subject)
3669 {
3670 SCHECK_PARTIAL();
3671 MRRETURN(MATCH_NOMATCH);
3672 }
3673 GETCHARINCTEST(c, eptr);
3674 prop_category = UCD_CATEGORY(c);
3675 if (prop_category == ucp_M) MRRETURN(MATCH_NOMATCH);
3676 while (eptr < md->end_subject)
3677 {
3678 int len = 1;
3679 if (!utf8) c = *eptr;
3680 else { GETCHARLEN(c, eptr, len); }
3681 prop_category = UCD_CATEGORY(c);
3682 if (prop_category != ucp_M) break;
3683 eptr += len;
3684 }
3685 }
3686 }
3687
3688 else
3689 #endif /* SUPPORT_UCP */
3690
3691 /* Handle all other cases when the coding is UTF-8 */
3692
3693 #ifdef SUPPORT_UTF8
3694 if (utf8) switch(ctype)
3695 {
3696 case OP_ANY:
3697 for (i = 1; i <= min; i++)
3698 {
3699 if (eptr >= md->end_subject)
3700 {
3701 SCHECK_PARTIAL();
3702 MRRETURN(MATCH_NOMATCH);
3703 }
3704 if (IS_NEWLINE(eptr)) MRRETURN(MATCH_NOMATCH);
3705 eptr++;
3706 while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++;
3707 }
3708 break;
3709
3710 case OP_ALLANY:
3711 for (i = 1; i <= min; i++)
3712 {
3713 if (eptr >= md->end_subject)
3714 {
3715 SCHECK_PARTIAL();
3716 MRRETURN(MATCH_NOMATCH);
3717 }
3718 eptr++;
3719 while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++;
3720 }
3721 break;
3722
3723 case OP_ANYBYTE:
3724 if (eptr > md->end_subject - min) MRRETURN(MATCH_NOMATCH);
3725 eptr += min;
3726 break;
3727
3728 case OP_ANYNL:
3729 for (i = 1; i <= min; i++)
3730 {
3731 if (eptr >= md->end_subject)
3732 {
3733 SCHECK_PARTIAL();
3734 MRRETURN(MATCH_NOMATCH);
3735 }
3736 GETCHARINC(c, eptr);
3737 switch(c)
3738 {
3739 default: MRRETURN(MATCH_NOMATCH);
3740 case 0x000d:
3741 if (eptr < md->end_subject && *eptr == 0x0a) eptr++;
3742 break;
3743
3744 case 0x000a:
3745 break;
3746
3747 case 0x000b:
3748 case 0x000c:
3749 case 0x0085:
3750 case 0x2028:
3751 case 0x2029:
3752 if (md->bsr_anycrlf) MRRETURN(MATCH_NOMATCH);
3753 break;
3754 }
3755 }
3756 break;
3757
3758 case OP_NOT_HSPACE:
3759 for (i = 1; i <= min; i++)
3760 {
3761 if (eptr >= md->end_subject)
3762 {
3763 SCHECK_PARTIAL();
3764 MRRETURN(MATCH_NOMATCH);
3765 }
3766 GETCHARINC(c, eptr);
3767 switch(c)
3768 {
3769 default: break;
3770 case 0x09: /* HT */
3771 case 0x20: /* SPACE */
3772 case 0xa0: /* NBSP */
3773 case 0x1680: /* OGHAM SPACE MARK */
3774 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
3775 case 0x2000: /* EN QUAD */
3776 case 0x2001: /* EM QUAD */
3777 case 0x2002: /* EN SPACE */
3778 case 0x2003: /* EM SPACE */
3779 case 0x2004: /* THREE-PER-EM SPACE */
3780 case 0x2005: /* FOUR-PER-EM SPACE */
3781 case 0x2006: /* SIX-PER-EM SPACE */
3782 case 0x2007: /* FIGURE SPACE */
3783 case 0x2008: /* PUNCTUATION SPACE */
3784 case 0x2009: /* THIN SPACE */
3785 case 0x200A: /* HAIR SPACE */
3786 case 0x202f: /* NARROW NO-BREAK SPACE */
3787 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
3788 case 0x3000: /* IDEOGRAPHIC SPACE */
3789 MRRETURN(MATCH_NOMATCH);
3790 }
3791 }
3792 break;
3793
3794 case OP_HSPACE:
3795 for (i = 1; i <= min; i++)
3796 {
3797 if (eptr >= md->end_subject)
3798 {
3799 SCHECK_PARTIAL();
3800 MRRETURN(MATCH_NOMATCH);
3801 }
3802 GETCHARINC(c, eptr);
3803 switch(c)
3804 {
3805 default: MRRETURN(MATCH_NOMATCH);
3806 case 0x09: /* HT */
3807 case 0x20: /* SPACE */
3808 case 0xa0: /* NBSP */
3809 case 0x1680: /* OGHAM SPACE MARK */
3810 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
3811 case 0x2000: /* EN QUAD */
3812 case 0x2001: /* EM QUAD */
3813 case 0x2002: /* EN SPACE */
3814 case 0x2003: /* EM SPACE */
3815 case 0x2004: /* THREE-PER-EM SPACE */
3816 case 0x2005: /* FOUR-PER-EM SPACE */
3817 case 0x2006: /* SIX-PER-EM SPACE */
3818 case 0x2007: /* FIGURE SPACE */
3819 case 0x2008: /* PUNCTUATION SPACE */
3820 case 0x2009: /* THIN SPACE */
3821 case 0x200A: /* HAIR SPACE */
3822 case 0x202f: /* NARROW NO-BREAK SPACE */
3823 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
3824 case 0x3000: /* IDEOGRAPHIC SPACE */
3825 break;
3826 }
3827 }
3828 break;
3829
3830 case OP_NOT_VSPACE:
3831 for (i = 1; i <= min; i++)
3832 {
3833 if (eptr >= md->end_subject)
3834 {
3835 SCHECK_PARTIAL();
3836 MRRETURN(MATCH_NOMATCH);
3837 }
3838 GETCHARINC(c, eptr);
3839 switch(c)
3840 {
3841 default: break;
3842 case 0x0a: /* LF */
3843 case 0x0b: /* VT */
3844 case 0x0c: /* FF */
3845 case 0x0d: /* CR */
3846 case 0x85: /* NEL */
3847 case 0x2028: /* LINE SEPARATOR */
3848 case 0x2029: /* PARAGRAPH SEPARATOR */
3849 MRRETURN(MATCH_NOMATCH);
3850 }
3851 }
3852 break;
3853
3854 case OP_VSPACE:
3855 for (i = 1; i <= min; i++)
3856 {
3857 if (eptr >= md->end_subject)
3858 {
3859 SCHECK_PARTIAL();
3860 MRRETURN(MATCH_NOMATCH);
3861 }
3862 GETCHARINC(c, eptr);
3863 switch(c)
3864 {
3865 default: MRRETURN(MATCH_NOMATCH);
3866 case 0x0a: /* LF */
3867 case 0x0b: /* VT */
3868 case 0x0c: /* FF */
3869 case 0x0d: /* CR */
3870 case 0x85: /* NEL */
3871 case 0x2028: /* LINE SEPARATOR */
3872 case 0x2029: /* PARAGRAPH SEPARATOR */
3873 break;
3874 }
3875 }
3876 break;
3877
3878 case OP_NOT_DIGIT:
3879 for (i = 1; i <= min; i++)
3880 {
3881 if (eptr >= md->end_subject)
3882 {
3883 SCHECK_PARTIAL();
3884 MRRETURN(MATCH_NOMATCH);
3885 }
3886 GETCHARINC(c, eptr);
3887 if (c < 128 && (md->ctypes[c] & ctype_digit) != 0)
3888 MRRETURN(MATCH_NOMATCH);
3889 }
3890 break;
3891
3892 case OP_DIGIT:
3893 for (i = 1; i <= min; i++)
3894 {
3895 if (eptr >= md->end_subject)
3896 {
3897 SCHECK_PARTIAL();
3898 MRRETURN(MATCH_NOMATCH);
3899 }
3900 if (*eptr >= 128 || (md->ctypes[*eptr++] & ctype_digit) == 0)
3901 MRRETURN(MATCH_NOMATCH);
3902 /* No need to skip more bytes - we know it's a 1-byte character */
3903 }
3904 break;
3905
3906 case OP_NOT_WHITESPACE:
3907 for (i = 1; i <= min; i++)
3908 {
3909 if (eptr >= md->end_subject)
3910 {
3911 SCHECK_PARTIAL();
3912 MRRETURN(MATCH_NOMATCH);
3913 }
3914 if (*eptr < 128 && (md->ctypes[*eptr] & ctype_space) != 0)
3915 MRRETURN(MATCH_NOMATCH);
3916 while (++eptr < md->end_subject && (*eptr & 0xc0) == 0x80);
3917 }
3918 break;
3919
3920 case OP_WHITESPACE:
3921 for (i = 1; i <= min; i++)
3922 {
3923 if (eptr >= md->end_subject)
3924 {
3925 SCHECK_PARTIAL();
3926 MRRETURN(MATCH_NOMATCH);
3927 }
3928 if (*eptr >= 128 || (md->ctypes[*eptr++] & ctype_space) == 0)
3929 MRRETURN(MATCH_NOMATCH);
3930 /* No need to skip more bytes - we know it's a 1-byte character */
3931 }
3932 break;
3933
3934 case OP_NOT_WORDCHAR:
3935 for (i = 1; i <= min; i++)
3936 {
3937 if (eptr >= md->end_subject)
3938 {
3939 SCHECK_PARTIAL();
3940 MRRETURN(MATCH_NOMATCH);
3941 }
3942 if (*eptr < 128 && (md->ctypes[*eptr] & ctype_word) != 0)
3943 MRRETURN(MATCH_NOMATCH);
3944 while (++eptr < md->end_subject && (*eptr & 0xc0) == 0x80);
3945 }
3946 break;
3947
3948 case OP_WORDCHAR:
3949 for (i = 1; i <= min; i++)
3950 {
3951 if (eptr >= md->end_subject)
3952 {
3953 SCHECK_PARTIAL();
3954 MRRETURN(MATCH_NOMATCH);
3955 }
3956 if (*eptr >= 128 || (md->ctypes[*eptr++] & ctype_word) == 0)
3957 MRRETURN(MATCH_NOMATCH);
3958 /* No need to skip more bytes - we know it's a 1-byte character */
3959 }
3960 break;
3961
3962 default:
3963 RRETURN(PCRE_ERROR_INTERNAL);
3964 } /* End switch(ctype) */
3965
3966 else
3967 #endif /* SUPPORT_UTF8 */
3968
3969 /* Code for the non-UTF-8 case for minimum matching of operators other
3970 than OP_PROP and OP_NOTPROP. */
3971
3972 switch(ctype)
3973 {
3974 case OP_ANY:
3975 for (i = 1; i <= min; i++)
3976 {
3977 if (eptr >= md->end_subject)
3978 {
3979 SCHECK_PARTIAL();
3980 MRRETURN(MATCH_NOMATCH);
3981 }
3982 if (IS_NEWLINE(eptr)) MRRETURN(MATCH_NOMATCH);
3983 eptr++;
3984 }
3985 break;
3986
3987 case OP_ALLANY:
3988 if (eptr > md->end_subject - min)
3989 {
3990 SCHECK_PARTIAL();
3991 MRRETURN(MATCH_NOMATCH);
3992 }
3993 eptr += min;
3994 break;
3995
3996 case OP_ANYBYTE:
3997 if (eptr > md->end_subject - min)
3998 {
3999 SCHECK_PARTIAL();
4000 MRRETURN(MATCH_NOMATCH);
4001 }
4002 eptr += min;
4003 break;
4004
4005 case OP_ANYNL:
4006 for (i = 1; i <= min; i++)
4007 {
4008 if (eptr >= md->end_subject)
4009 {
4010 SCHECK_PARTIAL();
4011 MRRETURN(MATCH_NOMATCH);
4012 }
4013 switch(*eptr++)
4014 {
4015 default: MRRETURN(MATCH_NOMATCH);
4016 case 0x000d:
4017 if (eptr < md->end_subject && *eptr == 0x0a) eptr++;
4018 break;
4019 case 0x000a:
4020 break;
4021
4022 case 0x000b:
4023 case 0x000c:
4024 case 0x0085:
4025 if (md->bsr_anycrlf) MRRETURN(MATCH_NOMATCH);
4026 break;
4027 }
4028 }
4029 break;
4030
4031 case OP_NOT_HSPACE:
4032 for (i = 1; i <= min; i++)
4033 {
4034 if (eptr >= md->end_subject)
4035 {
4036 SCHECK_PARTIAL();
4037 MRRETURN(MATCH_NOMATCH);
4038 }
4039 switch(*eptr++)
4040 {
4041 default: break;
4042 case 0x09: /* HT */
4043 case 0x20: /* SPACE */
4044 case 0xa0: /* NBSP */
4045 MRRETURN(MATCH_NOMATCH);
4046 }
4047 }
4048 break;
4049
4050 case OP_HSPACE:
4051 for (i = 1; i <= min; i++)
4052 {
4053 if (eptr >= md->end_subject)
4054 {
4055 SCHECK_PARTIAL();
4056 MRRETURN(MATCH_NOMATCH);
4057 }
4058 switch(*eptr++)
4059 {
4060 default: MRRETURN(MATCH_NOMATCH);
4061 case 0x09: /* HT */
4062 case 0x20: /* SPACE */
4063 case 0xa0: /* NBSP */
4064 break;
4065 }
4066 }
4067 break;
4068
4069 case OP_NOT_VSPACE:
4070 for (i = 1; i <= min; i++)
4071 {
4072 if (eptr >= md->end_subject)
4073 {
4074 SCHECK_PARTIAL();
4075 MRRETURN(MATCH_NOMATCH);
4076 }
4077 switch(*eptr++)
4078 {
4079 default: break;
4080 case 0x0a: /* LF */
4081 case 0x0b: /* VT */
4082 case 0x0c: /* FF */
4083 case 0x0d: /* CR */
4084 case 0x85: /* NEL */
4085 MRRETURN(MATCH_NOMATCH);
4086 }
4087 }
4088 break;
4089
4090 case OP_VSPACE:
4091 for (i = 1; i <= min; i++)
4092 {
4093 if (eptr >= md->end_subject)
4094 {
4095 SCHECK_PARTIAL();
4096 MRRETURN(MATCH_NOMATCH);
4097 }
4098 switch(*eptr++)
4099 {
4100 default: MRRETURN(MATCH_NOMATCH);
4101 case 0x0a: /* LF */
4102 case 0x0b: /* VT */
4103 case 0x0c: /* FF */
4104 case 0x0d: /* CR */
4105 case 0x85: /* NEL */
4106 break;
4107 }
4108 }
4109 break;
4110
4111 case OP_NOT_DIGIT:
4112 for (i = 1; i <= min; i++)
4113 {
4114 if (eptr >= md->end_subject)
4115 {
4116 SCHECK_PARTIAL();
4117 MRRETURN(MATCH_NOMATCH);
4118 }
4119 if ((md->ctypes[*eptr++] & ctype_digit) != 0) MRRETURN(MATCH_NOMATCH);
4120 }
4121 break;
4122
4123 case OP_DIGIT:
4124 for (i = 1; i <= min; i++)
4125 {
4126 if (eptr >= md->end_subject)
4127 {
4128 SCHECK_PARTIAL();
4129 MRRETURN(MATCH_NOMATCH);
4130 }
4131 if ((md->ctypes[*eptr++] & ctype_digit) == 0) MRRETURN(MATCH_NOMATCH);
4132 }
4133 break;
4134
4135 case OP_NOT_WHITESPACE:
4136 for (i = 1; i <= min; i++)
4137 {
4138 if (eptr >= md->end_subject)
4139 {
4140 SCHECK_PARTIAL();
4141 MRRETURN(MATCH_NOMATCH);
4142 }
4143 if ((md->ctypes[*eptr++] & ctype_space) != 0) MRRETURN(MATCH_NOMATCH);
4144 }
4145 break;
4146
4147 case OP_WHITESPACE:
4148 for (i = 1; i <= min; i++)
4149 {
4150 if (eptr >= md->end_subject)
4151 {
4152 SCHECK_PARTIAL();
4153 MRRETURN(MATCH_NOMATCH);
4154 }
4155 if ((md->ctypes[*eptr++] & ctype_space) == 0) MRRETURN(MATCH_NOMATCH);
4156 }
4157 break;
4158
4159 case OP_NOT_WORDCHAR:
4160 for (i = 1; i <= min; i++)
4161 {
4162 if (eptr >= md->end_subject)
4163 {
4164 SCHECK_PARTIAL();
4165 MRRETURN(MATCH_NOMATCH);
4166 }
4167 if ((md->ctypes[*eptr++] & ctype_word) != 0)
4168 MRRETURN(MATCH_NOMATCH);
4169 }
4170 break;
4171
4172 case OP_WORDCHAR:
4173 for (i = 1; i <= min; i++)
4174 {
4175 if (eptr >= md->end_subject)
4176 {
4177 SCHECK_PARTIAL();
4178 MRRETURN(MATCH_NOMATCH);
4179 }
4180 if ((md->ctypes[*eptr++] & ctype_word) == 0)
4181 MRRETURN(MATCH_NOMATCH);
4182 }
4183 break;
4184
4185 default:
4186 RRETURN(PCRE_ERROR_INTERNAL);
4187 }
4188 }
4189
4190 /* If min = max, continue at the same level without recursing */
4191
4192 if (min == max) continue;
4193
4194 /* If minimizing, we have to test the rest of the pattern before each
4195 subsequent match. Again, separate the UTF-8 case for speed, and also
4196 separate the UCP cases. */
4197
4198 if (minimize)
4199 {
4200 #ifdef SUPPORT_UCP
4201 if (prop_type >= 0)
4202 {
4203 switch(prop_type)
4204 {
4205 case PT_ANY:
4206 for (fi = min;; fi++)
4207 {
4208 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM36);
4209 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4210 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4211 if (eptr >= md->end_subject)
4212 {
4213 SCHECK_PARTIAL();
4214 MRRETURN(MATCH_NOMATCH);
4215 }
4216 GETCHARINC(c, eptr);
4217 if (prop_fail_result) MRRETURN(MATCH_NOMATCH);
4218 }
4219 /* Control never gets here */
4220
4221 case PT_LAMP:
4222 for (fi = min;; fi++)
4223 {
4224 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM37);
4225 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4226 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4227 if (eptr >= md->end_subject)
4228 {
4229 SCHECK_PARTIAL();
4230 MRRETURN(MATCH_NOMATCH);
4231 }
4232 GETCHARINC(c, eptr);
4233 prop_chartype = UCD_CHARTYPE(c);
4234 if ((prop_chartype == ucp_Lu ||
4235 prop_chartype == ucp_Ll ||
4236 prop_chartype == ucp_Lt) == prop_fail_result)
4237 MRRETURN(MATCH_NOMATCH);
4238 }
4239 /* Control never gets here */
4240
4241 case PT_GC:
4242 for (fi = min;; fi++)
4243 {
4244 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM38);
4245 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4246 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4247 if (eptr >= md->end_subject)
4248 {
4249 SCHECK_PARTIAL();
4250 MRRETURN(MATCH_NOMATCH);
4251 }
4252 GETCHARINC(c, eptr);
4253 prop_category = UCD_CATEGORY(c);
4254 if ((prop_category == prop_value) == prop_fail_result)
4255 MRRETURN(MATCH_NOMATCH);
4256 }
4257 /* Control never gets here */
4258
4259 case PT_PC:
4260 for (fi = min;; fi++)
4261 {
4262 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM39);
4263 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4264 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4265 if (eptr >= md->end_subject)
4266 {
4267 SCHECK_PARTIAL();
4268 MRRETURN(MATCH_NOMATCH);
4269 }
4270 GETCHARINC(c, eptr);
4271 prop_chartype = UCD_CHARTYPE(c);
4272 if ((prop_chartype == prop_value) == prop_fail_result)
4273 MRRETURN(MATCH_NOMATCH);
4274 }
4275 /* Control never gets here */
4276
4277 case PT_SC:
4278 for (fi = min;; fi++)
4279 {
4280 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM40);
4281 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4282 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4283 if (eptr >= md->end_subject)
4284 {
4285 SCHECK_PARTIAL();
4286 MRRETURN(MATCH_NOMATCH);
4287 }
4288 GETCHARINC(c, eptr);
4289 prop_script = UCD_SCRIPT(c);
4290 if ((prop_script == prop_value) == prop_fail_result)
4291 MRRETURN(MATCH_NOMATCH);
4292 }
4293 /* Control never gets here */
4294
4295 case PT_ALNUM:
4296 for (fi = min;; fi++)
4297 {
4298 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM59);
4299 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4300 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4301 if (eptr >= md->end_subject)
4302 {
4303 SCHECK_PARTIAL();
4304 MRRETURN(MATCH_NOMATCH);
4305 }
4306 GETCHARINC(c, eptr);
4307 prop_category = UCD_CATEGORY(c);
4308 if ((prop_category == ucp_L || prop_category == ucp_N)
4309 == prop_fail_result)
4310 MRRETURN(MATCH_NOMATCH);
4311 }
4312 /* Control never gets here */
4313
4314 case PT_SPACE: /* Perl space */
4315 for (fi = min;; fi++)
4316 {
4317 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM60);
4318 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4319 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4320 if (eptr >= md->end_subject)
4321 {
4322 SCHECK_PARTIAL();
4323 MRRETURN(MATCH_NOMATCH);
4324 }
4325 GETCHARINC(c, eptr);
4326 prop_category = UCD_CATEGORY(c);
4327 if ((prop_category == ucp_Z || c == CHAR_HT || c == CHAR_NL ||
4328 c == CHAR_FF || c == CHAR_CR)
4329 == prop_fail_result)
4330 MRRETURN(MATCH_NOMATCH);
4331 }
4332 /* Control never gets here */
4333
4334 case PT_PXSPACE: /* POSIX space */
4335 for (fi = min;; fi++)
4336 {
4337 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM61);
4338 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4339 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4340 if (eptr >= md->end_subject)
4341 {
4342 SCHECK_PARTIAL();
4343 MRRETURN(MATCH_NOMATCH);
4344 }
4345 GETCHARINC(c, eptr);
4346 prop_category = UCD_CATEGORY(c);
4347 if ((prop_category == ucp_Z || c == CHAR_HT || c == CHAR_NL ||
4348 c == CHAR_VT || c == CHAR_FF || c == CHAR_CR)
4349 == prop_fail_result)
4350 MRRETURN(MATCH_NOMATCH);
4351 }
4352 /* Control never gets here */
4353
4354 case PT_WORD:
4355 for (fi = min;; fi++)
4356 {
4357 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM62);
4358 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4359 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4360 if (eptr >= md->end_subject)
4361 {
4362 SCHECK_PARTIAL();
4363 MRRETURN(MATCH_NOMATCH);
4364 }
4365 GETCHARINC(c, eptr);
4366 prop_category = UCD_CATEGORY(c);
4367 if ((prop_category == ucp_L ||
4368 prop_category == ucp_N ||
4369 c == CHAR_UNDERSCORE)
4370 == prop_fail_result)
4371 MRRETURN(MATCH_NOMATCH);
4372 }
4373 /* Control never gets here */
4374
4375 /* This should never occur */
4376
4377 default:
4378 RRETURN(PCRE_ERROR_INTERNAL);
4379 }
4380 }
4381
4382 /* Match extended Unicode sequences. We will get here only if the
4383 support is in the binary; otherwise a compile-time error occurs. */
4384
4385 else if (ctype == OP_EXTUNI)
4386 {
4387 for (fi = min;; fi++)
4388 {
4389 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM41);
4390 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4391 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4392 if (eptr >= md->end_subject)
4393 {
4394 SCHECK_PARTIAL();
4395 MRRETURN(MATCH_NOMATCH);
4396 }
4397 GETCHARINCTEST(c, eptr);
4398 prop_category = UCD_CATEGORY(c);
4399 if (prop_category == ucp_M) MRRETURN(MATCH_NOMATCH);
4400 while (eptr < md->end_subject)
4401 {
4402 int len = 1;
4403 if (!utf8) c = *eptr;
4404 else { GETCHARLEN(c, eptr, len); }
4405 prop_category = UCD_CATEGORY(c);
4406 if (prop_category != ucp_M) break;
4407 eptr += len;
4408 }
4409 }
4410 }
4411
4412 else
4413 #endif /* SUPPORT_UCP */
4414
4415 #ifdef SUPPORT_UTF8
4416 /* UTF-8 mode */
4417 if (utf8)
4418 {
4419 for (fi = min;; fi++)
4420 {
4421 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM42);
4422 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4423 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4424 if (eptr >= md->end_subject)
4425 {
4426 SCHECK_PARTIAL();
4427 MRRETURN(MATCH_NOMATCH);
4428 }
4429 if (ctype == OP_ANY && IS_NEWLINE(eptr))
4430 MRRETURN(MATCH_NOMATCH);
4431 GETCHARINC(c, eptr);
4432 switch(ctype)
4433 {
4434 case OP_ANY: /* This is the non-NL case */
4435 case OP_ALLANY:
4436 case OP_ANYBYTE:
4437 break;
4438
4439 case OP_ANYNL:
4440 switch(c)
4441 {
4442 default: MRRETURN(MATCH_NOMATCH);
4443 case 0x000d:
4444 if (eptr < md->end_subject && *eptr == 0x0a) eptr++;
4445 break;
4446 case 0x000a:
4447 break;
4448
4449 case 0x000b:
4450 case 0x000c:
4451 case 0x0085:
4452 case 0x2028:
4453 case 0x2029:
4454 if (md->bsr_anycrlf) MRRETURN(MATCH_NOMATCH);
4455 break;
4456 }
4457 break;
4458
4459 case OP_NOT_HSPACE:
4460 switch(c)
4461 {
4462 default: break;
4463 case 0x09: /* HT */
4464 case 0x20: /* SPACE */
4465 case 0xa0: /* NBSP */
4466 case 0x1680: /* OGHAM SPACE MARK */
4467 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
4468 case 0x2000: /* EN QUAD */
4469 case 0x2001: /* EM QUAD */
4470 case 0x2002: /* EN SPACE */
4471 case 0x2003: /* EM SPACE */
4472 case 0x2004: /* THREE-PER-EM SPACE */
4473 case 0x2005: /* FOUR-PER-EM SPACE */
4474 case 0x2006: /* SIX-PER-EM SPACE */
4475 case 0x2007: /* FIGURE SPACE */
4476 case 0x2008: /* PUNCTUATION SPACE */
4477 case 0x2009: /* THIN SPACE */
4478 case 0x200A: /* HAIR SPACE */
4479 case 0x202f: /* NARROW NO-BREAK SPACE */
4480 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
4481 case 0x3000: /* IDEOGRAPHIC SPACE */
4482 MRRETURN(MATCH_NOMATCH);
4483 }
4484 break;
4485
4486 case OP_HSPACE:
4487 switch(c)
4488 {
4489 default: MRRETURN(MATCH_NOMATCH);
4490 case 0x09: /* HT */
4491 case 0x20: /* SPACE */
4492 case 0xa0: /* NBSP */
4493 case 0x1680: /* OGHAM SPACE MARK */
4494 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
4495 case 0x2000: /* EN QUAD */
4496 case 0x2001: /* EM QUAD */
4497 case 0x2002: /* EN SPACE */
4498 case 0x2003: /* EM SPACE */
4499 case 0x2004: /* THREE-PER-EM SPACE */
4500 case 0x2005: /* FOUR-PER-EM SPACE */
4501 case 0x2006: /* SIX-PER-EM SPACE */
4502 case 0x2007: /* FIGURE SPACE */
4503 case 0x2008: /* PUNCTUATION SPACE */
4504 case 0x2009: /* THIN SPACE */
4505 case 0x200A: /* HAIR SPACE */
4506 case 0x202f: /* NARROW NO-BREAK SPACE */
4507 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
4508 case 0x3000: /* IDEOGRAPHIC SPACE */
4509 break;
4510 }
4511 break;
4512
4513 case OP_NOT_VSPACE:
4514 switch(c)
4515 {
4516 default: break;
4517 case 0x0a: /* LF */
4518 case 0x0b: /* VT */
4519 case 0x0c: /* FF */
4520 case 0x0d: /* CR */
4521 case 0x85: /* NEL */
4522 case 0x2028: /* LINE SEPARATOR */
4523 case 0x2029: /* PARAGRAPH SEPARATOR */
4524 MRRETURN(MATCH_NOMATCH);
4525 }
4526 break;
4527
4528 case OP_VSPACE:
4529 switch(c)
4530 {
4531 default: MRRETURN(MATCH_NOMATCH);
4532 case 0x0a: /* LF */
4533 case 0x0b: /* VT */
4534 case 0x0c: /* FF */
4535 case 0x0d: /* CR */
4536 case 0x85: /* NEL */
4537 case 0x2028: /* LINE SEPARATOR */
4538 case 0x2029: /* PARAGRAPH SEPARATOR */
4539 break;
4540 }
4541 break;
4542
4543 case OP_NOT_DIGIT:
4544 if (c < 256 && (md->ctypes[c] & ctype_digit) != 0)
4545 MRRETURN(MATCH_NOMATCH);
4546 break;
4547
4548 case OP_DIGIT:
4549 if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0)
4550 MRRETURN(MATCH_NOMATCH);
4551 break;
4552
4553 case OP_NOT_WHITESPACE:
4554 if (c < 256 && (md->ctypes[c] & ctype_space) != 0)
4555 MRRETURN(MATCH_NOMATCH);
4556 break;
4557
4558 case OP_WHITESPACE:
4559 if (c >= 256 || (md->ctypes[c] & ctype_space) == 0)
4560 MRRETURN(MATCH_NOMATCH);
4561 break;
4562
4563 case OP_NOT_WORDCHAR:
4564 if (c < 256 && (md->ctypes[c] & ctype_word) != 0)
4565 MRRETURN(MATCH_NOMATCH);
4566 break;
4567
4568 case OP_WORDCHAR:
4569 if (c >= 256 || (md->ctypes[c] & ctype_word) == 0)
4570 MRRETURN(MATCH_NOMATCH);
4571 break;
4572
4573 default:
4574 RRETURN(PCRE_ERROR_INTERNAL);
4575 }
4576 }
4577 }
4578 else
4579 #endif
4580 /* Not UTF-8 mode */
4581 {
4582 for (fi = min;; fi++)
4583 {
4584 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM43);
4585 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4586 if (fi >= max) MRRETURN(MATCH_NOMATCH);
4587 if (eptr >= md->end_subject)
4588 {
4589 SCHECK_PARTIAL();
4590 MRRETURN(MATCH_NOMATCH);
4591 }
4592 if (ctype == OP_ANY && IS_NEWLINE(eptr))
4593 MRRETURN(MATCH_NOMATCH);
4594 c = *eptr++;
4595 switch(ctype)
4596 {
4597 case OP_ANY: /* This is the non-NL case */
4598 case OP_ALLANY:
4599 case OP_ANYBYTE:
4600 break;
4601
4602 case OP_ANYNL:
4603 switch(c)
4604 {
4605 default: MRRETURN(MATCH_NOMATCH);
4606 case 0x000d:
4607 if (eptr < md->end_subject && *eptr == 0x0a) eptr++;
4608 break;
4609
4610 case 0x000a:
4611 break;
4612
4613 case 0x000b:
4614 case 0x000c:
4615 case 0x0085:
4616 if (md->bsr_anycrlf) MRRETURN(MATCH_NOMATCH);
4617 break;
4618 }
4619 break;
4620
4621 case OP_NOT_HSPACE:
4622 switch(c)
4623 {
4624 default: break;
4625 case 0x09: /* HT */
4626 case 0x20: /* SPACE */
4627 case 0xa0: /* NBSP */
4628 MRRETURN(MATCH_NOMATCH);
4629 }
4630 break;
4631
4632 case OP_HSPACE:
4633 switch(c)
4634 {
4635 default: MRRETURN(MATCH_NOMATCH);
4636 case 0x09: /* HT */
4637 case 0x20: /* SPACE */
4638 case 0xa0: /* NBSP */
4639 break;
4640 }
4641 break;
4642
4643 case OP_NOT_VSPACE:
4644 switch(c)
4645 {
4646 default: break;
4647 case 0x0a: /* LF */
4648 case 0x0b: /* VT */
4649 case 0x0c: /* FF */
4650 case 0x0d: /* CR */
4651 case 0x85: /* NEL */
4652 MRRETURN(MATCH_NOMATCH);
4653 }
4654 break;
4655
4656 case OP_VSPACE:
4657 switch(c)
4658 {
4659 default: MRRETURN(MATCH_NOMATCH);
4660 case 0x0a: /* LF */
4661 case 0x0b: /* VT */
4662 case 0x0c: /* FF */
4663 case 0x0d: /* CR */
4664 case 0x85: /* NEL */
4665 break;
4666 }
4667 break;
4668
4669 case OP_NOT_DIGIT:
4670 if ((md->ctypes[c] & ctype_digit) != 0) MRRETURN(MATCH_NOMATCH);
4671 break;
4672
4673 case OP_DIGIT:
4674 if ((md->ctypes[c] & ctype_digit) == 0) MRRETURN(MATCH_NOMATCH);
4675 break;
4676
4677 case OP_NOT_WHITESPACE:
4678 if ((md->ctypes[c] & ctype_space) != 0) MRRETURN(MATCH_NOMATCH);
4679 break;
4680
4681 case OP_WHITESPACE:
4682 if ((md->ctypes[c] & ctype_space) == 0) MRRETURN(MATCH_NOMATCH);
4683 break;
4684
4685 case OP_NOT_WORDCHAR:
4686 if ((md->ctypes[c] & ctype_word) != 0) MRRETURN(MATCH_NOMATCH);
4687 break;
4688
4689 case OP_WORDCHAR:
4690 if ((md->ctypes[c] & ctype_word) == 0) MRRETURN(MATCH_NOMATCH);
4691 break;
4692
4693 default:
4694 RRETURN(PCRE_ERROR_INTERNAL);
4695 }
4696 }
4697 }
4698 /* Control never gets here */
4699 }
4700
4701 /* If maximizing, it is worth using inline code for speed, doing the type
4702 test once at the start (i.e. keep it out of the loop). Again, keep the
4703 UTF-8 and UCP stuff separate. */
4704
4705 else
4706 {
4707 pp = eptr; /* Remember where we started */
4708
4709 #ifdef SUPPORT_UCP
4710 if (prop_type >= 0)
4711 {
4712 switch(prop_type)
4713 {
4714 case PT_ANY:
4715 for (i = min; i < max; i++)
4716 {
4717 int len = 1;
4718 if (eptr >= md->end_subject)
4719 {
4720 SCHECK_PARTIAL();
4721 break;
4722 }
4723 GETCHARLEN(c, eptr, len);
4724 if (prop_fail_result) break;
4725 eptr+= len;
4726 }
4727 break;
4728
4729 case PT_LAMP:
4730 for (i = min; i < max; i++)
4731 {
4732 int len = 1;
4733 if (eptr >= md->end_subject)
4734 {
4735 SCHECK_PARTIAL();
4736 break;
4737 }
4738 GETCHARLEN(c, eptr, len);
4739 prop_chartype = UCD_CHARTYPE(c);
4740 if ((prop_chartype == ucp_Lu ||
4741 prop_chartype == ucp_Ll ||
4742 prop_chartype == ucp_Lt) == prop_fail_result)
4743 break;
4744 eptr+= len;
4745 }
4746 break;
4747
4748 case PT_GC:
4749 for (i = min; i < max; i++)
4750 {
4751 int len = 1;
4752 if (eptr >= md->end_subject)
4753 {
4754 SCHECK_PARTIAL();
4755 break;
4756 }
4757 GETCHARLEN(c, eptr, len);
4758 prop_category = UCD_CATEGORY(c);
4759 if ((prop_category == prop_value) == prop_fail_result)
4760 break;
4761 eptr+= len;
4762 }
4763 break;
4764
4765 case PT_PC:
4766 for (i = min; i < max; i++)
4767 {
4768 int len = 1;
4769 if (eptr >= md->end_subject)
4770 {
4771 SCHECK_PARTIAL();
4772 break;
4773 }
4774 GETCHARLEN(c, eptr, len);
4775 prop_chartype = UCD_CHARTYPE(c);
4776 if ((prop_chartype == prop_value) == prop_fail_result)
4777 break;
4778 eptr+= len;
4779 }
4780 break;
4781
4782 case PT_SC:
4783 for (i = min; i < max; i++)
4784 {
4785 int len = 1;
4786 if (eptr >= md->end_subject)
4787 {
4788 SCHECK_PARTIAL();
4789 break;
4790 }
4791 GETCHARLEN(c, eptr, len);
4792 prop_script = UCD_SCRIPT(c);
4793 if ((prop_script == prop_value) == prop_fail_result)
4794 break;
4795 eptr+= len;
4796 }
4797 break;
4798
4799 case PT_ALNUM:
4800 for (i = min; i < max; i++)
4801 {
4802 int len = 1;
4803 if (eptr >= md->end_subject)
4804 {
4805 SCHECK_PARTIAL();
4806 break;
4807 }
4808 GETCHARLEN(c, eptr, len);
4809 prop_category = UCD_CATEGORY(c);
4810 if ((prop_category == ucp_L || prop_category == ucp_N)
4811 == prop_fail_result)
4812 break;
4813 eptr+= len;
4814 }
4815 break;
4816
4817 case PT_SPACE: /* Perl space */
4818 for (i = min; i < max; i++)
4819 {
4820 int len = 1;
4821 if (eptr >= md->end_subject)
4822 {
4823 SCHECK_PARTIAL();
4824 break;
4825 }
4826 GETCHARLEN(c, eptr, len);
4827 prop_category = UCD_CATEGORY(c);
4828 if ((prop_category == ucp_Z || c == CHAR_HT || c == CHAR_NL ||
4829 c == CHAR_FF || c == CHAR_CR)
4830 == prop_fail_result)
4831 break;
4832 eptr+= len;
4833 }
4834 break;
4835
4836 case PT_PXSPACE: /* POSIX space */
4837 for (i = min; i < max; i++)
4838 {
4839 int len = 1;
4840 if (eptr >= md->end_subject)
4841 {
4842 SCHECK_PARTIAL();
4843 break;
4844 }
4845 GETCHARLEN(c, eptr, len);
4846 prop_category = UCD_CATEGORY(c);
4847 if ((prop_category == ucp_Z || c == CHAR_HT || c == CHAR_NL ||
4848 c == CHAR_VT || c == CHAR_FF || c == CHAR_CR)
4849 == prop_fail_result)
4850 break;
4851 eptr+= len;
4852 }
4853 break;
4854
4855 case PT_WORD:
4856 for (i = min; i < max; i++)
4857 {
4858 int len = 1;
4859 if (eptr >= md->end_subject)
4860 {
4861 SCHECK_PARTIAL();
4862 break;
4863 }
4864 GETCHARLEN(c, eptr, len);
4865 prop_category = UCD_CATEGORY(c);
4866 if ((prop_category == ucp_L || prop_category == ucp_N ||
4867 c == CHAR_UNDERSCORE) == prop_fail_result)
4868 break;
4869 eptr+= len;
4870 }
4871 break;
4872
4873 default:
4874 RRETURN(PCRE_ERROR_INTERNAL);
4875 }
4876
4877 /* eptr is now past the end of the maximum run */
4878
4879 if (possessive) continue;
4880 for(;;)
4881 {
4882 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM44);
4883 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4884 if (eptr-- == pp) break; /* Stop if tried at original pos */
4885 if (utf8) BACKCHAR(eptr);
4886 }
4887 }
4888
4889 /* Match extended Unicode sequences. We will get here only if the
4890 support is in the binary; otherwise a compile-time error occurs. */
4891
4892 else if (ctype == OP_EXTUNI)
4893 {
4894 for (i = min; i < max; i++)
4895 {
4896 if (eptr >= md->end_subject)
4897 {
4898 SCHECK_PARTIAL();
4899 break;
4900 }
4901 GETCHARINCTEST(c, eptr);
4902 prop_category = UCD_CATEGORY(c);
4903 if (prop_category == ucp_M) break;
4904 while (eptr < md->end_subject)
4905 {
4906 int len = 1;
4907 if (!utf8) c = *eptr; else
4908 {
4909 GETCHARLEN(c, eptr, len);
4910 }
4911 prop_category = UCD_CATEGORY(c);
4912 if (prop_category != ucp_M) break;
4913 eptr += len;
4914 }
4915 }
4916
4917 /* eptr is now past the end of the maximum run */
4918
4919 if (possessive) continue;
4920
4921 for(;;)
4922 {
4923 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM45);
4924 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
4925 if (eptr-- == pp) break; /* Stop if tried at original pos */
4926 for (;;) /* Move back over one extended */
4927 {
4928 int len = 1;
4929 if (!utf8) c = *eptr; else
4930 {
4931 BACKCHAR(eptr);
4932 GETCHARLEN(c, eptr, len);
4933 }
4934 prop_category = UCD_CATEGORY(c);
4935 if (prop_category != ucp_M) break;
4936 eptr--;
4937 }
4938 }
4939 }
4940
4941 else
4942 #endif /* SUPPORT_UCP */
4943
4944 #ifdef SUPPORT_UTF8
4945 /* UTF-8 mode */
4946
4947 if (utf8)
4948 {
4949 switch(ctype)
4950 {
4951 case OP_ANY:
4952 if (max < INT_MAX)
4953 {
4954 for (i = min; i < max; i++)
4955 {
4956 if (eptr >= md->end_subject)
4957 {
4958 SCHECK_PARTIAL();
4959 break;
4960 }
4961 if (IS_NEWLINE(eptr)) break;
4962 eptr++;
4963 while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++;
4964 }
4965 }
4966
4967 /* Handle unlimited UTF-8 repeat */
4968
4969 else
4970 {
4971 for (i = min; i < max; i++)
4972 {
4973 if (eptr >= md->end_subject)
4974 {
4975 SCHECK_PARTIAL();
4976 break;
4977 }
4978 if (IS_NEWLINE(eptr)) break;
4979 eptr++;
4980 while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++;
4981 }
4982 }
4983 break;
4984
4985 case OP_ALLANY:
4986 if (max < INT_MAX)
4987 {
4988 for (i = min; i < max; i++)
4989 {
4990 if (eptr >= md->end_subject)
4991 {
4992 SCHECK_PARTIAL();
4993 break;
4994 }
4995 eptr++;
4996 while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++;
4997 }
4998 }
4999 else eptr = md->end_subject; /* Unlimited UTF-8 repeat */
5000 break;
5001
5002 /* The byte case is the same as non-UTF8 */
5003
5004 case OP_ANYBYTE:
5005 c = max - min;
5006 if (c > (unsigned int)(md->end_subject - eptr))
5007 {
5008 eptr = md->end_subject;
5009 SCHECK_PARTIAL();
5010 }
5011 else eptr += c;
5012 break;
5013
5014 case OP_ANYNL:
5015 for (i = min; i < max; i++)
5016 {
5017 int len = 1;
5018 if (eptr >= md->end_subject)
5019 {
5020 SCHECK_PARTIAL();
5021 break;
5022 }
5023 GETCHARLEN(c, eptr, len);
5024 if (c == 0x000d)
5025 {
5026 if (++eptr >= md->end_subject) break;
5027 if (*eptr == 0x000a) eptr++;
5028 }
5029 else
5030 {
5031 if (c != 0x000a &&
5032 (md->bsr_anycrlf ||
5033 (c != 0x000b && c != 0x000c &&
5034 c != 0x0085 && c != 0x2028 && c != 0x2029)))
5035 break;
5036 eptr += len;
5037 }
5038 }
5039 break;
5040
5041 case OP_NOT_HSPACE:
5042 case OP_HSPACE:
5043 for (i = min; i < max; i++)
5044 {
5045 BOOL gotspace;
5046 int len = 1;
5047 if (eptr >= md->end_subject)
5048 {
5049 SCHECK_PARTIAL();
5050 break;
5051 }
5052 GETCHARLEN(c, eptr, len);
5053 switch(c)
5054 {
5055 default: gotspace = FALSE; break;
5056 case 0x09: /* HT */
5057 case 0x20: /* SPACE */
5058 case 0xa0: /* NBSP */
5059 case 0x1680: /* OGHAM SPACE MARK */
5060 case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */
5061 case 0x2000: /* EN QUAD */
5062 case 0x2001: /* EM QUAD */
5063 case 0x2002: /* EN SPACE */
5064 case 0x2003: /* EM SPACE */
5065 case 0x2004: /* THREE-PER-EM SPACE */
5066 case 0x2005: /* FOUR-PER-EM SPACE */
5067 case 0x2006: /* SIX-PER-EM SPACE */
5068 case 0x2007: /* FIGURE SPACE */
5069 case 0x2008: /* PUNCTUATION SPACE */
5070 case 0x2009: /* THIN SPACE */
5071 case 0x200A: /* HAIR SPACE */
5072 case 0x202f: /* NARROW NO-BREAK SPACE */
5073 case 0x205f: /* MEDIUM MATHEMATICAL SPACE */
5074 case 0x3000: /* IDEOGRAPHIC SPACE */
5075 gotspace = TRUE;
5076 break;
5077 }
5078 if (gotspace == (ctype == OP_NOT_HSPACE)) break;
5079 eptr += len;
5080 }
5081 break;
5082
5083 case OP_NOT_VSPACE:
5084 case OP_VSPACE:
5085 for (i = min; i < max; i++)
5086 {
5087 BOOL gotspace;
5088 int len = 1;
5089 if (eptr >= md->end_subject)
5090 {
5091 SCHECK_PARTIAL();
5092 break;
5093 }
5094 GETCHARLEN(c, eptr, len);
5095 switch(c)
5096 {
5097 default: gotspace = FALSE; break;
5098 case 0x0a: /* LF */
5099 case 0x0b: /* VT */
5100 case 0x0c: /* FF */
5101 case 0x0d: /* CR */
5102 case 0x85: /* NEL */
5103 case 0x2028: /* LINE SEPARATOR */
5104 case 0x2029: /* PARAGRAPH SEPARATOR */
5105 gotspace = TRUE;
5106 break;
5107 }
5108 if (gotspace == (ctype == OP_NOT_VSPACE)) break;
5109 eptr += len;
5110 }
5111 break;
5112
5113 case OP_NOT_DIGIT:
5114 for (i = min; i < max; i++)
5115 {
5116 int len = 1;
5117 if (eptr >= md->end_subject)
5118 {
5119 SCHECK_PARTIAL();
5120 break;
5121 }
5122 GETCHARLEN(c, eptr, len);
5123 if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break;
5124 eptr+= len;
5125 }
5126 break;
5127
5128 case OP_DIGIT:
5129 for (i = min; i < max; i++)
5130 {
5131 int len = 1;
5132 if (eptr >= md->end_subject)
5133 {
5134 SCHECK_PARTIAL();
5135 break;
5136 }
5137 GETCHARLEN(c, eptr, len);
5138 if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break;
5139 eptr+= len;
5140 }
5141 break;
5142
5143 case OP_NOT_WHITESPACE:
5144 for (i = min; i < max; i++)
5145 {
5146 int len = 1;
5147 if (eptr >= md->end_subject)
5148 {
5149 SCHECK_PARTIAL();
5150 break;
5151 }
5152 GETCHARLEN(c, eptr, len);
5153 if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break;
5154 eptr+= len;
5155 }
5156 break;
5157
5158 case OP_WHITESPACE:
5159 for (i = min; i < max; i++)
5160 {
5161 int len = 1;
5162 if (eptr >= md->end_subject)
5163 {
5164 SCHECK_PARTIAL();
5165 break;
5166 }
5167 GETCHARLEN(c, eptr, len);
5168 if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break;
5169 eptr+= len;
5170 }
5171 break;
5172
5173 case OP_NOT_WORDCHAR:
5174 for (i = min; i < max; i++)
5175 {
5176 int len = 1;
5177 if (eptr >= md->end_subject)
5178 {
5179 SCHECK_PARTIAL();
5180 break;
5181 }
5182 GETCHARLEN(c, eptr, len);
5183 if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break;
5184 eptr+= len;
5185 }
5186 break;
5187
5188 case OP_WORDCHAR:
5189 for (i = min; i < max; i++)
5190 {
5191 int len = 1;
5192 if (eptr >= md->end_subject)
5193 {
5194 SCHECK_PARTIAL();
5195 break;
5196 }
5197 GETCHARLEN(c, eptr, len);
5198 if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break;
5199 eptr+= len;
5200 }
5201 break;
5202
5203 default:
5204 RRETURN(PCRE_ERROR_INTERNAL);
5205 }
5206
5207 /* eptr is now past the end of the maximum run */
5208
5209 if (possessive) continue;
5210 for(;;)
5211 {
5212 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM46);
5213 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
5214 if (eptr-- == pp) break; /* Stop if tried at original pos */
5215 BACKCHAR(eptr);
5216 }
5217 }
5218 else
5219 #endif /* SUPPORT_UTF8 */
5220
5221 /* Not UTF-8 mode */
5222 {
5223 switch(ctype)
5224 {
5225 case OP_ANY:
5226 for (i = min; i < max; i++)
5227 {
5228 if (eptr >= md->end_subject)
5229 {
5230 SCHECK_PARTIAL();
5231 break;
5232 }
5233 if (IS_NEWLINE(eptr)) break;
5234 eptr++;
5235 }
5236 break;
5237
5238 case OP_ALLANY:
5239 case OP_ANYBYTE:
5240 c = max - min;
5241 if (c > (unsigned int)(md->end_subject - eptr))
5242 {
5243 eptr = md->end_subject;
5244 SCHECK_PARTIAL();
5245 }
5246 else eptr += c;
5247 break;
5248
5249 case OP_ANYNL:
5250 for (i = min; i < max; i++)
5251 {
5252 if (eptr >= md->end_subject)
5253 {
5254 SCHECK_PARTIAL();
5255 break;
5256 }
5257 c = *eptr;
5258 if (c == 0x000d)
5259 {
5260 if (++eptr >= md->end_subject) break;
5261 if (*eptr == 0x000a) eptr++;
5262 }
5263 else
5264 {
5265 if (c != 0x000a &&
5266 (md->bsr_anycrlf ||
5267 (c != 0x000b && c != 0x000c && c != 0x0085)))
5268 break;
5269 eptr++;
5270 }
5271 }
5272 break;
5273
5274 case OP_NOT_HSPACE:
5275 for (i = min; i < max; i++)
5276 {
5277 if (eptr >= md->end_subject)
5278 {
5279 SCHECK_PARTIAL();
5280 break;
5281 }
5282 c = *eptr;
5283 if (c == 0x09 || c == 0x20 || c == 0xa0) break;
5284 eptr++;
5285 }
5286 break;
5287
5288 case OP_HSPACE:
5289 for (i = min; i < max; i++)
5290 {
5291 if (eptr >= md->end_subject)
5292 {
5293 SCHECK_PARTIAL();
5294 break;
5295 }
5296 c = *eptr;
5297 if (c != 0x09 && c != 0x20 && c != 0xa0) break;
5298 eptr++;
5299 }
5300 break;
5301
5302 case OP_NOT_VSPACE:
5303 for (i = min; i < max; i++)
5304 {
5305 if (eptr >= md->end_subject)
5306 {
5307 SCHECK_PARTIAL();
5308 break;
5309 }
5310 c = *eptr;
5311 if (c == 0x0a || c == 0x0b || c == 0x0c || c == 0x0d || c == 0x85)
5312 break;
5313 eptr++;
5314 }
5315 break;
5316
5317 case OP_VSPACE:
5318 for (i = min; i < max; i++)
5319 {
5320 if (eptr >= md->end_subject)
5321 {
5322 SCHECK_PARTIAL();
5323 break;
5324 }
5325 c = *eptr;
5326 if (c != 0x0a && c != 0x0b && c != 0x0c && c != 0x0d && c != 0x85)
5327 break;
5328 eptr++;
5329 }
5330 break;
5331
5332 case OP_NOT_DIGIT:
5333 for (i = min; i < max; i++)
5334 {
5335 if (eptr >= md->end_subject)
5336 {
5337 SCHECK_PARTIAL();
5338 break;
5339 }
5340 if ((md->ctypes[*eptr] & ctype_digit) != 0) break;
5341 eptr++;
5342 }
5343 break;
5344
5345 case OP_DIGIT:
5346 for (i = min; i < max; i++)
5347 {
5348 if (eptr >= md->end_subject)
5349 {
5350 SCHECK_PARTIAL();
5351 break;
5352 }
5353 if ((md->ctypes[*eptr] & ctype_digit) == 0) break;
5354 eptr++;
5355 }
5356 break;
5357
5358 case OP_NOT_WHITESPACE:
5359 for (i = min; i < max; i++)
5360 {
5361 if (eptr >= md->end_subject)
5362 {
5363 SCHECK_PARTIAL();
5364 break;
5365 }
5366 if ((md->ctypes[*eptr] & ctype_space) != 0) break;
5367 eptr++;
5368 }
5369 break;
5370
5371 case OP_WHITESPACE:
5372 for (i = min; i < max; i++)
5373 {
5374 if (eptr >= md->end_subject)
5375 {
5376 SCHECK_PARTIAL();
5377 break;
5378 }
5379 if ((md->ctypes[*eptr] & ctype_space) == 0) break;
5380 eptr++;
5381 }
5382 break;
5383
5384 case OP_NOT_WORDCHAR:
5385 for (i = min; i < max; i++)
5386 {
5387 if (eptr >= md->end_subject)
5388 {
5389 SCHECK_PARTIAL();
5390 break;
5391 }
5392 if ((md->ctypes[*eptr] & ctype_word) != 0) break;
5393 eptr++;
5394 }
5395 break;
5396
5397 case OP_WORDCHAR:
5398 for (i = min; i < max; i++)
5399 {
5400 if (eptr >= md->end_subject)
5401 {
5402 SCHECK_PARTIAL();
5403 break;
5404 }
5405 if ((md->ctypes[*eptr] & ctype_word) == 0) break;
5406 eptr++;
5407 }
5408 break;
5409
5410 default:
5411 RRETURN(PCRE_ERROR_INTERNAL);
5412 }
5413
5414 /* eptr is now past the end of the maximum run */
5415
5416 if (possessive) continue;
5417 while (eptr >= pp)
5418 {
5419 RMATCH(eptr, ecode, offset_top, md, ims, eptrb, 0, RM47);
5420 eptr--;
5421 if (rrc != MATCH_NOMATCH) RRETURN(rrc);
5422 }
5423 }
5424
5425 /* Get here if we can't make it match with any permitted repetitions */
5426
5427 MRRETURN(MATCH_NOMATCH);
5428 }
5429 /* Control never gets here */
5430
5431 /* There's been some horrible disaster. Arrival here can only mean there is
5432 something seriously wrong in the code above or the OP_xxx definitions. */
5433
5434 default:
5435 DPRINTF(("Unknown opcode %d\n", *ecode));
5436 RRETURN(PCRE_ERROR_UNKNOWN_OPCODE);
5437 }
5438
5439 /* Do not stick any code in here without much thought; it is assumed
5440 that "continue" in the code above comes out to here to repeat the main
5441 loop. */
5442
5443 } /* End of main loop */
5444 /* Control never reaches here */
5445
5446
5447 /* When compiling to use the heap rather than the stack for recursive calls to
5448 match(), the RRETURN() macro jumps here. The number that is saved in
5449 frame->Xwhere indicates which label we actually want to return to. */
5450
5451 #ifdef NO_RECURSE
5452 #define LBL(val) case val: goto L_RM##val;
5453 HEAP_RETURN:
5454 switch (frame->Xwhere)
5455 {
5456 LBL( 1) LBL( 2) LBL( 3) LBL( 4) LBL( 5) LBL( 6) LBL( 7) LBL( 8)
5457 LBL( 9) LBL(10) LBL(11) LBL(12) LBL(13) LBL(14) LBL(15) LBL(17)
5458 LBL(19) LBL(24) LBL(25) LBL(26) LBL(27) LBL(29) LBL(31) LBL(33)
5459 LBL(35) LBL(43) LBL(47) LBL(48) LBL(49) LBL(50) LBL(51) LBL(52)
5460 LBL(53) LBL(54) LBL(55) LBL(56) LBL(57) LBL(58)
5461 #ifdef SUPPORT_UTF8
5462 LBL(16) LBL(18) LBL(20) LBL(21) LBL(22) LBL(23) LBL(28) LBL(30)
5463 LBL(32) LBL(34) LBL(42) LBL(46)
5464 #ifdef SUPPORT_UCP
5465 LBL(36) LBL(37) LBL(38) LBL(39) LBL(40) LBL(41) LBL(44) LBL(45)
5466 LBL(59) LBL(60) LBL(61) LBL(62)
5467 #endif /* SUPPORT_UCP */
5468 #endif /* SUPPORT_UTF8 */
5469 default:
5470 DPRINTF(("jump error in pcre match: label %d non-existent\n", frame->Xwhere));
5471 return PCRE_ERROR_INTERNAL;
5472 }
5473 #undef LBL
5474 #endif /* NO_RECURSE */
5475 }
5476
5477
5478 /***************************************************************************
5479 ****************************************************************************
5480 RECURSION IN THE match() FUNCTION
5481
5482 Undefine all the macros that were defined above to handle this. */
5483
5484 #ifdef NO_RECURSE
5485 #undef eptr
5486 #undef ecode
5487 #undef mstart
5488 #undef offset_top
5489 #undef ims
5490 #undef eptrb
5491 #undef flags
5492
5493 #undef callpat
5494 #undef charptr
5495 #undef data
5496 #undef next
5497 #undef pp
5498 #undef prev
5499 #undef saved_eptr
5500
5501 #undef new_recursive
5502
5503 #undef cur_is_word
5504 #undef condition
5505 #undef prev_is_word
5506
5507 #undef original_ims
5508
5509 #undef ctype
5510 #undef length
5511 #undef max
5512 #undef min
5513 #undef number
5514 #undef offset
5515 #undef op
5516 #undef save_capture_last
5517 #undef save_offset1
5518 #undef save_offset2
5519 #undef save_offset3
5520 #undef stacksave
5521
5522 #undef newptrb
5523
5524 #endif
5525
5526 /* These two are defined as macros in both cases */
5527
5528 #undef fc
5529 #undef fi
5530
5531 /***************************************************************************
5532 ***************************************************************************/
5533
5534
5535
5536 /*************************************************
5537 * Execute a Regular Expression *
5538 *************************************************/
5539
5540 /* This function applies a compiled re to a subject string and picks out
5541 portions of the string if it matches. Two elements in the vector are set for
5542 each substring: the offsets to the start and end of the substring.
5543
5544 Arguments:
5545 argument_re points to the compiled expression
5546 extra_data points to extra data or is NULL
5547 subject points to the subject string
5548 length length of subject string (may contain binary zeros)
5549 start_offset where to start in the subject string
5550 options option bits
5551 offsets points to a vector of ints to be filled in with offsets
5552 offsetcount the number of elements in the vector
5553
5554 Returns: > 0 => success; value is the number of elements filled in
5555 = 0 => success, but offsets is not big enough
5556 -1 => failed to match
5557 < -1 => some kind of unexpected problem
5558 */
5559
5560 PCRE_EXP_DEFN int PCRE_CALL_CONVENTION
5561 pcre_exec(const pcre *argument_re, const pcre_extra *extra_data,
5562 PCRE_SPTR subject, int length, int start_offset, int options, int *offsets,
5563 int offsetcount)
5564 {
5565 int rc, resetcount, ocount;
5566 int first_byte = -1;
5567 int req_byte = -1;
5568 int req_byte2 = -1;
5569 int newline;
5570 unsigned long int ims;
5571 BOOL using_temporary_offsets = FALSE;
5572 BOOL anchored;
5573 BOOL startline;
5574 BOOL firstline;
5575 BOOL first_byte_caseless = FALSE;
5576 BOOL req_byte_caseless = FALSE;
5577 BOOL utf8;
5578 match_data match_block;
5579 match_data *md = &match_block;
5580 const uschar *tables;
5581 const uschar *start_bits = NULL;
5582 USPTR start_match = (USPTR)subject + start_offset;
5583 USPTR end_subject;
5584 USPTR start_partial = NULL;
5585 USPTR req_byte_ptr = start_match - 1;
5586
5587 pcre_study_data internal_study;
5588 const pcre_study_data *study;
5589
5590 real_pcre internal_re;
5591 const real_pcre *external_re = (const real_pcre *)argument_re;
5592 const real_pcre *re = external_re;
5593
5594 /* Plausibility checks */
5595
5596 if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION;
5597 if (re == NULL || subject == NULL ||
5598 (offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL;
5599 if (offsetcount < 0) return PCRE_ERROR_BADCOUNT;
5600
5601 /* This information is for finding all the numbers associated with a given
5602 name, for condition testing. */
5603
5604 md->name_table = (uschar *)re + re->name_table_offset;
5605 md->name_count = re->name_count;
5606 md->name_entry_size = re->name_entry_size;
5607
5608 /* Fish out the optional data from the extra_data structure, first setting
5609 the default values. */
5610
5611 study = NULL;
5612 md->match_limit = MATCH_LIMIT;
5613 md->match_limit_recursion = MATCH_LIMIT_RECURSION;
5614 md->callout_data = NULL;
5615
5616 /* The table pointer is always in native byte order. */
5617
5618 tables = external_re->tables;
5619
5620 if (extra_data != NULL)
5621 {
5622 register unsigned int flags = extra_data->flags;
5623 if ((flags & PCRE_EXTRA_STUDY_DATA) != 0)
5624 study = (const pcre_study_data *)extra_data->study_data;
5625 if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0)
5626 md->match_limit = extra_data->match_limit;
5627 if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0)
5628 md->match_limit_recursion = extra_data->match_limit_recursion;
5629 if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0)
5630 md->callout_data = extra_data->callout_data;
5631 if ((flags & PCRE_EXTRA_TABLES) != 0) tables = extra_data->tables;
5632 }
5633
5634 /* If the exec call supplied NULL for tables, use the inbuilt ones. This
5635 is a feature that makes it possible to save compiled regex and re-use them
5636 in other programs later. */
5637
5638 if (tables == NULL) tables = _pcre_default_tables;
5639
5640 /* Check that the first field in the block is the magic number. If it is not,
5641 test for a regex that was compiled on a host of opposite endianness. If this is
5642 the case, flipped values are put in internal_re and internal_study if there was
5643 study data too. */
5644
5645 if (re->magic_number != MAGIC_NUMBER)
5646 {
5647 re = _pcre_try_flipped(re, &internal_re, study, &internal_study);
5648 if (re == NULL) return PCRE_ERROR_BADMAGIC;
5649 if (study != NULL) study = &internal_study;
5650 }
5651
5652 /* Set up other data */
5653
5654 anchored = ((re->options | options) & PCRE_ANCHORED) != 0;
5655 startline = (re->flags & PCRE_STARTLINE) != 0;
5656 firstline = (re->options & PCRE_FIRSTLINE) != 0;
5657
5658 /* The code starts after the real_pcre block and the capture name table. */
5659
5660 md->start_code = (const uschar *)external_re + re->name_table_offset +
5661 re->name_count * re->name_entry_size;
5662
5663 md->start_subject = (USPTR)subject;
5664 md->start_offset = start_offset;
5665 md->end_subject = md->start_subject + length;
5666 end_subject = md->end_subject;
5667
5668 md->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0;
5669 utf8 = md->utf8 = (re->options & PCRE_UTF8) != 0;
5670 md->use_ucp = (re->options & PCRE_UCP) != 0;
5671 md->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0;
5672
5673 md->notbol = (options & PCRE_NOTBOL) != 0;
5674 md->noteol = (options & PCRE_NOTEOL) != 0;
5675 md->notempty = (options & PCRE_NOTEMPTY) != 0;
5676 md->notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0;
5677 md->partial = ((options & PCRE_PARTIAL_HARD) != 0)? 2 :
5678 ((options & PCRE_PARTIAL_SOFT) != 0)? 1 : 0;
5679 md->hitend = FALSE;
5680 md->mark = NULL; /* In case never set */
5681
5682 md->recursive = NULL; /* No recursion at top level */
5683
5684 md->lcc = tables + lcc_offset;
5685 md->ctypes = tables + ctypes_offset;
5686
5687 /* Handle different \R options. */
5688
5689 switch (options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE))
5690 {
5691 case 0:
5692 if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0)
5693 md->bsr_anycrlf = (re->options & PCRE_BSR_ANYCRLF) != 0;
5694 else
5695 #ifdef BSR_ANYCRLF
5696 md->bsr_anycrlf = TRUE;
5697 #else
5698 md->bsr_anycrlf = FALSE;
5699 #endif
5700 break;
5701
5702 case PCRE_BSR_ANYCRLF:
5703 md->bsr_anycrlf = TRUE;
5704 break;
5705
5706 case PCRE_BSR_UNICODE:
5707 md->bsr_anycrlf = FALSE;
5708 break;
5709
5710 default: return PCRE_ERROR_BADNEWLINE;
5711 }
5712
5713 /* Handle different types of newline. The three bits give eight cases. If
5714 nothing is set at run time, whatever was used at compile time applies. */
5715
5716 switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options :
5717 (pcre_uint32)options) & PCRE_NEWLINE_BITS)
5718 {
5719 case 0: newline = NEWLINE; break; /* Compile-time default */
5720 case PCRE_NEWLINE_CR: newline = CHAR_CR; break;
5721 case PCRE_NEWLINE_LF: newline = CHAR_NL; break;
5722 case PCRE_NEWLINE_CR+
5723 PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break;
5724 case PCRE_NEWLINE_ANY: newline = -1; break;
5725 case PCRE_NEWLINE_ANYCRLF: newline = -2; break;
5726 default: return PCRE_ERROR_BADNEWLINE;
5727 }
5728
5729 if (newline == -2)
5730 {
5731 md->nltype = NLTYPE_ANYCRLF;
5732 }
5733 else if (newline < 0)
5734 {
5735 md->nltype = NLTYPE_ANY;
5736 }
5737 else
5738 {
5739 md->nltype = NLTYPE_FIXED;
5740 if (newline > 255)
5741 {
5742 md->nllen = 2;
5743 md->nl[0] = (newline >> 8) & 255;
5744 md->nl[1] = newline & 255;
5745 }
5746 else
5747 {
5748 md->nllen = 1;
5749 md->nl[0] = newline;
5750 }
5751 }
5752
5753 /* Partial matching was originally supported only for a restricted set of
5754 regexes; from release 8.00 there are no restrictions, but the bits are still
5755 defined (though never set). So there's no harm in leaving this code. */
5756
5757 if (md->partial && (re->flags & PCRE_NOPARTIAL) != 0)
5758 return PCRE_ERROR_BADPARTIAL;
5759
5760 /* Check a UTF-8 string if required. Unfortunately there's no way of passing
5761 back the character offset. */
5762
5763 #ifdef SUPPORT_UTF8
5764 if (utf8 && (options & PCRE_NO_UTF8_CHECK) == 0)
5765 {
5766 if (_pcre_valid_utf8((USPTR)subject, length) >= 0)
5767 return PCRE_ERROR_BADUTF8;
5768 if (start_offset > 0 && start_offset < length)
5769 {
5770 int tb = ((USPTR)subject)[start_offset];
5771 if (tb > 127)
5772 {
5773 tb &= 0xc0;
5774 if (tb != 0 && tb != 0xc0) return PCRE_ERROR_BADUTF8_OFFSET;
5775 }
5776 }
5777 }
5778 #endif
5779
5780 /* The ims options can vary during the matching as a result of the presence
5781 of (?ims) items in the pattern. They are kept in a local variable so that
5782 restoring at the exit of a group is easy. */
5783
5784 ims = re->options & (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL);
5785
5786 /* If the expression has got more back references than the offsets supplied can
5787 hold, we get a temporary chunk of working store to use during the matching.
5788 Otherwise, we can use the vector supplied, rounding down its size to a multiple
5789 of 3. */
5790
5791 ocount = offsetcount - (offsetcount % 3);
5792
5793 if (re->top_backref > 0 && re->top_backref >= ocount/3)
5794 {
5795 ocount = re->top_backref * 3 + 3;
5796 md->offset_vector = (int *)(pcre_malloc)(ocount * sizeof(int));
5797 if (md->offset_vector == NULL) return PCRE_ERROR_NOMEMORY;
5798 using_temporary_offsets = TRUE;
5799 DPRINTF(("Got memory to hold back references\n"));
5800 }
5801 else md->offset_vector = offsets;
5802
5803 md->offset_end = ocount;
5804 md->offset_max = (2*ocount)/3;
5805 md->offset_overflow = FALSE;
5806 md->capture_last = -1;
5807
5808 /* Compute the minimum number of offsets that we need to reset each time. Doing
5809 this makes a huge difference to execution time when there aren't many brackets
5810 in the pattern. */
5811
5812 resetcount = 2 + re->top_bracket * 2;
5813 if (resetcount > offsetcount) resetcount = ocount;
5814
5815 /* Reset the working variable associated with each extraction. These should
5816 never be used unless previously set, but they get saved and restored, and so we
5817 initialize them to avoid reading uninitialized locations. */
5818
5819 if (md->offset_vector != NULL)
5820 {
5821 register int *iptr = md->offset_vector + ocount;
5822 register int *iend = iptr - resetcount/2 + 1;
5823 while (--iptr >= iend) *iptr = -1;
5824 }
5825
5826 /* Set up the first character to match, if available. The first_byte value is
5827 never set for an anchored regular expression, but the anchoring may be forced
5828 at run time, so we have to test for anchoring. The first char may be unset for
5829 an unanchored pattern, of course. If there's no first char and the pattern was
5830 studied, there may be a bitmap of possible first characters. */
5831
5832 if (!anchored)
5833 {
5834 if ((re->flags & PCRE_FIRSTSET) != 0)
5835 {
5836 first_byte = re->first_byte & 255;
5837 if ((first_byte_caseless = ((re->first_byte & REQ_CASELESS) != 0)) == TRUE)
5838 first_byte = md->lcc[first_byte];
5839 }
5840 else
5841 if (!startline && study != NULL &&
5842 (study->flags & PCRE_STUDY_MAPPED) != 0)
5843 start_bits = study->start_bits;
5844 }
5845
5846 /* For anchored or unanchored matches, there may be a "last known required
5847 character" set. */
5848
5849 if ((re->flags & PCRE_REQCHSET) != 0)
5850 {
5851 req_byte = re->req_byte & 255;
5852 req_byte_caseless = (re->req_byte & REQ_CASELESS) != 0;
5853 req_byte2 = (tables + fcc_offset)[req_byte]; /* case flipped */
5854 }
5855
5856
5857 /* ==========================================================================*/
5858
5859 /* Loop for handling unanchored repeated matching attempts; for anchored regexs
5860 the loop runs just once. */
5861
5862 for(;;)
5863 {
5864 USPTR save_end_subject = end_subject;
5865 USPTR new_start_match;
5866
5867 /* Reset the maximum number of extractions we might see. */
5868
5869 if (md->offset_vector != NULL)
5870 {
5871 register int *iptr = md->offset_vector;
5872 register int *iend = iptr + resetcount;
5873 while (iptr < iend) *iptr++ = -1;
5874 }
5875
5876 /* If firstline is TRUE, the start of the match is constrained to the first
5877 line of a multiline string. That is, the match must be before or at the first
5878 newline. Implement this by temporarily adjusting end_subject so that we stop
5879 scanning at a newline. If the match fails at the newline, later code breaks
5880 this loop. */
5881
5882 if (firstline)
5883 {
5884 USPTR t = start_match;
5885 #ifdef SUPPORT_UTF8
5886 if (utf8)
5887 {
5888 while (t < md->end_subject && !IS_NEWLINE(t))
5889 {
5890 t++;
5891 while (t < end_subject && (*t & 0xc0) == 0x80) t++;
5892 }
5893 }
5894 else
5895 #endif
5896 while (t < md->end_subject && !IS_NEWLINE(t)) t++;
5897 end_subject = t;
5898 }
5899
5900 /* There are some optimizations that avoid running the match if a known
5901 starting point is not found, or if a known later character is not present.
5902 However, there is an option that disables these, for testing and for ensuring
5903 that all callouts do actually occur. */
5904
5905 if ((options & PCRE_NO_START_OPTIMIZE) == 0)
5906 {
5907 /* Advance to a unique first byte if there is one. */
5908
5909 if (first_byte >= 0)
5910 {
5911 if (first_byte_caseless)
5912 while (start_match < end_subject && md->lcc[*start_match] != first_byte)
5913 start_match++;
5914 else
5915 while (start_match < end_subject && *start_match != first_byte)
5916 start_match++;
5917 }
5918
5919 /* Or to just after a linebreak for a multiline match */
5920
5921 else if (startline)
5922 {
5923 if (start_match > md->start_subject + start_offset)
5924 {
5925 #ifdef SUPPORT_UTF8
5926 if (utf8)
5927 {
5928 while (start_match < end_subject && !WAS_NEWLINE(start_match))
5929 {
5930 start_match++;
5931 while(start_match < end_subject && (*start_match & 0xc0) == 0x80)
5932 start_match++;
5933 }
5934 }
5935 else
5936 #endif
5937 while (start_match < end_subject && !WAS_NEWLINE(start_match))
5938 start_match++;
5939
5940 /* If we have just passed a CR and the newline option is ANY or ANYCRLF,
5941 and we are now at a LF, advance the match position by one more character.
5942 */
5943
5944 if (start_match[-1] == CHAR_CR &&
5945 (md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) &&
5946 start_match < end_subject &&
5947 *start_match == CHAR_NL)
5948 start_match++;
5949 }
5950 }
5951
5952 /* Or to a non-unique first byte after study */
5953
5954 else if (start_bits != NULL)
5955 {
5956 while (start_match < end_subject)
5957 {
5958 register unsigned int c = *start_match;
5959 if ((start_bits[c/8] & (1 << (c&7))) == 0) start_match++;
5960 else break;
5961 }
5962 }
5963 } /* Starting optimizations */
5964
5965 /* Restore fudged end_subject */
5966
5967 end_subject = save_end_subject;
5968
5969 /* The following two optimizations are disabled for partial matching or if
5970 disabling is explicitly requested. */
5971
5972 if ((options & PCRE_NO_START_OPTIMIZE) == 0 && !md->partial)
5973 {
5974 /* If the pattern was studied, a minimum subject length may be set. This is
5975 a lower bound; no actual string of that length may actually match the
5976 pattern. Although the value is, strictly, in characters, we treat it as
5977 bytes to avoid spending too much time in this optimization. */
5978
5979 if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 &&
5980 (pcre_uint32)(end_subject - start_match) < study->minlength)
5981 {
5982 rc = MATCH_NOMATCH;
5983 break;
5984 }
5985
5986 /* If req_byte is set, we know that that character must appear in the
5987 subject for the match to succeed. If the first character is set, req_byte
5988 must be later in the subject; otherwise the test starts at the match point.
5989 This optimization can save a huge amount of backtracking in patterns with
5990 nested unlimited repeats that aren't going to match. Writing separate code
5991 for cased/caseless versions makes it go faster, as does using an
5992 autoincrement and backing off on a match.
5993
5994 HOWEVER: when the subject string is very, very long, searching to its end
5995 can take a long time, and give bad performance on quite ordinary patterns.
5996 This showed up when somebody was matching something like /^\d+C/ on a
5997 32-megabyte string... so we don't do this when the string is sufficiently
5998 long. */
5999
6000 if (req_byte >= 0 && end_subject - start_match < REQ_BYTE_MAX)
6001 {
6002 register USPTR p = start_match + ((first_byte >= 0)? 1 : 0);
6003
6004 /* We don't need to repeat the search if we haven't yet reached the
6005 place we found it at last time. */
6006
6007 if (p > req_byte_ptr)
6008 {
6009 if (req_byte_caseless)
6010 {
6011 while (p < end_subject)
6012 {
6013 register int pp = *p++;
6014 if (pp == req_byte || pp == req_byte2) { p--; break; }
6015 }
6016 }
6017 else
6018 {
6019 while (p < end_subject)
6020 {
6021 if (*p++ == req_byte) { p--; break; }
6022 }
6023 }
6024
6025 /* If we can't find the required character, break the matching loop,
6026 forcing a match failure. */
6027
6028 if (p >= end_subject)
6029 {
6030 rc = MATCH_NOMATCH;
6031 break;
6032 }
6033
6034 /* If we have found the required character, save the point where we
6035 found it, so that we don't search again next time round the loop if
6036 the start hasn't passed this character yet. */
6037
6038 req_byte_ptr = p;
6039 }
6040 }
6041 }
6042
6043 #ifdef PCRE_DEBUG /* Sigh. Some compilers never learn. */
6044 printf(">>>> Match against: ");
6045 pchars(start_match, end_subject - start_match, TRUE, md);
6046 printf("\n");
6047 #endif
6048
6049 /* OK, we can now run the match. If "hitend" is set afterwards, remember the
6050 first starting point for which a partial match was found. */
6051
6052 md->start_match_ptr = start_match;
6053 md->start_used_ptr = start_match;
6054 md->match_call_count = 0;
6055 rc = match(start_match, md->start_code, start_match, NULL, 2, md, ims, NULL,
6056 0, 0);
6057 if (md->hitend && start_partial == NULL) start_partial = md->start_used_ptr;
6058
6059 switch(rc)
6060 {
6061 /* NOMATCH and PRUNE advance by one character. If MATCH_SKIP_ARG reaches
6062 this level it means that a MARK that matched the SKIP's arg was not found.
6063 We treat this as NOMATCH. THEN at this level acts exactly like PRUNE. */
6064
6065 case MATCH_NOMATCH:
6066 case MATCH_PRUNE:
6067 case MATCH_SKIP_ARG:
6068 case MATCH_THEN:
6069 new_start_match = start_match + 1;
6070 #ifdef SUPPORT_UTF8
6071 if (utf8)
6072 while(new_start_match < end_subject && (*new_start_match & 0xc0) == 0x80)
6073 new_start_match++;
6074 #endif
6075 break;
6076
6077 /* SKIP passes back the next starting point explicitly. */
6078
6079 case MATCH_SKIP:
6080 new_start_match = md->start_match_ptr;
6081 break;
6082
6083 /* COMMIT disables the bumpalong, but otherwise behaves as NOMATCH. */
6084
6085 case MATCH_COMMIT:
6086 rc = MATCH_NOMATCH;
6087 goto ENDLOOP;
6088
6089 /* Any other return is either a match, or some kind of error. */
6090
6091 default:
6092 goto ENDLOOP;
6093 }
6094
6095 /* Control reaches here for the various types of "no match at this point"
6096 result. Reset the code to MATCH_NOMATCH for subsequent checking. */
6097
6098 rc = MATCH_NOMATCH;
6099
6100 /* If PCRE_FIRSTLINE is set, the match must happen before or at the first
6101 newline in the subject (though it may continue over the newline). Therefore,
6102 if we have just failed to match, starting at a newline, do not continue. */
6103
6104 if (firstline && IS_NEWLINE(start_match)) break;
6105
6106 /* Advance to new matching position */
6107
6108 start_match = new_start_match;
6109
6110 /* Break the loop if the pattern is anchored or if we have passed the end of
6111 the subject. */
6112
6113 if (anchored || start_match > end_subject) break;
6114
6115 /* If we have just passed a CR and we are now at a LF, and the pattern does
6116 not contain any explicit matches for \r or \n, and the newline option is CRLF
6117 or ANY or ANYCRLF, advance the match position by one more character. */
6118
6119 if (start_match[-1] == CHAR_CR &&
6120 start_match < end_subject &&
6121 *start_match == CHAR_NL &&
6122 (re->flags & PCRE_HASCRORLF) == 0 &&
6123 (md->nltype == NLTYPE_ANY ||
6124 md->nltype == NLTYPE_ANYCRLF ||
6125 md->nllen == 2))
6126 start_match++;
6127
6128 md->mark = NULL; /* Reset for start of next match attempt */
6129 } /* End of for(;;) "bumpalong" loop */
6130
6131 /* ==========================================================================*/
6132
6133 /* We reach here when rc is not MATCH_NOMATCH, or if one of the stopping
6134 conditions is true:
6135
6136 (1) The pattern is anchored or the match was failed by (*COMMIT);
6137
6138 (2) We are past the end of the subject;
6139
6140 (3) PCRE_FIRSTLINE is set and we have failed to match at a newline, because
6141 this option requests that a match occur at or before the first newline in
6142 the subject.
6143
6144 When we have a match and the offset vector is big enough to deal with any
6145 backreferences, captured substring offsets will already be set up. In the case
6146 where we had to get some local store to hold offsets for backreference
6147 processing, copy those that we can. In this case there need not be overflow if
6148 certain parts of the pattern were not used, even though there are more
6149 capturing parentheses than vector slots. */
6150
6151 ENDLOOP:
6152
6153 if (rc == MATCH_MATCH || rc == MATCH_ACCEPT)
6154 {
6155 if (using_temporary_offsets)
6156 {
6157 if (offsetcount >= 4)
6158 {
6159 memcpy(offsets + 2, md->offset_vector + 2,
6160 (offsetcount - 2) * sizeof(int));
6161 DPRINTF(("Copied offsets from temporary memory\n"));
6162 }
6163 if (md->end_offset_top > offsetcount) md->offset_overflow = TRUE;
6164 DPRINTF(("Freeing temporary memory\n"));
6165 (pcre_free)(md->offset_vector);
6166 }
6167
6168 /* Set the return code to the number of captured strings, or 0 if there are
6169 too many to fit into the vector. */
6170
6171 rc = md->offset_overflow? 0 : md->end_offset_top/2;
6172
6173 /* If there is space, set up the whole thing as substring 0. The value of
6174 md->start_match_ptr might be modified if \K was encountered on the success
6175 matching path. */
6176
6177 if (offsetcount < 2) rc = 0; else
6178 {
6179 offsets[0] = md->start_match_ptr - md->start_subject;
6180 offsets[1] = md->end_match_ptr - md->start_subject;
6181 }
6182
6183 DPRINTF((">>>> returning %d\n", rc));
6184 goto RETURN_MARK;
6185 }
6186
6187 /* Control gets here if there has been an error, or if the overall match
6188 attempt has failed at all permitted starting positions. */
6189
6190 if (using_temporary_offsets)
6191 {
6192 DPRINTF(("Freeing temporary memory\n"));
6193 (pcre_free)(md->offset_vector);
6194 }
6195
6196 /* For anything other than nomatch or partial match, just return the code. */
6197
6198 if (rc != MATCH_NOMATCH && rc != PCRE_ERROR_PARTIAL)
6199 {
6200 DPRINTF((">>>> error: returning %d\n", rc));
6201 return rc;
6202 }
6203
6204 /* Handle partial matches - disable any mark data */
6205
6206 if (start_partial != NULL)
6207 {
6208 DPRINTF((">>>> returning PCRE_ERROR_PARTIAL\n"));
6209 md->mark = NULL;
6210 if (offsetcount > 1)
6211 {
6212 offsets[0] = start_partial - (USPTR)subject;
6213 offsets[1] = end_subject - (USPTR)subject;
6214 }
6215 rc = PCRE_ERROR_PARTIAL;
6216 }
6217
6218 /* This is the classic nomatch case */
6219
6220 else
6221 {
6222 DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n"));
6223 rc = PCRE_ERROR_NOMATCH;
6224 }
6225
6226 /* Return the MARK data if it has been requested. */
6227
6228 RETURN_MARK:
6229
6230 if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0)
6231 *(extra_data->mark) = (unsigned char *)(md->mark);
6232 return rc;
6233 }
6234
6235 /* End of pcre_exec.c */
Properties
Name Value
svn:eol-style native
svn:keywords "Author Date Id Revision Url"
ViewVC Help
Powered by ViewVC 1.1.5
|
__label__pos
| 0.966857 |
Ruiby DSL Documentation
Ruiby Version: 1.31.4
Generated at : 2015-04-23 20:48:23 +0200
See code example
Search :
generalities
All Ruiby commands correspond of
• a object creation (container, widget), see later,
• complement set propertie to current/alst widget created : css_name(), space(), tooltip()
• a immediate dialog (modal) command :
• a immediate command, the can be used in callback code: gui manipulation... :
2 kinds of objects :
• container
Containers organyze children widget, but show (almost) nothing.
Children must be created in container bloc, container can contains widget and container :
| stack do
| button("Hello")
| label(" word")
| flow { button("x") ; label("y") }
| end
• widgets
Widget must be placed in a container.
2 kinds of placement :
• sloted : widget take all disponible space ( gtk: pack(expand,fill) ), share
space with other sloted widget in same container
• slotied : widget take only necessary place ( gtk: pack(no-expand , no-fill) )
|------------------------|
|<buttoni >|
|<labeli >|
|<--------------------- >|
|< >|
|< button >|
|< >|
|<--------------------- >|
|< >|
|< label >|
|< >|
|<--------------------- >|
|<buttoni >|
|------------------------|
by default, all widgetcontainer are sloted !
widget name ended by 'i' ( buttoni, labeli, stacki , flowi ...) are slotied
slot() command is deprecated. sloti() command must be use if *i command
do not exist : w=sloti( widgetname() {...} )
space() can be used for slot a empty space.
Attachement to a side of a container is not supported. You must put empty sloted widget
in free space:
• scoth xxxx in top of frame : >stack { stacki { xxx } ; stack { } }
• scoth xxxx in bottom of frame : >stack { stack { } ; stacki { xxx } }
• scoth xxxx in left of frame : >flow { flowi { xxx } ; stack { } }
Dynamique variables bindings
The class ::DynVar support a single value and the observer pattern.
So widgets can be associate with an dynamique value :
• if the value change, the widget change the view accordingly to the new value,
• if the view change by operator action, the value change accordingly.
• Threading is care : widget updates will be done in maint thread context
Widgets which supports DynVar are :
• entry,ientry,
• label,
• islider,
• check_button
This list will be extende to combo_button, toggle_button, list, grid ...
'make_DynClass' and 'make_StockDynClass' can be use for creation of Class/object
which contain DynVar : as OStruct, but data members are DynVar.
• @calc=make_DynObject({"resultat"=> 0,"value" => "0" , "stack" => [] })
@calc.resultat => @calc.resultat.value="X" ; x= @calc.resultat.value
• @calc=make_StockDynObject("name",{"resultat"=> 0,"value" => "0" , "stack" => [] })
create a object, name him for Stock, give default values if object does not exists
in current stock.
ex
• accept
def accept?(t)
mock class which can be push to layout stack : they accept some
specific type of commands
ex
accordion
def accordion()
Accordion
create a accordion menu.
must contain aitem() which must containe alabel() :
accordion { aitem(txt) { alabel(lib) { code }; ...} ... }
ex
after
def after(n,&blk)
as anim, but one shot, after some millisecs
no threading: the bloc is evaluated by gtk mainloop in main thread context
ex
aitem
def aitem(txt,&blk)
a button menu in accordion
bloc is evaluate for create/view a list of alabel :
aitem(txt) { alabel(lib) { code }; ...}
ex
alabel
def alabel(txt,&blk)
create a button-entry in a accordion menu
bloc is evaluate on user click. must be in aitem() bloc :
accordion { aitem(txt) { alabel(lib) { code }; ...} ... }
ex
alert
def alert(*txt)
alert(txt): modal popup with text (as in html)
ex
anim
def anim(n,&blk)
shot peridicly a bloc parameter
no threading: the bloc is evaluated by gtk mainloop in main thread context
return handle of animation. can be stoped by delete(anim) // NOT WORK!, return a Numeric...
ex
append
def append(text)
ex
append and prompt
def append_and_prompt(text)
ex
append to
def append_to(cont,&blk)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
append the result of bloc parameter to a contener (stack or flow)
thread protected
Usage :
@stack= stack {}
. . . .
append_to(@stack) { button("Hello") }
ex
apply options
def apply_options(w,options)
apply some styles property to an existing widget.
options are :size, :width; :height, :margins, :bg, :fg, :font
apply_options(w,
:size=> [10,10],
:width=>100, :heigh=>200,
:margins=> 10
:bg=>'FF00AA",
:fg=> Gdk::Color:RED,
:tooltip=> "Hello...",
:font=> "Tahoma bold 32"
)
ex
ask
def ask(*txt)
show a modal dialog, asking yes/no question, return boolean response
ex
ask color
def ask_color()
modal dialog asking a color
ex
ask dir to read
def ask_dir_to_read(initial_dir=nil)
ask a existent dir name
ex
ask dir to write
def ask_dir_to_write(initial_dir=nil)
ask a dir name
ex
ask file to read
def ask_file_to_read(dir,filter)
File dialog
ask a existent file name
ex
ask file to write
def ask_file_to_write(dir,filter)
ask a filename for creation/modification
ex
attribs
def attribs(w,options)
Commands
common widget property applied for (almost) all widget.
options are last argument of every dsl command, see apply_options
ex
autoslot
def autoslot(w=nil)
slot() precedently created widget if not sloted.
this is done by attribs(w) which is call after construction of almost all widget
ex
background
def background(color,options={},&b)
set a background color to current container
Usage : stack { background("FF0000") { flow { ...} } }
ex
backgroundi
def backgroundi(color,options={},&b)
ex
bourrage
def bourrage(n=1)
ex
box
def box()
box { } container which manage children widget without slot (pack())
in parent container.
Use it for cell in table, notebook : table { row { cell(box { });... }; ... }
ex
button
def button(text,option={},&blk)
create button, with text (or image if txt start with a '')
block argument is evaluate at button click
ex
button expand
def button_expand(text,initiale_state=false,options={},&b)
a button which show a sub-frame on action
ex
button icon text
def button_icon_text(icon,text="",options={},&b)
a button with icon+text verticaly aligned,
can be call anywhere, and in htool_bar_with_icon_text
option is label options and isize ( option for icon size, see label())
ex
button list
def button_list()
ex
buttoni
def buttoni(text,option={},&blk)
create button, with text (or image if txt start with a '')
block argument is evaluate at button click, slotied :
packed without expand for share free place
ex
calendar
def calendar(time=Time.now,options={})
calendar
Month Calendar with callback on month/year move and day selection :
calendar(Time.now-24*3600, :selection => proc {|day| } , :changed => proc {|widget| }
calendar respond to
• set_time(time) ; set a selected date from a Time object
• get_time() ; return Time of selected day
ex
• canvas
def canvas(width,height,option={})
Creative Commons BY-SA : Regis d'Aubarede
LGPL
Create a drawing area, for pixel/vectoriel draw
for interactive actions see test.rb fo little example.
@cv=canvas(width,height,opt) do
on_canvas_draw { |w,ctx| myDraw(w,ctx) }
on_canvas_button_press {|w,e| [e.x,e.y] } must return a object which will given to next move/release callback
on_canvas_button_motion {|w,e,o| n=[e.x,e.y] ; ... ; n }
on_canvas_button_release {|w,e,o| ... }
on_canvas_keypress {|w,key| ... }
end
for drawing in canvas, this commands are offered.
basic gtk comands can be uses to ( move_to(), line_to()... )
def myDraw(w,ctx)
w.init_ctx
w.draw_line([x1,y1,....],color,width)
w.draw_point(x1,y1,color,width)
w.draw_polygon([x,y,...],colorFill,colorStroke,widthStroke)
w.draw_circle(cx,cy,rayon,colorFill,colorStroke,widthStroke)
w.draw_rectangle(x0,y0,w,h,r,widthStroke,colorFill,colorStroke)
w.draw_pie(x,y,r,l_ratio_color_label)
w.draw_arc(x,y,r,start,eend,width,color_stroke,color_fill=nil)
w.draw_varbarr(x0,y0,x1,y1,vmin,vmax,l_date_value,width) {|value| color}
w.draw_image(x,y,filename)
w.draw_text(x,y,text,scale,color)
lxy=w.translate(lxy,dx=0,dy=0) move a list of points
lxy=w.rotate(lxy,x0,y0,angle) rotate a list of points
w.scale(10,20,2) { w.draw_image(3,0,filename) } draw in a transladed/scaled coord system
>> image will be draw at 16,20, and size doubled
end
ex
canvasOld
def canvasOld(width,height,option={})
DEPRECATED; Create a drawing area, for pixel draw
option can define closure :mouse_down :mouse_up :mouse_move
for interactive actions
ex
cell
def cell(w)
a cell in a row/table. take all space, centered
ex
cell bottom
def cell_bottom(w)
create a cell in a row/table, bottom aligned
ex
cell hspan
def cell_hspan(n,w)
a cell in a row/table. take space of n cells, horizontaly
ex
cell hspan left
def cell_hspan_left(n,w)
create a hspan_cell in a row/table, left justified
ex
cell hspan right
def cell_hspan_right(n,w)
create a hspan_cell in a row/table, right justified
ex
cell hvspan
def cell_hvspan(n,m,w)
a cell in a row/table. take space of n x m cells, horizontaly x verticaly
ex
cell left
def cell_left(w)
create a cell in a row/table, left justified
ex
cell pass
def cell_pass(n=1)
keep empty n cell consecutive on current row
ex
cell right
def cell_right(w)
create a cell in a row/table, right justified
ex
cell span
def cell_span(n=2,w)
a cell in a row/table. take space of n cells, horizontaly
ex
cell top
def cell_top(w)
create a cell in a row/table, top aligned
ex
cell vspan
def cell_vspan(n,w)
a cell in a row/table. take space of n cells, verticaly
ex
cell vspan bottom
def cell_vspan_bottom(n,w)
a cell_vspan aligned on bottom
ex
cell vspan top
def cell_vspan_top(n,w)
a cell_vspan aligned on top
ex
center
def center()
center { } container which center his content (auto-sloted)
TODO : tested!
ex
check button
def check_button(text="",value=false,option={},&blk)
create a checked button
state can be read by cb.active?
ex
chrome
def chrome(on=false)
show or supress the window system decoration
ex
clear
def clear(cont)
clear a containet (stack or flow)
thread protected
ex
clear append to
def clear_append_to(cont,&blk)
clear a container (stack or flow) and append the result of bloc parameter to this
container
thread protected
ex
clickable
def clickable(method_name,&b)
specific to gtk : some widget like label can't support click event, so they must
be contained in a clickable parent (EventBox)
Exemple: clickable(:callback_click_name) { label(" click me! ") }
click callback is definied by a method name.
see pclickable for callback by closure.
ex
close dialog
def close_dialog)
ex
color choice
def color_choice(text=nil,options={},&cb)
create a button wich will show a dialog for color choice
if bloc is given, it with be call on each change, with new color value as parameter
current color is w.get_color()
ex
color conversion
def color_conversion(color)
ex
combo
def combo(choices,default=nil,option={},&blk)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
Inputs widgets
combo box.
Choices are describes with:
• a Hash choice-text => value-of-choice
• or an array of string : value of choice is the index of choice in array
default: initiale choice, String (text of choice) or index of choice in array/hash of choices
bloc : called when a choice is selected, with text and value
methods defined:
• cb.get_selection() >> [text-selected, value-of-selected] or ['',-1]
Usage :
combo(%w{aa bb cc},"bb") { |text,index| alert("{text} at {index}") }
combo({"aa" => 20, "bb"=> 30, "cc"=> 40},0) { |text,index| alert("{text} at {index}") }
ex
• component
def component)
ex
css name
def css_name(name)
give a name to last widget created. Useful for css style declaration
ex
cv
def cv.rotate(lxy,x0,y0,angle)
ex
def style
def def_style(string_style=nil)
define a set ofcss style, to be apply to every widget of main window
if noparameter, load a file .rcZ
ex
delete
def delete(w)
delete a widget or a timer
thread protected
ex
dialog
def dialog(title="")
Dialog contents is build with bloc parameter.
call is bloced until action on Ok/Nok/delete button
return true if dialog quit is done by action on OK button
dialog("title") {
flow { button("dd") ... }
}
ex
dialog async
def dialog_async(title,config={},&b)
Dialog
Dialog content is build with bloc parameter.
Action on Ok/Nok/delete button make a call to :response bloc.
dialog is destoy if return value of :response is true
dialog_async("title",:response=> bloc {|dia,e| }) {
flow { button("dd") ... }
}
ex
dialog chooser
def dialog_chooser(title, action, button)
ex
do notification
def do_notification()
ex
edit
def edit(filename)
File Edit
dialog showing code editor
ex
entry
def entry(value,size=10,option={},&blk)
create a text entry for keyboard input
if block defined, it while be trigger on eech of (character) change of the entry
ex
error
def error(*txt)
modal popup with text and/or ruby Exception.
ex
exe
def exe(cmd,to=nil)
execute a asynchonous system command, as done in a shell.
output goes to log, pid of process is in $ruiby_script_pid
on linux/unix host, exe() use PTY gem , on Windows it use popen3
to parameter is timeout of IO.select which wait for stdout output.
ex
execute
def execute(line=nil)
ex
fentry
def fentry(value,option={},&blk)
create a integer text entry for keyboed input
option must define :min :max :by for spin button
ex
field
def field(tlabel,width,value,option={},&blk)
show a label and a entry in a flow. entry widget is returned
see fields()
ex
fields
def fields(alabel=[["nothing",""]],option={},&blk)
show a stack of label/entry and buttons validation/annulation
on button, bloc is invoked with the list of values of entrys
ex
flow
def flow(config={},add1=true,&b)
container : horizontal box, take all space available, sloted in parent by default
ex
flow paned
def flow_paned(size,fragment,&blk)
create a container which can containe 2 widgets, separated by movable bar
block invoked must create 2 widgets,horizonaly disposed
ex
flowi
def flowi(config={},add1=true,&b)
container : horizontal box, take only necessary space , sloted in parent
ex
force update
def force_update(canvas)
update a canvas
ex
frame
def frame(t="",config={},add1=true,&b)
a box with border and texte title, take all space
ex
framei
def framei(t="",config={},add1=true,&b)
a box with border and texte title, take only necessary space
ex
get as bool
def get_as_bool()
ex
get config
def get_config(w)
get a Hash aff all properties of a gtk widget
ex
get current container
def get_current_container()
ex
get history
def get_history(n=-1)
ex
get icon
def get_icon(name)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
raster images access
ex
get image from
def get_image_from(name,size=:button)
get a Image widget from a file or from a Gtk::Stock
image can be a filename or a predefined icon in GTK::Stock
for file image, whe can specify a sub image (sqared) :
filename.png[NoCol , NoRow]xSize
filename.png[3,2]x32 : extract a icon of 32x32 pixel size from third column/second line
see samples/draw.rb
ex
get line
def get_line()
ex
get pixbuf
def get_pixbuf(name)
ex
get selection
def get_selection()
ex
get stockicon pixbuf
def get_stockicon_pixbuf(name)
Imageinitialize(:label => nil, :mnemonic => nil, :stock => nil, :size => nil)'
ex
grid
def grid(names,w=0,h=0,options={})
create a grid of data (as list, but multicolumn)
use set_data() to put a 2 dimensions array of text
same methods as list widget
all columnes are String type
ex
gui invoke
def gui_invoke(&blk)
Invoke HMI from anywhere
if threader() is done by almost one window,
evaluate (instance_eval) the bloc in the context of this window
async: bloc will be evaluate after the return!
ex
gui invoke in window
def gui_invoke_in_window(w,&blk)
ex
gui invoke wait
def gui_invoke_wait(&blk)
if threader() is done by almost one window,
evaluate (instance_eval) the bloc in the context of this window
sync: bloc will be evaluate before the return. Warining! : imlementation is stupid
ex
haccordion
def haccordion()
create a horizontral accordion menu.
must contain aitem() which must containe alabel() :
accordion { aitem(txt) { alabel(lib) { code }; ...} ... }
ex
hide app
def hide_app)
ex
hradio buttons
def hradio_buttons(ltext=["empty!"],value=-1)
as vradio_buttons , but horizontaly disposed
ex
html color
def html_color(str)
parse color from RRggBB html format Ruiby_dsl.html_color
ex
htoolbar
def htoolbar(options={})
horizontal toolbar of icon button and/or separator
if icon name contain a '/', second last is tooltip text
Usage:
htoolbar { toolbat_button("text/tooltip" { } ; toolbar_separator ; ... }
ex
htoolbar with icon text
def htoolbar_with_icon_text(conf={})
horizontal toolbar of (icone+text)
htoolbar_with_icon_text do
button_icon_text "dialog_info","text info" do alert(1) end
button_icon_text "sep"
end
if icone name start with 'sep' : a vertical separator is drawn in place of touch
see sketchi
ex
ientry
def ientry(value,option={},&blk)
create a integer text entry for keyboed input
option must define :min :max :by for spin button
ex
image
def image(file,options={})
create a icon with a raster file
option can specify a new size : :width and :height, or :size (square image)
ex
init threader
def init_threader)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
implictly called by Ruiby window creator
initialize multi thread engine
ex
initialize
def initialize()
ex
islider
def islider(value=0,option={},&b)
create a slider
option must define :min :max :by for spin button
current value can be read by w.value
if bloc is given, it with be call on each change, with new value as parameter
if value is a DynVar, slider will be binded to the DynVar : each change of the var value will update the slider,
of no block given,each change of the slider is notifies to the DynVar, else change will
only call the block.
ex
label
def label(text,options={})
create label, with text (or image if txt start with a '')
spatial option : isize : icon size if image (menu,small_toolbar,large_toolbar,button,dnd,dialog)
ex
labeli
def labeli(text,options={})
ex
left
def left(&blk)
TODO : not tested!
ex
levelbar
def levelbar(start=0,options)
ex
list
def list(title,w=0,h=0,options={})
Creative Commons BY-SA : Regis d'Aubarede
LGPL
List
create a verticale liste of data, with scrollbar if necessary
define methods:
• list() : get (gtk)list widget embeded
• model() : get (gtk) model of the list widget
• clear() clear content of the list
• set_data(array) : clear and put new data in the list
• selected() : get the selected items (or [])
• index() : get the index of selected item (or [])
• set_selection(index) : force current selection do no item in data
• set_selctions(i0,i1) : force multiple consecutives selection from i1 to i2
if bloc is given, it is called on each selection, with array
of index of item selectioned
Usage : list("title",100,200) { |li| alert("Selections is : {i.join(',')}") }.set_data(%w{a b c d})
ex
• log
def log(*txt)
Logs
put a line of message text in log dialog (create and show the log dialog if not exist)
ex
make DynClass
def make_DynClass(h={"dummy"=>"?"})
Object binding
As Struct, but data member are all DynVar
see samples/dyn.rb
ex
make StockDynClass
def make_StockDynClass(h={"dummy"=>"?"})
make_DynClass, but data are saved at exit time.
see samples/dyn.rb
ex
make StockDynObject
def make_StockDynObject(oname,h)
ex
menu
def menu(text)
a vertial drop-down menu, only for menu_bar container
ex
menu bar
def menu_bar()
Menu
create a application menu. must contain menu() {} :
menu_bar {menu("F") {menu_button("a") { } ; menu_separator; menu_checkbutton("b") { |w|} ...}}
ex
menu button
def menu_button(text="?",&blk)
create an text entry in a menu
ex
menu checkbutton
def menu_checkbutton(text="?",state=false,&blk)
create an checkbox entry in a menu
ex
menu separator
def menu_separator()
ex
message
def message(style,*txt)
ex
name
def name()
ex
next row
def next_row()
ex
notebook
def notebook()
notebooks
create a notebook widget. it must contain page() wigget
notebook { page("first") { ... } ; ... }
nb.page=page> => active no page
ex
observ
def observ(&blk)
ex
on canvas button motion
def on_canvas_button_motion(&blk )
define action on mouse button motion on current canvas definition
ex
on canvas button press
def on_canvas_button_press(&blk)
define action on button_press
action must return an object whici will be transmit to motion/release handler
ex
on canvas button release
def on_canvas_button_release(&blk)
define action on mouse button press on current canvas definition
ex
on canvas draw
def on_canvas_draw(&blk)
define the drawing on current canvas definition
ex
on canvas key press
def on_canvas_key_press(&blk)
define action on keyboard press on current **window** definition
ex
on canvas resize
def on_canvas_resize(&blk)
ex
on destroy
def on_destroy(&blk)
ex
on resize
def on_resize(&blk)
ex
out
def out.get_color()
ex
page
def page(title,icon=nil)
a page widget. only for notebook container.
button can be text or icone (if startin by '', as label)
ex
pclickable
def pclickable(aproc=nil,options={},&b)
specific to gtk : some widget like label can't support click event, so they must
be contained in a clickable parent (EventBox)
Exemple: pclickable(proc { alert true}) { label(" click me! ") }
bloc is evaluated in a stack container
ex
pclickablie
def pclickablie(aproc=nil,options={},&b)
as pclickable, but container is a stacki
pclickablei(proc { alert("e") }) { label("click me!") }
ex
plot
def plot.maxlen(name,len)
ex
popup
def popup(w=nil)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
Popup
create a dynamic popup.
popup block can be composed by pp_item and pp_separator
Exemple :
popup { pp_item("text") { } ; pp_seperator ; pp_item('Exit") { exit!(0)} ; ....}
popup can be rebuild by popup_clear_append(w)
ex
popup clear append
def popup_clear_append(pp)
clear a existant popup, rebuild it by bloc eval
popup_clear_append(@pp) { pp_item(..) ; pp_separator() ....}
ex
pp item
def pp_item(text,&blk)
a button in a popup
ex
pp separator
def pp_separator()
a bar separator in a popup
ex
progress bar
def progress_bar(start=0,options)
Show the evolution if a numeric value. Evolution is a number between 0 and 1.0
w.progress=n force current evolution
ex
prompt
def prompt(txt,value="")
show a modal dialog, asking question, active bloc closure with text response
in parameters
prompt("Age ?") { |n| alert("Your age is {n-1}, bravo !")
ex
properties
def properties(title,hash,options={:edit=>false, :scroll=>[0,0]})
create a property shower/editor : vertical liste of label/entry representing the ruby Hash content
Edition: Option: use :edit => true for show value in text entry, and a validate button,
on button action, yield of bloc parameter is done with modified Hash as argument
widget define set_data()methods for changing current value
ex
propertys
def propertys(title,hash,options={:edit=>false, :scroll=>[0,0]},&b)
deprecated: see properties
ex
razslot
def razslot()
forget precedent widget oconstructed
ex
regular
def regular(on=true)
Some other layouts
set homogeneous contrainte on current container :
all chidren whill have same size
• stack : children will have same height
• flow : children will have same width
ex
• replace current
def replace_current(text)
ex
right
def right(&blk)
TODO : not tested!
ex
row
def row()
create a row. must be defined in a table closure
Closure argment should only contain cell(s) call.
many cell type are disponibles : cell cell_bottom cell_hspan cell_hspan_left
cell_hspan_right cell_left cell_pass cell_right cell_span cell_top cell_vspan
cell_vspan_bottom cell_vspan_top
row do
cell( label("ee")) ; cell_hspan(3, button("rr") ) }
end
ex
rposition
def rposition(x,y)
change position of window in the desktop. relative position works only in *nix
system.
ex
ruiby component
def ruiby_component()
can be included by a gtk windows, for use ruiby.
do an include, and then call ruiby_component() with bloc for use ruiby dsl
ruiby_component() must be call one shot for a window,
it initialise ruiby.
then append_to(),append_before()... can be use fore dsl usage
ex
ruiby exit
def ruiby_exit()
ex
save stock
def save_stock )
ex
script
def script(caption="Parameters",nb_column=2,hctx=nil)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
script
define a hmi corresponding to a script command.
see samples/script.rb
the layout created contains three zones:
• parameters : a set of entry, created with a DynObject which descriptor is hctx
• button zone : a table of widgets. widget are created with bloc traitment,
• a log zone : scolling area on text, appended with log() commande
• bottom fixed buttons : clear log and exit.
ex
• scrolled
def scrolled(width,height,&b)
Scrollable stack container
create a Scrolled widget with a autobuild stack in it
stack can be populated
respond to : scroll_to_top; scroll_to_bottom,
ex
scrolled win
def scrolled_win.index()
ex
self
def self.html_color(str)
ex
separator
def separator(width=1.0)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
create a bar (vertical or horizontal according to stack/flow current container)
ex
set as bool
def set_as_bool(v)
ex
set history
def set_history(n=-1)
ex
set name
def set_name(name)
ex
set trace
def set_trace(on)
ex
show all children
def show_all_children(c)
ex
show app
def show_app()
ex
show methods
def show_methods(obj=nil,filter=nil)
show methods of a object/class in log window
ex
slider
def slider(start=0.0,min=0.0,max=1.0,options={})
Create a horizontal bar with a stick which can be moved.
block (if defined) is invoked on each value changed
w.proess=n can force current position at n
ex
slot
def slot(w)
pack widget in parameter, share space with prother widget
this is the default: all widget will be sloted if they are not slotied
this is done by attribs(w) which is call after construction of almost all widget
ex
slot append after
def slot_append_after(w,wref)
append the widget w after anotherone wref)
thread protected
ex
slot append before
def slot_append_before(w,wref)
append the widget w before another one wref
thread protected
ex
sloti
def sloti(w)
pack widget in parameter, take only necessary space
ex
snapshot
def snapshot(filename=nil)
make a snapshot raster file of current window
can be called by user.
Is called by mainloop if string 'take-a-snapshot' is present in ARGV
only for Windows !!!
ex
source editor
def source_editor(args={},&blk)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
source editor
a source_editor widget : text as showed in fixed font, colorized (default: ruby syntaxe)
from: green shoes plugin
options= :width :height :on_change :lang :font
@edit=source_editor().editor
@edit.buffer.text=File.read(@filename)
ex
space
def space(n=1)
create a one-character size space, (or n character x n line space)
ex
spacei
def spacei(n=1)
ex
spacing
def spacing(npixels=0)
set space between each chidren of current box
ex
stack
def stack(config={},add1=true,&b)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
Slot : H/V Box or Frame
container : vertical box, take all space available, sloted in parent by default
ex
stack paned
def stack_paned(size,fragment,&blk)
Panned :
create a container which can containe 2 widgets, separated by movable bar
block invoked must create 2 widgets, vertivaly disposed
ex
stacki
def stacki(config={},add1=true,&b)
container : vertical box, take only necessary space , sloted in parent
ex
stock
def stock(name,defv)
Creative Commons BY-SA : Regis d'Aubarede
LGPL
Variable binding for widget : (shower/editor widget) <==> (int/float/string/bool variable)
ex
syst add button
def syst_add_button(label,&prc)
ex
syst add check
def syst_add_check(label,&prc)
ex
syst add sepratator
def syst_add_sepratator()
ex
syst icon
def syst_icon(file)
ex
syst quit button
def syst_quit_button(yes)
ex
systray
def systray(x=nil,y=nil,systray_config={})
ex
systray setup
def systray_setup(config)
ex
table
def table(nb_col=0,nb_row=0,config={})
Creative Commons BY-SA : Regis d'Aubarede
LGPL
table
create a container for table-disposed widgets. this is not a grid!
table(r,c) { row { cell(w) ; .. } ; ... }
or this form :
table { cell(w) ; cell(w2) ; next_row ; cell(w3), cell(w4) }
ex
terminal
def terminal(title="Terminal")
create a terminal window INTO the process : gtk terminal
for acces to internal state of the current process
type help command.
ex
text area
def text_area(w=200,h=100,args={})
multiline entry
w=text_area(min_width,min_height,options)
Some binding are defined :
• w.text_area ; get text area widdget (w is a ScrolledWindow)
• w.text="" ; set content
• puts w.text() ; get content
• w.append("data \n") ; append conent to the end of current content
• w.text_area.wrap_mode = :none/:word
ex
• text area dyn
def text_area_dyn(dynvar,w=200,h=100,args={})
multiline entry on dynvar
ex
threader
def threader(per)
must be created by application (in initialize, after super), active the tread engine for
caller window.
if several windows, last created is the winner : gtk_invoke will throw to last treaded() window!
ex
toggle button
def toggle_button(text1,text2=nil,value=false,option={},&blk)
two state button, with text for each state and a initiale value
value can be read by w.active?
value can be changed by w.set_active(true/false)
callback is called on state change, with new value as argument
ex
toolbar button
def toolbar_button(name,tooltip=nil,&blk)
ex
toolbar separator
def toolbar_separator()
ex
tooltip
def tooltip(value="?")
give a tooltip to last widget created.
ex
tr
def tr(old,neww)
ex
trace
def trace(*txt)
travce() : like alert(), but with a warning icone
ex
tree grid
def tree_grid(names,w=0,h=0,options={})
create a tree view of data (as grid, but first column is a tree)
use set_data() to put a Hash of data
same methods as grid widget
a columns Class are distinges by column name :
• raster image if name start with a ''
• checkbutton if name start with a '?'
• Integer if name start with a '0'
• String else
ex
• tv
def tv.terminal(term=nil)
@tv.override_font( Pango::FontDescription.new("courier bold 10"))
ex
update
def update(data)
ex
value
def value()
ex
var box
def var_box(sens,config={},add1=true,&b)
container : vertical or horizontal box (stack/flow, choice by first argument),
sloted in parent by default
ex
var boxi
def var_boxi(sens,config={},add1=true,&b)
container : vertical or horizontal box (stacki/flowi, choice by first argument),
sloted in parent by default
ex
vbox scrolled
def vbox_scrolled(width,height,&b)
ex
video
def video(url=nil,w=300,h=200)
Show a video in a gtk widget.
• if block is defined, it is invoked on each video progression (from 0 to 1.0)
• w.play
• w.stop
• w.uri= "file:///foo.avi"
• w.uri= "rtsp:///host:port/video"
• .progress=n force current position in video (0..1)
see samples/video.rb and samples/quadvideo.rb
ex
• vradio buttons
def vradio_buttons(ltext=["empty!"],value=-1)
create a liste of radio button, vertically disposed
value is the indice of active item (0..(n-1)) at creation time
define 2 methods:
• get_selected get indice of active radio-button
• set_selected(indice) set indice of active radio-button
ex
• w
def w.options(config)
p options if options && options.size>0
ex
widget
def widget.get_data()
ex
widget properties
def widget_properties(title=nil,w=nil)
ex
wtree
def wtree(w)
ex
Code of samples/canvas.rb
def component()
stack do
htoolbar {
toolbar_button("open","Open file...") {
fload(ask_file_to_read(".","*.rb"),nil)
}
toolbar_button("Save","Save buffer to file...") {
@file=ask_file_to_write(".","*.rb") unless File.exists?(@file)
@title.text=@file
[email protected]
File.open(@file,"wb") { |f| f.write(content) } if @file && content && content.size>2
}
}
stack_paned(800,0.7) {
flow_paned(900,0.4) do
stack {
@title=sloti(label("Edit"))
@edit=source_editor(:lang=> "ruby", :font=> "Courier new 12").editor
sloti(button("Test...") { execute() })
}
stack {
@canvas= canvas(400,400) {
on_canvas_draw { |w,cr| redraw(w,cr) }
}
}
end
notebook do
page("Error") { @error_log=text_area(600,100,{:font=>"Courier new 10"}) }
page("Canvas Help") { make_help(text_area(600,100,{:font=>"Courier new 10"})) }
end
}
buttoni("reload canvas.rb...") do
begin
load (__FILE__)
rescue StandardError => e
error(e)
end
end
end
end
def redraw(w,ctx)
return if @redraw_error
return unless @blk
begin
@redraw_error=false
@error_log.text=""
begin
dde_animation=CanvasBinding.eval_in(@cv,ctx,@blk)
GLib::Timeout.add([dde_animation,50].max) { @canvas.redraw ; false } if dde_animation && dde_animation>0
rescue Exception => e
@redraw_error=true
error("Error in evaluate script :\n",e)
end
rescue Exception => e
@redraw_error=true
trace(e)
end
end
def execute()
[email protected]
@blk= content
File.open(@filedef,"w") {|f| f.write(content)} if content.size>30
@redraw_error=false
@canvas.redraw
rescue Exception => e
trace(e)
end
def log(*e)
@error_log.text+=e.join(" ")+"\n"
end
def trace(e)
@error_log.text=e.to_s + " : \n "+ e.backtrace[0..3].join("\n ")
end
def make_help(ta)
ta.text=DrawPrimitive.help_text
end
def make_example(ta)
src=File.dirname(__FILE__)+"/test.rb"
content=File.read(src)
ta.text=content.split(/(def component)|(end # endcomponent)/)[2]
end
def fload(file,content)
if File.exists?(file) && content==nil
content=File.read(file)
end
return unless content!=nil
@file=file
@mtime=File.exists?(file) ? File.mtime(@file) : 0
@content=content
@edit.buffer.text=content
end
end
#=====================================================================================
# Draw Primitives
#=====================================================================================
module DrawPrimitive
def error(*t) Message.error(*t) end
####################################### Simple drawing
def line(li,color="#000000",ep=2)
color=Ruiby.cv_color_html(color)
$ctx.set_line_width(ep)
$ctx.set_source_rgba(color.red/65000.0, color.green/65000.0, color.blue/65000.0, 1)
pt0,*poly=*li
$ctx.move_to(*pt0)
poly.each {|px| $ctx.line_to(*px) }
$ctx.stroke
end
def fill(li,color="#000000",ep=2)
color=Ruiby.cv_color_html(color)
$ctx.set_line_width(ep)
$ctx.set_source_rgba(color.red/65000.0, color.green/65000.0, color.blue/65000.0, 1)
pt0,*poly=*li
$ctx.move_to(*pt0)
poly.each {|px| $ctx.line_to(*px) }
$ctx.fill
end
def update(ms=20) @canvas.redraw ; sleep(ms*0.001) end
def tradu(l) l.each_slice(2).to_a end
def scale(l,sx,sy=nil) l.map {|(x,y)| [x*sx,y*(sy||sx)]} end
def trans(l,dx,dy) l.map {|(x,y)| [x+dx,y+dy]} end
def rotat(l,angle) sa,ca=Math.sin(angle),Math.cos(angle); l.map {|(x,y)| [x*ca-y*sa,x*sa+y*ca]} end
def crotat(l,x,y,angle) trans(rotat(trans(l,-x,-y),angle),x,y) end
def cscale(l,x,y,cx,cy=nil) trans(scale(trans(l,-x,-y),cx,cy),x,y) end
def rotation(cx,cy,a,&blk) grotation(cx,cy,a,&blk) end
def grotation(cx,cy,a,&blk)
if a==0
yield
return
end
$ctx.translate(cx,cy)
$ctx.rotate(a)
yield rescue error $!
$ctx.rotate(-a)
$ctx.translate(-cx,-cy)
end
def gscale(cx,cy,a,&blk)
if a==0
yield
return
end
$ctx.translate(cx,cy)
$ctx.scale(a,a)
yield rescue error $!
$ctx.scale(1.0/a,1.0/a)
$ctx.translate(-cx,-cy)
end
def pt(x,y,color="#000000",ep=2)
line([[x,y-ep/4],[x,y+ep/4]],color,ep)
end
def axe(min,max,pas,sens)
x0=20
x1=15
l=[]; l << [x0,x0]
(min+2*x0).step(max,pas) { |v|
l << [sens==0 ? v:x0, sens==1 ? v: x0 ]
l << [sens==0 ? v:x1, sens==1 ? v: x1 ]
l << [sens==0 ? v:x0, sens==1 ? v: x0 ]
}
line(l)
end
def axes(x0,maxx,maxy,pasx,pasy)
axe(x0,maxx,pasx,0)
axe(x0,maxy,pasy,1)
end
def plot_yfx(x0,pas,&b)
l=[]
x0.step(700,pas) { |x| y= b.call(x) ; l << [20+x,20+y] }
line(l)
end
def plot_xyft(t0,tmax,pas,xy,color="#000000",ep=2,&b)
l=[]
t0.step(tmax,pas) { |t|
t1= b.call(t)
l << [xy[0].call(t1)+20,xy[1].call(t1)+20]
}
line(l,color,ep)
pt(*l.first,"#AAAAFF",4)
pt(*l.last,"#FFAAAA",4)
end
def text(x,y,text,scale=1)
$ctx.set_line_width(1)
$ctx.set_source_rgba(0, 0 ,0, 1)
if scale==1
$ctx.move_to(x,y)
$ctx.show_text(text)
else
gscale(x,y,scale) { $ctx.move_to(0,0); $ctx.show_text(text) }
end
end
def def_animate(ms)
@dde_animation= ms
end
def self.help_text()
h=<<EEND
pt(x,y,color,width)
draw a point at x,y. color and stroke width optional
line([ [x,y],....],color,width)
draw a polyline. color and stroke width optional
fill([ [x,y],....],color,width)
draw a polygone. color and stroke width optional
tradu(l) [0,1,2,..] ===> [[0,1],[2,3],...]
scale(l,sx,sy=nil) scale by (sx,sy), form 0,0
trans(l,dx,dy) transmate by dx, dy
rotat(l,angle) rotation by angle from 0,0
crotat(l,x,y,angle) rotation by angle from cener x,y
cscale(l,x,y,cx,xy=nil) scake by cx,cy from center c,y
grotation(cx,cy,a) { instr } execute instr in rotated context (for text/image)
gscale(cx,cy,a) { instr } execute instr in scaled context (for text/image)
def_animate( n ) ask to reexecute this script n millisencondes forward
axes((xy0,maxx,maxy,stepx,stepy)
draw plotter"s axes (to be well done...)
plot_yfx(x0,step) { |x| f(x) }
draw a funtion y=f(x)
plot_xyft(t0,step) { |t| t=Math::PI/(t/700) ; [fx(x),fy(t)] }
draw a parametric curve
text(x,y,"Hello")
draw a text
text(x,y,"Hello",coef)
draw a text scaled by coef
def_animation( ms )
ask to rexecute this script aech ms millisecondes
Examples
0.step(100,10) { |x| pt( rand*x, rand*x ,"#000",4)
line([ [0,0],[100,0],[100,100],[0,1000],[50,50],[0,0]],"#FF0000",4)
axes(20,800,800,20,10)
plot_yfx(10,3) { |x| 20+100+100*Math.sin(Math::PI*x/40)}
EEND
end
end
Ruiby.start_secure { RubyApp.new }
Code of samples/table2.rb
def component()
stack {
frame("") { table(2,10,{set_column_spacings: 3}) do
row { cell_left label "c1" ; cell_left label "c2" ; cell label "c3" ; cell label "c4" ;}
row { cell_right label "c1" ; cell_left label "c2" ; cell label "c3" ; cell label "c4" ;}
row { cell_right label "c1" ; cell_hspan(3,button("hspan 3")) }
row { cell_vspan_top(2,button("vspan 2")) ; cell label "c2" ; cell label "c3" ; cell label "c4" ;}
row { cell_pass; cell label "c2" ; cell_hspan_right(2,pan("hspan 2")) }
end }
flow {
frame("List") {
stack {
@list=list("Demo",0,200)
flow {
button("s.content") { alert("Selected= #{@list.selection()}") }
button("s.index") { alert("iSelected= #{@list.index()}") }
}
}
}
frame("Grid") {
stack {
@grid=grid(%w{nom prenom age},100,200)
flow {
button("s.content") { alert("Selected= #{@grid.selection()}") }
button("s.index") { alert("iSelected= #{@grid.index()}") }
}
}
}
}
button("Exit") { exit! }
}
######### Populate list & grid
10.times { |i| @list.add_item("Hello #{i}") }
@grid.set_data([["a",1,1.0],["b",1,111111.0],["c",2222222222,1.0],["c",2222222222,1.0],["c",2222222222,1.0]])
Thread.new() do 5.times {
sleep(1)
gui_invoke { @grid.add_row([Time.now.to_s,Time.now.to_i,Time.now.to_f]) }
} end
end
def pan(t)
box { button(t) ; button("2 lines") }
end
end
Ruiby.start do
window = RubyApp.new
end
Code of samples/testth.rb
def component()
stack do
flow {
stack { @lab=stacki { } }
separator stack { @fr=stacki { } }
}
sloti( button("Exit") { exit! })
end
end # endcomponent
def run1
@ss=0
sleep 2
loop do
sleep(0.2)
gui_invoke_wait { @[email protected] }
if @ss<20
gui_invoke { append_to(@lab) {
sloti(label(Time.now.to_f.to_s)) } }
else
gui_invoke { @lab.children[0..3].each { |w| delete(w) } }
end
end
end
def run2
ii=0
sleep 30
loop {
Open3.popen3("ping 10.177.235.1") { |si,so,se|
while str=(so.gets || se.gets)
if ii>10
gui_invoke_wait {
@fr.children[0..-3].each { |w| delete(w) }
}
ii=3
end
log str gui_invoke { append_to(@fr) { sloti(label(str.chomp)) } }
ii+=1
end
}
}
end
end
Ruiby.start do RubyApp.new end
Code of samples/animtext.rb
#!/usr/bin/ruby
# encoding: utf-8
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
require_relative '../lib/Ruiby'
#require 'Ruiby'
Ruiby.app(title: "Text Animation", width: 900, height: 300) do
l,size=nil,40
stack { l=label("Hello Ruiby...",font: "Arial bold #{1}",bg: "#05A") }
after(500) do
anim(20) do
size=size>100 ? 10 : size+0.2
options={
font: "Arial bold #{size}",
fg: "#%02X%02X%02X" % [50+(200-size%200),50+size%200,50+size%200]
}
apply_options(l, options)
end
end
end
Code of samples/test_systray.rb
def component()
systray(1000,850, icon: "media/angel.png") do
syst_icon HAPPY_ICON
syst_add_button "Reload" do |state| load(__FILE__) rescue log $! ; end
syst_add_button "Execute Test" do |state| move(100,100);show; update() end
syst_quit_button true
end # end
Code of samples/multi_window_threading.rb
#!/usr/bin/ruby
# encoding: utf-8
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
###########################################################
# multi_window_threading.rb :
# test threading :
# gui_invoke() and gui_invoke_in_window()
###########################################################
require_relative '../lib/Ruiby'
def run(lapp)
loop {
app=lapp[rand(lapp.length)]
gui_invoke_in_window(app) { @wdata.append "CouCou\n" }
gui_invoke { @wdata.append "CouCou in first window\n" }
p "appended to #{app.class}"
sleep 1
}
end
class RubyApp < Ruiby_gtk
def component
stack {
stacki {
label "window #{self.class}"
button "top" do
@wdata.append Time.now.to_s+"\n"
end
}
@wdata= text_area(400,100,:text=>"Hello\n")
buttoni("exit") { destroy(self) }
}
threader(10)
end
end
class RubyApp1 < RubyApp ; end
class RubyApp2 < RubyApp ; end
class RubyApp3 < RubyApp ; end
Ruiby.start do
l=[RubyApp1.new("1",400,100),RubyApp2.new("2",300,100),RubyApp3.new("3",200,100)]
Ruiby.update
Thread.new(l) { |lapp| run(lapp) }
end
Code of samples/test_include.rb
#!/usr/bin/ruby
# encoding: utf-8
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
require_relative '../lib/Ruiby'
class Win < Gtk::Window
include Ruiby
def initialize(t,w,h)
super()
add(@vb=Gtk::Box.new(:vertical, 3))
show_all
add_a_ruiby_button()
signal_connect "destroy" do Gtk.main_quit ; end
end
def add_a_ruiby_button()
ruiby_component do
append_to(@vb) do
button("Hello Word #{@vb.children.size}") {
add_a_ruiby_button()
}
end
end
end
end
Ruiby.start do Win.new("application title",350,10) end
Code of samples/netprog.rb
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
################################################################################
# select * from netstat join tasklist where *.to_s like '%1%' ;)
################################################################################
raise("not windows!") unless RUBY_PLATFORM =~ /in.*32/
require 'gtk3'
require_relative '../lib/Ruiby'
$fi=ARGV[0] || "LISTENING"
$filtre=Regexp.new($fi)
class Ruiby_gtk
def make_list_process()
hpid={}
%x{tasklist}.split(/\r?\n/).each { |line|
ll=line.chomp.split(/\s+/)
next if ll.length<5
prog,pid,_,_,*l=ll
hpid[pid]= [prog,l.join(" ")]
}
hpid
end
def net_to_table(filtre)
hpid=make_list_process()
ret=[]
%x{netstat -ano}.split(/^/).each { |line|
_,src,dst,flag,pid=line.chomp.strip.split(/\s+/)
prog,s = hpid[pid]||["?","?"]
ret << [flag,src,dst,prog,pid.to_i,s] if [flag,src,dst,prog,pid,s].inspect =~ filtre
}
ret.sort { |a,b| a[4]<=>b[4]}
end
end
Ruiby.app(:width => 0, :height => 0, :title => "NetProg #{$fi}") do
@periode=2000
stack do
@grid=grid(%w{flag source destination proc pid proc-size},500,100)
@grid.set_data(net_to_table($filtre))
buttoni("Refresh") { @grid.set_data(net_to_table($filtre)) }
flowi do
button("Filter") { prompt("Filter ?",$fi) { |value| $fi=value;$filtre=Regexp.new($fi) } }
button("Periode") {
prompt("periode (ms) ?",@periode.to_s) { |value|
delete(@ann)
@periode=[1000,20000,value.to_i].sort[1]
@ann=anim(@periode) {
Thread.new {
d=net_to_table($filtre) ; gui_invoke { @grid.set_data(d) }
} unless @active.active?
}
}
}
@active=check_button("Freese",false)
end
end
@ann=anim(@periode) {
Thread.new {
d=net_to_table($filtre) ; gui_invoke { @grid.set_data(d) }
} unless @active.active?
}
end
Code of samples/test.rb
def component()
(puts "\n\n####define style...####\n\n" ; def_style "* { background-image: -gtk-gradient(linear, left top, left bottom, from(#AAA), to(@888));border-width: 3;}") if ARGV.size>0 && ARGV[0]=~/css/i
after(1000) {puts "\n\n\n" ; Gem.loaded_specs.each {|name,gem| puts " #{gem.name}-#{gem.version}"} }
mlog 'before Component'
stack do
htoolbar_with_icon_text do
button_icon_text("open","Open...") { edit(__FILE__) }
button_icon_text("save","Save.."){ alert("Save what ?")}
button_icon_text("sep")
button_icon_text("undo","Undo") { alert( "undo")}
button_icon_text("redo","Redo") { alert("redo") }
end
flowi do
sloti(label( <<-EEND ,:font=>"Tahoma bold 12"))
This window is test & demo of Ruiby capacity. Ruby is #{RUBY_VERSION}, Ruiby is #{Ruiby::VERSION},
Gtk is #{Gtk::VERSION.join(".")} HMI code take #{File.read(__FILE__).split("comp"+"onent"+"()")[1].split(/\r?\n/).select {|l| l !~ /\s*#/ && l.strip.size>3}.size} LOC (without blanc lines,comment line,'end' alone)
EEND
end
separator
flow {
@left=stack {
test_table
test_canvas
}
separator
stack do
notebook do
page("","#home") {
stack(margins: 40){
image(Ruiby::DIR+"/../media/ruiby.png")
label("A Notebook Page with icon as button-title",{font: "Arial 18"})
buttoni("Test css defininition...") {
ici=self
dialog_async("Edit Css style...",:response => proc {def_style(@css_editor.editor.buffer.text);false}) {
@css_editor=source_editor(:width=>300,:height=>200,:lang=> "css", :font=> "Courier new 12")
@css_editor.editor.buffer.text="* { background-image: -gtk-gradient(linear, left top, left bottom, \nfrom(#AAA), to(@888));\nborder-width: 3;}"
}
}
}
}
page("List & grids") { test_list_grid }
page("Explorer") { test_treeview }
page("ex&dia") { test_dialog }
page("Properties") { test_properties(0) }
page("Source Ed") {
if ed=source_editor(:width=>200,:height=>300,:lang=> "ruby", :font=> "Courier new 8",:on_change=> proc { edit_change })
@editor=ed.editor
@editor.buffer.text='def comp'+'onent'+File.read(__FILE__).split(/comp[o]nent/)[1]
end
}
page("Menu") { test_menu }
page("Accordion") { test_accordion }
page("Pan & Scrolled") { test_pan_scroll}
end # end notebook
frame("Buttons in frame") {
flow { sloti(button("packed with sloti()") {alert("button packed with sloti()")})
@bref=sloti(button("bb")) ; button("packed with slot()") ;
}
}
frame("regular size sub-widget (homogeneous)") {
flow {
regular
5.times { |i| button("**"*(1+i)) ; tooltip("button <b>#{i+1}</b>") }
}
}
end
} # end flow
flowi {
button("Test dialogs...") { do_special_actions() }
button("Exit") { ruiby_exit }
}
mlog 'after Component'
end
end
def test_table
frame("Forms",margins: 10,bg: "#FEE") { table(2,10,{set_column_spacings: 3}) do
row { cell_right(label "state") ; cell(button("set") { alert("?") }) }
row { cell_right label "speed" ; cell(entry("aa")) }
row { cell_right label "size" ; cell ientry(11,{:min=>0,:max=>100,:by=>1}) }
row { cell_right label "feeling" ; cell islider(10,{:min=>0,:max=>100,:by=>1}) }
row { cell_right label "speedy" ; cell(toggle_button("on","off",false) {|ok| alert ok ? "Off": "On" }) }
row { cell label "acceleration type" ; cell hradio_buttons(%w{aa bb cc},1) }
row { cell label "mode on" ; cell check_button("",false) }
row { cell label "mode off" ; cell check_button("",true) }
row { cell_left label "Attribute" ; cell combo({"aaa"=>1,"bbb"=>2,"ccc"=>3},1) }
row { cell_left label "Color" ; cell box { color_choice() {|c| alert(c.to_s)} } }
end
}
end
def test_canvas()
flow do
stack do
button("Color") {
#alert("alert !") ; error("error !") ; ask("ask !") ;trace("trace !") ;
@color=ask_color()
}
tooltip("Please choose the <b>drawing</b> <i>color</i>...")
@epaisseur=islider(1,{:min=>1,:max=>30,:by=>1})
tooltip("Please choose the <b>drawing</b> pen <i>width</i>...")
end
@ldraw=[] ; @color= html_color("#FF4422");
canvas(200,100) do
on_canvas_draw { |w,cr|
@ldraw.each do |line|
next if line.size<3
color,ep,pt0,*poly=*line
cr.set_line_width(ep)
cr.set_source_rgba(color.red/65000.0, color.green/65000.0, color.blue/65000.0, 1)
cr.move_to(*pt0)
poly.each {|px| cr.line_to(*px) }
cr.stroke
end
}
on_canvas_button_press{ |w,e|
pt= [e.x,e.y] ; @ldraw << [@color,@epaisseur.value,pt] ; pt
}
on_canvas_button_motion { |w,e,o|
if o
pt= [e.x,e.y] ; (@ldraw.last << pt) if pt[0]!=o[0] || pt[1]!=o[1] ; pt
end
}
on_canvas_button_release { |w,e,o|
pt= [e.x,e.y] ; (@ldraw.last << pt)
}
end
stacki {
label("Popup test...")
popup(canvas(50,200) { }) {
pp_item("copy") { alert "copy.." }
pp_item("cut") { alert "cut..." }
pp_item("past") { alert "pasting.." }
pp_separator
pp_item("Save") { alert "Saving.." }
}
}
end
end
def test_treeview()
stack do
tr=tree_grid(%w{month name prename 0age ?male},200,300)
tr.set_data({
janvier: {
s1:["aaa","bbb",22,true],
s2:["aaa","bbb",33,false],
s3:["aaa","bbb",111,true],
s4:["aaa","bbb",0xFFFF,true],
},
fevrier: {
s1:["aaa","bbb",22,true],
s2:["aaa","bbb",33,false],
},
})
end
end
def test_dialog()
stack do
sloti(button_expand("Test button_expand()") {
flow { 2.times { |c| stack { 5.times { |a| label("#{c}x#{a}",{font: "arial 33"}) } } } }
})
buttoni("dailog...") do
rep=dialog("modal window...") {
label("eee")
list("aa",100,100)
}
alert("Response was "+rep.to_s)
end
space
buttoni("dailog async...") do
dialog_async("modal window...",{response: proc {|a| alert(a);true}}) {
label("eee")
list("aa",100,100)
}
end
buttoni(" Crud in memory ") { test_crud() }
end
end
def test_list_grid()
flow {
stack {
frame("CB on List") {
stacki{
@list0=list("callback on selection",100,200) { |li| alert("Selections are : #{li.join(',')}") }
@list0.set_data((0..1000).to_a.map(&:to_s))
buttoni("set selection no2") { @list0.set_selection(1) }
}
}
frame("Grid") {
stack { stacki {
@grid=grid(%w{nom prenom age},100,150)
flow {
button("s.content") { alert("Selected= #{@grid.selection()}") }
button("s.index") { alert("iSelected= #{@grid.index()}") }
}
} }
}
}
frame("List with getter") {
stack {
@list=list("Demo",0,100)
flowi {
button("s.content") { alert("Selected= #{@list.selection()}") }
button("s.index") { alert("iSelected= #{@list.index()}") }
}
}
}
}
10.times { |i| @list.add_item("Hello #{i}") }
@grid.set_data((1..30).map { |n| ["e#{n}",n,1.0*n]})
end
def test_properties(no)
flowi {
sloti(button("#harddisk") { alert("image button!")})
tt={int: 1,float: 1.0, array: [1,2,3], hash: {a:1, b:2}}
properties("props editable",tt,{edit: true}) { |a| log(a.inspect);log(tt.inspect) }
properties("props show",tt)
}
h={};70.times { |i| h[i]= "aaa#{i+100}" }
properties("very big propertys editable",h,{edit: true,scroll: [100,200]}) { |a| log(a.inspect);log(h.inspect) }
end
def test_crud()
$gheader=%w{id first-name last-name age}
$gdata=[%w{regis aubarede 12},%w{siger ederabu 21},%w{baraque aubama 12},%w{ruiby ruby 1}]
i=-1; $gdata.map! { |l| i+=1; [i]+l }
a=PopupTable.new("title of dialog",400,200,
$gheader,
$gdata,
{
"Delete" => proc {|line|
$gdata.select! { |l| l[0] !=line[0] || l[1] !=line[1]}
a.update($gdata)
},
"Duplicate" => proc {|line|
nline=line.clone
nline[0]=$gdata.size
$gdata << nline
a.update($gdata)
},
"Create" => proc {|line|
nline=line.clone.map {|v| ""}
nline[0]=$gdata.size
$gdata << nline
a.update($gdata)
},
"Edit" => proc {|line|
data={} ;line.zip($gheader) { |v,k| data[k]=v }
PopupForm.new("Edit #{line[1]}",0,0,data,{
"Rename" => proc {|w,cdata| cdata['first-name']+="+" ; w.set_data(cdata)},
"button-orrient" => "h"
}) do |h|
$gdata.map! { |l| l[0] ==h.values[0] ? h.values : l}
a.update($gdata)
end
},
}
) { |data| alert data.map { |k| k.join ', '}.join("\n") }
end
def test_menu
stack {
menu_bar {
menu("File Example") {
menu_button("Open") { alert("o") }
menu_button("Close") { alert("i") }
menu_separator
menu_checkbutton("Lock...") { |w|
w.toggle
append_to(@f) { button("ee #{}") }
}
}
menu("Edit Example") {
menu_button("Copy") { alert("a") }
}
}
@f=stacki { regular ; space ; space ; calendar() }
}
end
def test_accordion()
flow {
accordion do
("A".."G").each do |cc|
aitem("#{cc} Flip...") do
5.times { |i|
alabel("#{cc}e#{i}") { alert("#{cc} x#{i}") }
}
end
end
end
label "x"
}
end
def test_pan_scroll()
stack do
sloti(label("Test scrolled zone"))
stack_paned 300,0.5 do
vbox_scrolled(-1,20) {
30.times { |i|
flow { sloti(button("eeee#{i}"));sloti(button("eeee")) }
}
}
vbox_scrolled(-1,20) {
30.times { |i|
flow { sloti(button("eeee#{i}"));sloti(button("eeee"));sloti(button("aaa"*100)) }
}
}
end
end
end
def edit_change()
alert("please, do not change my code..")
end
def do_special_actions()
100.times { |i| log("#{i} "+ ("*"*(i+1))) }
dialog("Dialog tests") do
stack do
labeli " alert, prompt, file chosser and log "
c={width: 200,height: 40,font: "Arial old 12"}
button("Dialog",c) {
@std=nil
@std=dialog_async "test dialog" do
stack {
a=text_area(300,200)
a.text="ddd dd ddd ddd dd\n ddd"*200
separator
flowi{ button("ddd") {@std.destroy}; button("aaa") {@std.destroy}}
}
end
}
button("alert", c) { alert("alert is ok?") }
button("ask", c) { log ask("alert is ok?") }
button("prompt", c) { log prompt("test prompt()!\nveuillezz saisir un text de lonqueur \n plus grande que trois") { |reponse| reponse && reponse.size>3 }}
button("file Exist",c) { log ask_file_to_read(".","*.rb") }
button("file new/Exist",c) { log ask_file_to_write(".","*.rb") }
button("Dir existant",c) { log ask_dir_to_read(".") }
button("Dir new/Exist",c) { log ask_dir_to_write(".") }
button("dialog...") do
dialog("title") {
stack {
fields([["prop1","1"],["prop1","2"],["properties1","3"]]) {|*avalues| alert(avalues.join(", "))}
separator
}
}
end
button("dialog async...") do
dialog_async("title",:response=> proc { ask("ok") }) {
stack {
label "without validations.."
fields([["prop1","1"],["prop1","2"],["properties1","3"]])
separator
}
}
end
button("Timeline",c) { do_timeline() }
end
end
end
def do_timeline()
dialog("ruiby/gtk startup timestamps") do
lline=[[10 ,180]]
ltext=[]
xmin, xmax= $mlog.first[0], $mlog.last[0]
a,b,ot = (400.0-20)/(xmax-xmin) , 10.0 , 0
$mlog.each_with_index {|(time,text),i|
pos=a*time+b
h=50+i*15
lline << [pos,180] ;lline << [pos,h] ;lline << [pos,180]
ltext << [[pos+5,h],text+ "(#{time-ot} ms)"]
ot=time
}
labeli("Total time : #{xmax} milliseconds")
canvas(500,200) {
on_canvas_draw { |w,cr|
w.init_ctx("#774433","#FFFFFF",2)
w.draw_line(lline.flatten)
ltext.each { |(pos,text)| w.draw_text(*pos,text) }
}
}
end
end
# end
Code of samples/plot.rb
# encoding: utf-8
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
require_relative '../lib/Ruiby'
Ruiby.app width: 400, height: 300, title: "Ploter test" do
def aleac(pas=1)
l=[[50,0]]
100.times { l << [l.last[0]+rand(-pas..pas),l.last[1]+1] }
l
end
def alear()
l=[[50,50]]
100.times { l << [l.last[0]+rand(-4..4),l.last[1]+rand(-4..4)] }
l
end
a=b=c=nil
stack do
label("Test Ruiby 'plot' ",font: "Arial bold 22")
separator
a=plot(400,100,{"a"=> { data: aleac(), color: "#004050" , maxlendata: 100},
"b"=> { data: aleac(), color: "#FFA0A0"}})
b=plot(400,100,{"b"=> { data: aleac(20)}})
c=plot(400,100,{"c"=> { data: alear(),xminmax: [0,100],yminmax: [0,100]}})
end
t=3
i=0
anim(t) do
i+=1
puts Time.now.to_f*1000 if i%(1000/t)==0
a.scroll_data("a", [0,100,a.get_data("a").last[0]+rand(-5..5)].sort[1])
a.scroll_data("b", [0,100,a.get_data("b").last[0]+rand(-10..10)].sort[1]) if Time.now.to_i%10<5
b.get_data("b").each_cons(3) {|p0,p1,p2| p1[0]=(2*p1[0]+p0[0]+p2[0])/4 if p0 && p1 && p2}
b.get_data("b")[0][0]=(b.get_data("b")[1][0]+b.get_data("b")[0][0])/2
b.get_data("b")[-1][0]=(b.get_data("b")[-2][0]+b.get_data("b")[-1][0])/2
c.get_data("c").each {|p| p[0]=p[0]+rand(-1..+1); p[1]=p[1]+rand(-1..+1) }
b.redraw
c.redraw
end
end
Code of samples/dyn.rb
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
require_relative '../lib/Ruiby.rb'
################################ App test ###################################
Ruiby.app do
stacki {
labeli( <<-EEND ,font: "Arial 14",bg: "#004455", fg: "#CCCCCC")
Test variables binding for entry/slider/CheckButton/toggleButton/radioButton/label.
Observer pattern :
widget can be observer of a variable,
so variable modification will be showing in all widget observer,
and a edition by a observer widget will be notified to all widget concerned.
EEND
v1=DynVar.stock("v1",1)
v2=DynVar.stock("v2","99")
v3=DynVar.stock("v3",true)
v4=DynVar.stock("v4",1)
flow {
framei("Int value",margins: 20) {
framei("Dyn widget") {
flowi { labeli "dyn label: " ; label v1,bg: "#FFCCCC" ; bourrage 10 }
flowi { labeli "dyn entry : " ; entry v1 }
flowi { labeli "dyn radiobutton: " ; hradio_buttons(["FALSE","TRUE","two"],v1) }
flowi { labeli "dyn show/edit slider: " ; islider v1 }
flowi { labeli "dyn show slider: " ; islider v1 do end}
flowi { labeli "dyn checkButton: " ; check_button "!= 0",v3 }
flowi { labeli "dyn toggle: " ; toggle_button "FALSE","TRUE",v3 }
}
flowi { labeli "editor (not dyn) :" ; entry("") { |v| v1.value=v.to_i } }
flowi {
labeli "+/- button :"
button("v1++") { v1.value=v1.value+1}
button("v1--") { v1.value=v1.value-1}
}
}
framei("String value",margins: 20) {
framei("Dyn widget") {
flowi { labeli "dyn entry : " ; entry v2 }
}
flowi { labeli "editor (not dyn) :" ; entry("") { |v| v2.value=v } }
flowi { labeli "+/- button :" ; button("v2++") { v2.value=v2.value+"a"}; button("v2--") { v2.value=v2.value[0..-2] } }
}
framei("Boolean value",margins: 20) {
framei("Dyn widget") {
flowi { labeli "dyn check button: " ; check_button "True", v3 }
flowi { labeli "dyn check button: " ; check_button "True", v3 }
}
labeli(v3)
separator
flowi { button("set tot true ") { v3.value=true}; button("set to false") { v3.value=false } }
}
}
flow {
Lieu=make_DynClass({"adresse" => "unknown" , "ville" => "Rouen" })
l1=Lieu.new({"adresse" => "1 route du chemin vert", "ville" => "Caen"})
framei("ObjectBinding",margins: 20) {
flowi { labeli "adresse : " ,width: 200; entry l1.adresse}
flowi { labeli "ville : ",width: 200 ; entry l1.ville}
flowi { regular
button(" Validation ") { alert l1.to_h }
button(" Reset ") { l1.adresse.value=""; l1.ville.value="" }
}
}
Lieu2=make_StockDynClass({"adresse" => "unknown" , "ville" => "Rouen" })
l2=Lieu2.new("add",{"adresse" => "2 route du chemin vert", "ville" => "Caen"})
framei("Stoked ObjectBinding",margins: 20) {
flowi { labeli "adresse : " ,width: 200; entry l2.adresse }
flowi { labeli "ville : ",width: 200 ; entry l2.ville }
flowi {
regular
button("Validation") { alert l2.to_h }
button("Reset") { l2.adresse.value=""; l2.ville.value="" }
}
}
}
buttoni("Normal Exit") { ruiby_exit } # will save l2 data at exit time, (not done on exit!(0) )
}
end
Code of samples/minicalc.rb
# Creative Commons BY-SA : Regis d'Aubarede <[email protected]>
# LGPL
require_relative '../lib/Ruiby.rb'
Ruiby.app width: 300,height: 200,title:"Calc" do
chrome(false)
@calc=make_StockDynObject("calc",{"res"=> 0,"value" => "0" , "stack" => [] })
@calc.stack.value=eval @calc.stack.value
stack do
flowi {
sloti(toggle_button("D",false) {|v| chrome(v)})
frame("Calculator",margins: 20) do
flowi { labeli "Resultat: " ,width: 200 ; entry(@calc.res) ; button("reset") { @calc.res.value="" ; @calc.stack.value=["0","reset"]}}
flowi { labeli "Value: " ,width: 200 ; entry(@calc.value) ; button("reset") { @calc.value.value="" }}
flowi do
regular
'+ - * / syn cos'.split(' ').each { |op| button(op) { ope(op,@calc.res,@calc.value) } }
end
end
}
flowi {
regular
button("Reset") { @calc.stack.value=["0","reset"] ; @calc.res.value="0" ; @calc.value.value=""}
button("Trace") { alert((@calc.stack.value.slice(-20..-1)||@calc.stack.value).each_slice(2).map {|b,a| "%s %10.5f" % [a,b]}.reverse.join("\n")) }
button("Exit") { ruiby_exit }
}
end
def ope(ope,dvRes,dvVal)
return if dvVal.value==""
expr=ope.size==1 ? "#{dvRes.value.to_f.to_s} #{ope} #{dvVal.value.to_f.to_s}" : "Math.#{ope}(#{dvRes.value.to_f.to_s})"
res= eval(expr).to_f
@calc.stack.value.push(dvVal.value)
@calc.stack.value.push(ope)
(ope.size==1 ? dvRes : dvVal).value=res.to_s
#dvVal.value=""
rescue Exception
alert("Expretion exotique : #{expr}")
end
end
No example for : force_update, on_canvas_resize, on_canvas_key_press, canvasOld, clear, clear_append_to, show_all_children, slot_append_before, slot_append_after, snapshot, get_selection, vradio_buttons, fentry, field, out, text_area_dyn, spacei, progress_bar, levelbar, clickable, pclickable, pclickablie, var_box, var_boxi, accept, spacing, right, autoslot, razslot, backgroundi, haccordion, scrolled_win, popup_clear_append, get_icon, get_stockicon_pixbuf, get_image_from, get_pixbuf, exe, next_row, cell_vspan, cell_hvspan, cell_span, cell_hspan_left, cell_top, cell_bottom, cell_vspan_bottom, save_stock, set_name, observ, do_notification, set_as_bool, get_as_bool, set_trace, button_list, wtree, message, dialog_chooser, aaa_generalities, get_current_container, get_config, css_name, attribs, color_conversion, widget_properties, toolbar_separator, show_methods, video, tv, append_and_prompt, replace_current, get_history, set_history, get_line, terminal, init_threader, syst_add_sepratator, syst_add_check, systray_setup, show_app, hide_app, close_dialog, on_resize, on_destroy, rposition
made by samples/make_doc.rb
|
__label__pos
| 0.987977 |
Appcast for Sketch http://osx.iusethis.com/app/sketch version history with a sparkle via iusethis.com en-us http://www.bohemiancoding.com/sketch Bohemian Coding Sketch 1.0 is a innovative and fresh look at vector drawing for the Mac. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and controls. Though simple to use, it offers powerful vector drawing and text tools like perfect Boolean operations, Symbols and powerful Rulers, Guides and Grids. 93 vector drawing illustration mac art graphics Shareware Sketch 2.4.4 http://osx.iusethis.com/app/versions/12882#ver_72526 Version: 2.4.4
** Sketch 3.0 is now available **
- Updates links for our new website
]]>
72526 Tue, 15 Apr 2014 02:16:35 -0000 not specified
Sketch 2.4.3 http://osx.iusethis.com/app/versions/12882#ver_71226 Version: 2.4.3
- Improvements to SVG importing
- Fixes a bug where Artboard origins would appear at 0,0
- Improves security when storing documents in DropBox
- Various bug fixes
]]>
71226 Sat, 22 Feb 2014 13:20:08 -0000 not specified
Sketch 2.4.2 http://osx.iusethis.com/app/versions/12882#ver_68666 Version: 2.4.2
- Fixes a bug that could crash Sketch when undoing vector edits
- Fixes a bug where the hex field wouldn't accept valid hex colors
- Fixes a bug where ungrouping multiple groups wouldn't select all layers
- Fixes a bug where a blur would flip an inner shadows
- Fixes a bug where moving layer with the arrow keys wouldn't update the inspector
- Fixes a bug where grouping rotated layers would happen incorrectly
- Fixes a bug where a rotated mask would render its fill incorrectly
- Fixes a bug where the inspector could get stuck
- Fixes a bug where the Pen and path tool wouldn't get inserted into the correct artboard in some cases
- Dragging images into Sketch now gives them proper filenames
- Dragging an image on Sketch to open it now properly selects it in the canvas too
- Fixes a bug where you couldn't remove certain colors from the presets
- Fixes a rare crashes when opening existing documents
- Improves Round to Pixel Edge to now also round layer size and vector points
- Fixes a bug when Alpha mask wouldn't render at the correct resolution on @2x exports
- Improves Text layer snapping
- Fixes a bug where rotated lines would resize incorrectly. For existing lines: flatten them first
- Fixes a rare crasher when editing text fields
- New Text layer are now always inserted above the current layer
- Export-as PDF: Slices are now exported in reversed order; top-down instead of bottom-up as it was before
- Fixes a color inaccuracy in converting hex colors
- The 'Make Grid' tool no longer inserts object in confusing order
- 'Add slices for Selection' now selects the correct slice in the slice tool afterwards
- Adds better support for the standard OS color picker
- Fixes a few crashes
]]>
68666 Tue, 26 Nov 2013 02:40:27 -0000 not specified
Sketch 2.4.1 http://osx.iusethis.com/app/versions/12882#ver_68626 Version: 2.4.1
- Fixes a bug that could crash Sketch when undoing vector edits
- Fixes a bug where the hex field wouldn't accept valid hex colors
- Fixes a bug where ungrouping multiple groups wouldn't select all layers
- Fixes a bug where a blur would flip an inner shadows
- Fixes a bug where moving layer with the arrow keys wouldn't update the inspector
- Fixes a bug where grouping rotated layers would happen incorrectly
- Fixes a bug where a rotated mask would render its fill incorrectly
- Fixes a bug where the inspector could get stuck
- Fixes a bug where the Pen and path tool wouldn't get inserted into the correct artboard in some cases
- Dragging images into Sketch now gives them proper filenames
- Dragging an image on Sketch to open it now properly selects it in the canvas too
- Fixes a bug where you couldn't remove certain colors from the presets
- Fixes a rare crashes when opening existing documents
- Improves Round to Pixel Edge to now also round layer size and vector points
- Fixes a bug when Alpha mask wouldn't render at the correct resolution on @2x exports
- Improves Text layer snapping
- Fixes a bug where rotated lines would resize incorrectly. For existing lines: flatten them first
- Fixes a rare crasher when editing text fields
- New Text layer are now always inserted above the current layer
- Export-as PDF: Slices are now exported in reversed order; top-down instead of bottom-up as it was before
- Fixes a color inaccuracy in converting hex colors
- The 'Make Grid' tool no longer inserts object in confusing order
- 'Add slices for Selection' now selects the correct slice in the slice tool afterwards
- Adds better support for the standard OS color picker
- Fixes a few crashes
]]>
68626 Mon, 25 Nov 2013 13:24:38 -0000 not specified
Sketch 2.4 http://osx.iusethis.com/app/versions/12882#ver_68268 Version: 2.4
Performance Improvements:
- Grouping and Ungrouping layers is much faster
- Selecting large objects in the Layer List is now much faster
- Undo has been sped up significantly
- Duplicating large numbers of objects is now much faster
- Making a grid of objects is now much faster
- Moving large numbers of objects is now much faster
- Selecting multiple layers via the canvas is now faster too
New:
- Better Mask rendering
- One-click activation for Blur effects
- Pressing 0-9 keys now adjusts layer opacity
- Improves rendering speed, especially when zooming and panning
- Feedback form now stores your name and email address for the next time
Improvements:
- Speed improvements for saving and loading documents
- Improves the zoom tool (Z) with better icons
- Improved PDF Import
- Improved colour accuracy
- Right-click in the Pages list now works properly for non-selected pages too
- Adds compatibility options for Sketch Mirror 1.0.1
- Reduced file size when saving documents
- Sketch now properly remembers between documents and relaunches which fonts to use as the default
- Speed and reliability improvements to Text Editing
- Significant speed improvements when using circular gradients
- Selecting HSB colour values in the colour picker is now more predictable (H value never gets reset)
- Sketch Mirror exports now always get a white background
- Inner-outer strokes are now disabled in the UI when they can't be used
- The Slice tool now remembers the slice selection
- The 'Make Grid' tool remembers what margins you used last time
- Tab-key now works in the slice tool
- Hovering over a text layer now highlights its text, not the frame, making identification easier
Bug Fixes:
- Fixes a bug where rearranging layers in the layer list could have them jump around
- Fixes a bug where shadow wouldn't be rendered in the correct color
- Vector points now nudge correctly on rotated shapes
- Fixes a bug where searching would stop after the first character was typed
- Fixes a bug where an outer border could cause a doughnut-shaped path to fill completely
- Fixes a bug where copy-pasting subpaths would lead to confusing situations
- Fixes a bug in Convert Text to Outlines where the new layer could end up with no fills
- Individual rounded corners can now have decimal values
- Fixes a bug that would prevent Sketch from saving into folders that contained a slash in their name
- Fixes accuracy of layer snapping in nested groups and with text layers
- Fixes a bug where colour presets would change subtly when being reapplied
- Fixes a refresh issue when changing slice names
- Fixes a rendering bug when changing large spread values
- Fixes a few minor crashes
- Fixes a bug that could cause an artboard to be misaligned when adding
- Fixes a bug when snapping rotated layers
- Fixes a bug where slices wouldn't fit properly around their layers
- Fixes a bug where tabbing through the HSB fields could change their value
- Fixes a bug in boolean operations
- Fixes a bug where one couldn't add colour presets in the text colour picker
- Fixes a bug in shadow blurring
- Fixes bugs in editing multi-paragraph text
- Fixes backwards compatibility for loading presets
- Fixes rendering issues with combined blurs and blending
- Fixes a possible crasher when using blur on lines
- Fixes an undo bug in Rotate Copies
- Fixes rendering issues with inner shadows on (rotated) bitmaps
- Fixes refresh bugs when using undo
- Fixes a bug where grouping layers with masks could end up causing redraw issues
- Fixes a couple of rare crashes
]]>
68268 Thu, 14 Nov 2013 23:38:50 -0000 not specified
Sketch 2.3.1 http://osx.iusethis.com/app/versions/12882#ver_66446 Version: 2.3.1
- Tall artboards for Sketch Mirror are now getting auto-retina-ized too
- Improves stability when using Sketch Mirror
- Artboards sent to Sketch Mirror now always have a white background
- Fixes a bug that caused a crash when opening new documents
- You can once again tweak x/y/width/height values of subpaths in the inspector
- Zoom-tool click to zoom in has been improved
- When frequently zooming in and out you can now tell Sketch (via the preferences) to maintain the viewport
- Fixes a bug that could cause layers to jump when moving into artboards
- Fixes a few refreshing issues when editing text layers
- Negative rotation values entered now don't get converted anymore
- Fixes an undo issue when deleting a page
- Fixes a bug in the text color picker when using the screen Picker
- Fixes a crash in blur editing
- Fixes a crasher in editing grid lines
]]>
66446 Fri, 20 Sep 2013 18:08:40 -0000 not specified
Sketch 2.3.0 http://osx.iusethis.com/app/versions/12882#ver_65962 Version: 2.3.0
- Adds Support for Sketch Mirror: Our new iOS companion app that lets you mirror designs in Sketch on your iOS devices
- EPS and PDF import; dragging a PDF into Sketch now gives you full access to all text and path info
- Major speed and performance improvements: Zooming and Panning is now much faster
- Working in large documents is now significantly faster as well
- New layer style: Background Blur
- Much more precise Boolean Operations
- Supports pasting vectors from Illustrator
- Major stability improvements
- Toolbar icons for Mask and Scale
- Pages menu now shows previews and lets you manage pages directly
]]>
65962 Mon, 02 Sep 2013 21:19:08 -0000 not specified
Sketch 2.2.4 http://osx.iusethis.com/app/versions/12882#ver_63056 Version: 2.2.4
- Retina Export can now export the ‘@1x’ version too
- A new ‘Welcome to Sketch’ panel with a newsletter, tutorials, links and more.
- Double-clicking a text layer now selects the word being clicked on
- Shape Tool adds X & Y Fields in the toolbar for the selected point
- Sketch now respects the alpha mask on images when adding a gradient
- Improves overall reliability of text editing
- Various improvements to SVG exporting
- Dropping images or adding shapes now inserts them above the selected layer
- Text and Bitmap layers can now have multiple shadows
- Fixes a bug that accidentally disabled shadow spread for shapes too
- Fixes a bug where a fill could leak from behind an inner stroke
- Fixes a bug in Image transformations
- Fixes a bug where an image with a blur or color adjust would disappear when a color fill was enabled
- Grid lines in the color picker can now be hidden temporarily using the Option key
- Fixes a bug where a 0px border would produce blurry edges on a shape
- Fixes a bug where double-clicking a layer in the layer list could have it jump randomly
- Fixes a bug where scaling an edited rectangle could destroy the edits
- Greatly improves the speed of resizing layers and groups
- Fixes a color crasher when picking non-standard colors
- Copy-pasting objects between Artboards should be more predictable now
- When copy-pasting bitmaps with rectangular marquee, colours no longer change
- Fixes a bug where resizing a group after moving its contents could have it jump back to its original position
- Fixes a bug where the layer list wouldn't update after dragging in an image from the desktop if you were in the slice tool
- Fixes a bug where duplicating pages in the Pages sheet would not refresh the canvas properly
- Fixes a bug where some text layers could appear cut off or appear to move slightly on export
- Layer selection is now preserved when switching back and forth between pages
- When 'Zoom on Selection' is turned on, it now also zooms in/out on bitmap's selections properly
- Pressing CMD+D inside the bitmap tool now duplicates the selected area instead of the entire layer
- Right-click 'delete' on a slice in the layer list now works as it should
- When Vectorizing a stroke with a gradient, we now also transfer the gradient over
- Duplicating or Copy-pasting now has Sketch make sure that the slice name isn't in use already
- Undoing a layer insert will no longer put a thick grey band on the screen
- Better slice and artboard snapping at different zoom levels
- Flattened layers no longer appear at the top of the layer list
- "Center Selection" is now disabled when there's no layer selected
- Fixes pasting via layer list and in canvas; layers no longer appear in semi-random places
- Changing the Artboard name will now change its slice name too - and vice versa
- Better trimming of Quicklook Previews
- Restores the behaviour where pressing Escape will exit the current group
- Fixes a bug where blended layers in artboards wouldn't show up correctly
- When selecting objects, Sketch now properly shows their combined width/height in the toolbar again
- Resizing a group after transforming its contents no longer makes the layers jump unexpectedly
- Zooming out no longer centers on the artboard. This was particularly annoying with larger artboards
- Fixes an incompatibility in opening Sketch documents from version 1
- Other bug fixes and performance improvements
CSS Export improvements:
- Text layers now export proper color values
- Box shadows are now exported as comma-separated values
- Shadows now also appends 'px' to the spread attribute
- Non-prefixed CSS gradients are now exported at the corect angle
Scripting improvements:
- You can now use -addLayerOfType: to add new layers do documents. Available choices: "rectangle", "text" or "group"
- 'textColor' and 'setTextColor:' are now available as scriptable properties on Text Layers
- New APIs has been added for adding/duplicating/removing pages and layer guides
]]>
63056 Mon, 24 Jun 2013 18:33:15 -0000 not specified
Sketch 2.1.1 http://osx.iusethis.com/app/versions/12882#ver_59656 Version: 2.1.1
- Fixes a bug where shadows would get displaced after zooming in - Improves the rendering accuracy of rounded rectangle corners - Fixes a few potential crashers or layout glitches when working with text layers - Adds a "Rotation" field in the inspector - Pressing any of the standard hotkeys (V/R/O etc) inside a text field will now perform the hotkey instead of filling in the character. - Fixes a bug where the rulers/grid would not match up with the canvas when zoomed in - Fixes a refresh issue when working with radial gradients at +100% zoom level - Fixes a bug where overlapping gradient points couldn't be deleted - There's now a setting to disable shadows on high zoom levels - Fixes a potential crasher when opening/closing artboard preview - Fixes a sandboxing-related bug where exporting a single slice would fail if the name contained a '/' - Improves selecting and inserting layers inside a rotated group - You can now batch-change boolean operations on subpaths by going to Edit > Combine in the menu - Fixes a bug where boolean operations would look weird on vectored text - Fixes a bug where gradients on blended images would disappear - New slices now take the shadow of layers inside groups into account - In Border Options, Dash field now show proper placeholder values - Fixes a bug where text field steppers wouldn't show up on hover. - Vectorize text now preserves the style attributes of the text for the new shape - Fixes an issue where a fill with a shadow could leak from behind its inner stroke - Fixes a bug with deleting parts from rotated or transformed images - Fixes a bug that might have caused text editing to slow down greatly - Kerning now changes automatically when you change font size - Changes the name of 'convert to shape' to 'convert to outlines' - Fixes a bug where adding a vector to a compound path would reset its style - Fixes a bug where an empty group could result in a crash on autosave - Artboard window remembers position - There's now a checkbox to not append "copy" after duplicated layers - There's now a checkbox if you don't want a new document to open on launch - Fixes a bug where the inspector wouldn't update after creating slices from artboards - EPS image data now also gets saved properly in the bundle file - Layers dropped into the canvas now always get dropped at the location of the mouse - Copy-pasting text layers now preserves their associated text style - Fixes a bug where single-underlined text would show up as double-underline in the inspector - Fixes an issue where slices wouldn't update their x/y values - Fixes a bug where editing certain text layers could result in a crash - Fixes a bug where selecting multiple items in the layer list wouldn't get reflected in the canvas - Fixes a bug where the style of an existing compound shape would get lost by adding a shape with the vector tool - Now shapes won't go between pixel bounds when resizing multiple layers - Fixes a bug where exiting the pen tool could have you end up with an empty path - Improves distance measuring between intersecting layers - Fixes a resizing issue with flipped layers - The cmd+click contextual layer menu now also digs into groups - Fixes an inaccuracy in the Rotate Copies tool - Fixes a potential crasher that could occur when resizing shapes to very small sizes - Fixes an bug where the current zoom would show up incorrectly - Fixes a bug with adding styles to multiple subpaths of the same shape - Fixes an issue with removing text borders - You can now hold down shift to align user guides to integer values - Non-rotated layers now snap properly to rotated layer bounds - There are now commands for turning uppercase text into lowercase and vice versa - Resize handles are no longer shown for text layers that contain only one word - Fixes a drawing issue with the position & size guides
]]>
59656 Tue, 02 Oct 2012 14:35:14 -0000 not specified
Sketch 2.1 http://osx.iusethis.com/app/versions/12882#ver_58498 Version: 2.1
# Major Features - Graphics updated for Retina display - Improved rendering quality and speed of inner shadows & glows - Improved accuracy of working with small layers - Layers can now sit between pixel boundaries # Artboard Enhancements - You can now open a preview of an artboard in a separate window - When moving an artboard, Sketch can now move the layers inside the artboard along with it - You can now duplicate artboards including the layers inside it - You can now scale artboards up along with the layers they contain. Perfect for making more detailed Retina assets. - When switching between artboards, if you have a layout grid turned on, the grid will now be in the centre of the artboard instead of on the left - Restyled the artboards so they look and work more like individual canvasses - You can now automatically hide the layers that are not visible within the current artboard - Zoom between artboard switching. With this option turned on, switching from (in this case) a 256×256 artboard to a 128×128 artboard will also zoom the canvas in by 2× to make the new slice occupy the same physical size on-screen as the previous artboard. Useful when comparing multiple resolutions of the same icons. # Exporting - @2x exports no longer go in their own subfolder - Fixes an issue where blurred layers wouldn't show up properly on @2x exports - When you include a '/' in the name of your slice, Sketch will put it in a subfolder. For example, naming your slice “nav/btns” will create an image named “btns” in a folder named “nav”. - Border CSS attribute is now properly "border" instead of "border style" # Interface Enhancements - You can now hide the layer list and inspector if you want. Especially useful on smaller screens, or to have more focus. - Improved inserting and moving guides by providing better cursor feedback - Disable zoom animations for when they don’t fit your flow - X/Y fields now also show relative to ruler origin, even when they're in a group - Added the ability to reorder multiple items in the layer list - Inspector now has proper Tab-key behaviour # Canvas Enhancements - Hand tool now also works during the drawing of shapes - You can now double-tap with two fingers to zoom in/out on artboards - Improves zooming behaviour when using trackpad pinch in/out or Magic Mouse - Fixes an issue where sometimes the reflection wouldn't be drawn on an image - Several improvements to the vector point popover to make it easier to change the corner radius - Fixes an issue with resizing images inside groups - ‘Set Style as Default’ now works for the vector tool as well - Improved behaviour on duplicating multiple layers - Added an easy way to see all content in the canvas by going to View > Center Canvas, or by double-tapping with two fingers outside artboards - Fixed an undo issue in the transform tool - Makes it easier to go into groups - Gradient stop points now always align to the edge of the layer whether or not 'layer guides' are enabled - ‘Zoom to Selection’ now uses a wider gap around the selected objects - Fixed an issue where ‘Move to Front’ would duplicate a layer instead # Text Editing - Fixed an undo issue with text on a path - Fixed an issue where the text layer wouldn't resize properly after text attributes changed - When pasting text into Sketch, the new text layer will now never be wider than the width of the canvas - Fixed an issue with editing text layers where the text field would lose focus # General - Saving files with larger images is now performed much faster - Fixed a few undo issues - Fixed a few random crashes - Many small tweaks and fixes - Improved SVG import - Significantly improves the responsiveness and speed of the app
]]>
58498 Thu, 16 Aug 2012 14:44:01 -0000 not specified
Sketch 2.0.3 http://osx.iusethis.com/app/versions/12882#ver_56116 Version: 2.0.3
- Adds a 'Mask with Selected Shape' item to make it easier to mask images
- Group bounds now take masks properly into account
- Fixes a bug when exporting blurred layers
- When deleting the last subpath of a shape, the shape itself now also gets deleted
- Fixes an undo issue when opening existing documents
- Fixes a crasher in the Artboard and Slice tools
- Groups can no longer be blurred
- Removes the 'feature' that caused resizing objects to be centred in the canvas because it caused unwanted side-effects
- Fixes a crashing issue when putting a Glow on a spiral shape
- Fixes a refresh issue when removing a fill from a layer with a bitmap-based style
- Save as Template works again
- Fixes an issue where not all font styles would update
- Improves the position tool (hold down option to try)
- Fixes an issue where resizing a layer after undoing & redoing a boolean operation could distort the subpaths.
- Improves reliability of resizing text layers
- Improves working with text styles
- Using the alt/option key when nudging a layer with the keyboard now duplicates it
- Fixes a bug that could cause all menu items to stay disabled
- Fixes a crashing issue with empty paths
- Initial slice size now also takes outer glow into consideration
- Pressing escape in a text field will put the focus back on the canvas now
- Fixes a few bugs related to 'Revert To Saved'
- Fixes a bug when exporting @2x graphics
- Fixes a rendering bug when combining noise fill with a shadow
- Fixes a little display bug in the rulers
]]>
56116 Mon, 18 Jun 2012 20:25:38 -0000 not specified
Sketch 2.0 http://osx.iusethis.com/app/versions/12882#ver_54398 Version: 2.0
Sketch 2.0 is now available.
It's a free upgrade for all registered users.
It's an enormous update. The entire UI has changed and all tools have been improved.
A few features were dropped from the 2.0 though:
- Distort effects
- Symbols (which will be properly reintroduced at a later point)
We hope you all enjoy the new stuff and please let us know what you think of the 2.0 update. To learn more about the 2.0, please visit the website
]]>
54398 Mon, 30 Apr 2012 22:18:20 -0000 not specified
Sketch 1.3 http://osx.iusethis.com/app/versions/12882#ver_49324 Version: 1.3
- Fixes bugs related to undo
- Fixes bugs in SVG importing
- Fixes a bug in Fullscreen on Lion
- Restores the Distribute & Align functionality
- Fixes bugs in the Smart Rotate tool
- Fixes bugs in the Scissors tool
- Cosmetic update to some of the toolbar icons
]]>
49324 Wed, 18 Jan 2012 22:08:40 -0000 not specified
Sketch 1.2 http://osx.iusethis.com/app/versions/12882#ver_44998 Version: 1.2
- Support for Lion's Autosave feature
- Support for Lion's Versions feature
- Support for Lion's Fullscreen feature
- Greatly improves stability
- Greatly improves undo support
- Improves SVG import and export
- Makes it easier to change curve modes from straight to rounded, curved etc
- Images are now better saved in bundles; PDFs no longer get converted to bitmaps
- Many other minor improvements and bugfixes
]]>
44998 Tue, 20 Sep 2011 07:32:35 -0000 not specified
Sketch 1.1 http://osx.iusethis.com/app/versions/12882#ver_39359 Version: 1.1
- Reintroduces the Decorate tool; easy for creating arrowheads etc.
- Multiple Selection in the Vector tool (using Shift-key)
- Drawing straight (or 45º) lines using the command key
- Other bugfixes and minor improvements
]]>
39359 Sun, 27 Feb 2011 18:20:35 -0000 not specified
Sketch 1.0.6 http://osx.iusethis.com/app/versions/12882#ver_37704 Version: 1.0.6
- Fixes a bug that made it impossible to create Symbol Layers.
- Improves SVG importing again.
- Fixes a bug in Merging layers.
- Fixes a bug that would prevent Sketch from zooming in to the center.
]]>
37704 Mon, 08 Nov 2010 15:38:45 -0000 10.6
Sketch 1.0 http://osx.iusethis.com/app/versions/12882#ver_36897 Version: 1.0
No changes specified]]>
36897 Wed, 08 Sep 2010 07:40:08 -0000 10.6
|
__label__pos
| 0.529631 |
All Subjects
All Types
Info
Grades
5-8
Permitted Use
Part of WNET
25 Favorites
594 Views
Estimating Profit from a Job
Students learn about estimation and rounding and practice rounding with decimal points.
Lesson Summary
Overview
In this TV411 activity, Franklin goes to the store to purchase supplies to complete a painting job. He works with Laverne to estimate the cost of materials using rounding and uses that estimate to calculate his rate of pay based on how long the job takes him.
Grade Level:
5-8
Suggested Time
1 hour
Media Resources
Estimating Costs, Estimating Profits QuickTime Video
Materials
Handout: A Sample Budget Sheet
Assessment: Level A
Assessment: Level B
Answer Key
The Lesson
Part I: Learning Activity
1. Read the following to your students: "Franklin asks Laverne to help him work out a budget for a job he has been offered, to paint a room in a friend's house. On a piece of paper, write down what you would need to know in order to determine if you are being paid enough to paint a room assuming you need to account for your time and the cost of supplies. How could you figure out your profit? Work in pairs." Note: Put the necessary information, such as time, cost of various supplies, and amount of pay, on the board so that the students are reminded of the important factors to consider.
2. Tell the students that they will now watch a video clip in which Franklin and Laverne discuss the costs and the profit of Franklin's painting job. Ask students to pay attention to careful details such as profits, costs, and items used for the job that are important factors in determining a budget.
3. Show the Estimating Costs, Estimating Profits QuickTime Video .
4. Distribute Handout: A Sample Budget Sheet .
5. Ask the students to work up a detailed budget for a painting job. They should estimate the costs of paintbrushes, rollers, and pans separately. They should make notes about how they rounded the estimates of the costs, and whether this will likely cause them to under-estimate or over-estimate the overall cost of the job.
6. Ask the students to work out their budget in a structured way, on the handout.
7. Discuss the students' budgets. Be sure to discuss with the students how they decide in a budget whether to round numbers up or down, and how to estimate their profit. Also consider how the students' budgets were like or unlike Franklin's, whether the budget sheet on the handout was useful to them, and why, and what differences they would make for a different kind of job. Be sure to draw on any students' experience with work and budgets.
Part II: Assessment
Assessment: Level A (proficiency): Students round off the cost of items to the nearest dollar or nearest 50 cents. Be careful to watch for students who think the answer always has to have 50 cents in it to have been rounded to the nearest 50 cents.
Assessment: Level B (above proficiency): Students apply their knowledge of estimation to compare the effects of rounding off to different levels of precision.
Contributor:
Funder:
You must be logged in to use this feature
Need an account?
Register Now
|
__label__pos
| 0.969176 |
Yii框架结合sphinx,Ajax实现搜索分页功能示例
本文实例讲述了Yii框架结合sphinx,Ajax实现搜索分页功能的方法。分享给大家供大家参考,具体如下:
效果图:
控制器:
<?php
namespace backendcontrollers;
use Yii;
use yiiwebController;
use yiidataPagination;
use SphinxClient;
use yiidbQuery;
use yiiwidgetsLinkPager;
use backendmodelsGoods;
class SouController extends Controller
{
//显示搜索页面
public function actionIndex()
{
//接受搜索值
$sou=Yii::$app->request->get('sou');
$p1=Yii::$app->request->get('p1');
$p2=Yii::$app->request->get('p2');
//echo $sou.$p1.$p2;die;
//sphinx搜索
$cl = new SphinxClient();
$cl -> SetServer('127.0.0.1',9312);
$cl -> SetConnectTimeout(3);
$cl -> SetArrayResult(true);
if($sou)
{
//只搜索条件
$cl -> SetMatchMode(SPH_MATCH_ANY);
}
else
{
//全局扫描
$cl -> SetMatchMode(SPH_MATCH_FULLSCAN);
}
//设置价格(注意:创建索引时,价格属性定义为int)
if($p1&&$p2)
{
$cl->SetFilterRange('price',$p1,$p2);
}
//搜索查询关键字
$res = $cl->Query($sou,"mysql_goods");
//ajax分页
$model=new Goods();
foreach ($res['matches'] as $key => $val)
{
$ids[] = $val['id'];
}
//查询条件数据
$query = $model->find()->where(['id'=>$ids]);
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count(),'defaultPageSize'=>3]);
//分页
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
//关键字变红
foreach($models as $k=>$v)
{
$models[$k]['goods_name']=str_replace("$sou","<font color='red'>$sou</font>",$v['goods_name']);//将关键字替换成红色字体
}
//显示列表,分配数据
return $this->render('index', [
'res' => $models,
'pages' => $pages,
'sou'=>$sou,
'p1'=>$p1,
'p2'=>$p2
]);
}
}
?>
视图层:
<?php
use yiihelpersHtml;
use yiiwidgetsActiveForm;
use yiiwidgetsLinkPager;
$form = ActiveForm::begin([
'action' => 'index.php?r=sou/index',
'method' => 'get'
]) ?>
<center>
<div id="list">
商品名称:
<input type="text" name="sou" value="<?php echo $sou?>">
价格区间:
<input type="text" name="p1" value="<?php echo $p1?>">---<input type="text" name="p2" value="<?php echo $p2?>">
<input type="submit" value="搜索">
<table border="1" style="width:500px;">
<tr>
<th>ID</th>
<th>商品名称</th>
<th>商品价格</th>
</tr>
<?php foreach($res as $key=>$v){?>
<tr>
<td><?php echo $v['id'];?></td>
<td><?php echo $v['goods_name'];?></td>
<td><?php echo $v['price'];?></td>
</tr>
<?php }?>
</table>
<!--分页-->
<?= LinkPager::widget(['pagination' => $pages]) ?>
</div>
</center>
<?php ActiveForm::end() ?>
<!--显示-->
<?php $this->beginBlock('test2') ?>
$(document).on('click', '.pagination a', function(e)
{
//阻止page显示,看地址
e.preventDefault();
var href = $(this).attr('href');
$.post(href,function(msg){
$('#list').html(msg);
})
});
<?php $this->endBlock();
$this->registerJs($this->blocks['test2'] , yiiwebView::POS_END)
?>
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
|
__label__pos
| 0.947749 |
Ups Are Called Tech Companies And Others Are Not
The definition of expertise is science or knowledge put into sensible use to unravel issues or invent helpful tools. Freud flirted with an essentialist definition when he equated masculinity with activity in contract to feminism passivity – though he came to see that equation as oversimplified. Ellul’s argument is that we’ve entered a historic phase by which we now have given up control over human affairs to technology and the technological crucial. Technology causes stress on the environment due to the harm it causes on natural habitats.
The time period info technology was coined by the Harvard Business Review, in an effort to make a distinction between goal-built machines designed to perform a limited scope of functions and common-goal computing machines that could be programmed for various duties. Now if we take a look at the same S-Curve in the context of innovation in regard to an industry or product we can see that there exists four main stages of innovation. Instructional know-how is a sub system of the principle system of instructional know-how.
In strict sense, educational expertise is anxious with determining and providing appropriate stimuli to the learner to produce a certain sort of responses for making learning more effective. And I usually spiralled into the Internet’s vortex myself, clicking, for example, on a tutorial article about expertise and distraction and someway winding up at a viral video about a Brazilian cyclist who is sideswiped by a rushing truck and lands, miraculously, on a mattress.
And while some imagine that digital expertise will drive social and economic teams further aside by way of excessive costs, Adams disagrees. If the modernization will go beyond this, I can actually say that technology can dehumanize the society. Mechanical controls and residential economics lessons didn’t regularly evolve into digital sewing machine controls; as an alternative, one know-how ousted another.
READ Fox News Monopoly, Memo Local News Stations.
A systematic technical planning process is required to supply the framework for identification of know-how growth wants. Another drawback with digital actuality is time: it takes an extended time period to develop a digital environment which will not be good news for any commercial enterprise wishing to speculate on this technology. In one business we have been challenged to discover a much cheaper different know-how that could provide the identical.
|
__label__pos
| 0.621429 |
else
Попробуем изменить функцию из предыдущего примера так, чтобы она возвращала не просто тип предложения, а целую строку Sentence is normal или Sentence is question.
def get_type_of_sentence(sentence):
last_char = sentence[-1]
if last_char == '?':
sentence_type = 'question'
else:
sentence_type = 'normal'
return "Sentence is " + sentence_type
print(get_type_of_sentence('Hodor')) # => 'Sentence is normal'
print(get_type_of_sentence('Hodor?')) # => 'Sentence is question'
Мы добавили else и новый блок. Этот блок выполнится, только если условие в if — ложь.
“Else” переводится «иначе», «в ином случае».
Задание
Реализуйте функцию normalize_url, которая выполняет так называемую нормализацию данных. Она принимает адрес сайта и возвращает его с https:// в начале.
Функция принимает адреса в виде АДРЕС или http://АДРЕС, но всегда возвращает адрес в виде https://АДРЕС. На вход функции также может поступить адрес в уже нормализованном виде https://АДРЕС, в этом случае ничего менять не надо.
Примеры вызова:
print(normalize_url('https://ya.ru')) # => 'https://ya.ru'
print(normalize_url('google.com')) # => 'https://google.com'
print(normalize_url('http://ai.fi')) # => 'https://ai.fi'
Есть два пути решения:
1. Можно сравнить первые 7 символов строки-аргумента со строкой http://.
2. Можно использовать оператор in, чтобы проверить, содержится ли подстрока слева в строке справа. Используется он так:
print('cat' in 'Moscato') # => True
А потом на основе этого добавлять или не добавлять https://.
Вам скорее всего потребуется отбросить ненужный кусок строки в начале оной. А помните, мы рассматривали способ получения кусочка от строки в её начале? Напоминаю:
# Берём 6 символов от начала
print('Winterfell'[:6]) # => 'Winter'
Так вот, можно отбросить те же самые 6 символов. Делается это так:
# Отбрасываем первые 6 символов
print('Winterfell'[6:]) # => 'fell'
Определения
• else — способ задать блок кода, который будет выполнен, если условие с if не удовлетворено.
Нашли ошибку? Есть что добавить? Пулреквесты приветствуютсяhttps://github.com/hexlet-basics
Упражнение доступно только авторизованным пользователям.
Пожалуйста, авторизуйтесь с помощью учётной записи GitHub, это необходимо для отслеживания прогресса выполнения уроков. Если у вас ещё нет учётной записи, то сейчас самое время создать аккаунт на GitHub.
|
__label__pos
| 0.587459 |
Questions tagged [difficulty-bomb]
The tag has no usage guidance.
Filter by
Sorted by
Tagged with
25
votes
1answer
6k views
What is the “difficulty bomb” and what is the goal of it?
The difficulty bomb is related to the switch to proof of stake. How does it work exactly and why is it going to help to switch to proof of stake?
15
votes
2answers
7k views
How does the Ethereum Homestead difficulty adjustment algorithm work?
From From EIP 2, the Homestead difficulty adjustment algorithm is: block_diff = parent_diff + parent_diff // 2048 * max(1 - (block_timestamp - parent_timestamp) // 10, -99) + int(2**...
23
votes
3answers
21k views
How is the Mining Difficulty calculated on Ethereum?
Having read various pieces of documentation, it's still not completely clear to me what dictates the difficulty rise, and how Ethereum difficulty levels differ to Bitcoin. In the past week ...
25
votes
2answers
17k views
When will the difficulty bomb make mining impossible?
I know the answer must be out there in the code already, but I couldn't figure out where exactly. Could someone do the maths for me: With block 200k the difficulty bomb started increasing the ...
12
votes
1answer
2k views
What if difficulty bomb makes mining impossible before POS release?
As mining difficulty raises and POS is still not ready, I was just wondering if POS release can still be on time compared to the difficulty bomb giving too high difficulty. In simpler words, is there ...
6
votes
3answers
2k views
Will metropolis delay the difficulty bomb?
Vitalik said the "ice age will be delayed anyways" (with metropolis). It's not that important or applicable either way, though on the other hand that given network going to be mucking around with ...
3
votes
1answer
332 views
Is there any way to diffuse the difficulty bomb and continue operating as though Ice Age doesn't exist?
I am running a private chain for my own purposes. Rather: it's a "public" discoverable chain but not any known or publicized chain. I want to continue to run this with PoW and no difficulty bomb. ...
5
votes
1answer
227 views
Parity: what is “bombDefuseTransition”
I see the Parity option for "bombDefuseTransition" here, under chain spec: https://github.com/paritytech/parity/wiki/Chain-specification Two questions: 1 - Why is this needed? (Would I be correct ...
|
__label__pos
| 0.997151 |
View Single Post
Old 10-08-2019, 06:55 PM #8
LHLaurini
New Member
Join Date: Oct 2019
City & State: Santa Maria, RS
My Country: Brazil
Line Voltage: 220VAC 60Hz
I'm a: Student Tech
Posts: 6
Default Re: Is it possible to recover a gamepad's firmware after accidentally erasing it?
Hey, people. I'd like your input.
Does anybody think it's worth to keep trying to recover the firmware? To me, it's starting to look more and more like a waste of time, since the chance of it actually working is pretty slim. Here's why:
1. I'd need to order a SWD programmer, since I don't currently own one;
2. Correctly identifying the proper connections looks like it'll be a challenge, assuming the labeling makes any sense. I'm starting to suspect it may not. You can see from the photos DEBUG_KC and DEBUG_SC are connected to the sticks and a few points have multiple labels ;
3. The firmware I found needs to be compatible. Though it looks like it might, I'll probably not work fully (for instance, the battery indicator likely won't).
4. After all, I can't really be sure the issue is actually a corrupt firmware, so it could be all a waste.
I'm thinking of scrapping the main board and using the daughter boards (most of the buttons are on them), the battery, the motors, the sticks and the case to make a "new" controller. It seems a cheap ATtiny88 would be good enough (it has enough pins, I hope I can fit what I need into 8k ). Then I'd just need a Li-Ion charger, a Bluetooth module and a few simple components. I think that could be quite a learning experience.
Of course, there may be no turning back from that. But hey, it's not working anyway, right?
So what do you think (and what would you do)?
LHLaurini is offline Reply With Quote
|
__label__pos
| 0.571104 |
Sign up ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
Quick background: I'm using texniccentre on windows vista, Miktex 2.9 installed.
I'm trying to make use of the iopams.sty file in order to use the \fl command in equations.
My header is set to this:
\usepackage{amsmath}
\usepackage{pifont}
\usepackage{amssymb}
\usepackage{iopams}
\usepackage{epsf}
\usepackage{pstricks}
\usepackage{bm}
\usepackage{psfig}
\usepackage{rotating}
\usepackage{array}
\usepackage{dcolumn}
\usepackage{longtable}
\usepackage{afterpage}
\usepackage{fancyhdr}
\usepackage[Lenny]{fncychap} %makes nice chapter headings
\usepackage{url} %use urls in references, etc.
\usepackage{multirow} % for different no of rows per column
%make refs [1-9]
%\usepackage[square,comma,numbers,sort&compress]{natbib}
\usepackage{natbib}
\usepackage{custom}
I get many undefined control sequences, it looks like each new command given in the iopams.sty file gives its own undefined control sequence (I apologise for not being able to give the output stream, texniccentre doesn't seem to want to let me copy and paste the output it gives).
Furthermore the \fl command itself is recognised as an undefined control sequence. This led me to wonder if \fl might be part of amsmath, so I took out iopams from my header, and it still gave \fl as an UCS. STrangely I can't seem to find the \fl command in either the amsmath.sty or iopams.sty files, yet I know for a fact it's in there as I've used it before and it's documented as part of iopams.
Does anyone have any experience using these bits in question? Thanks
share|improve this question
Welcome to TeX.SX! A tip: If you indent lines by 4 spaces, then they're marked as a code sample. You can also highlight the code and click the "code" button ({}). – Claudio Fiandrino Jul 18 '12 at 15:47
1 Answer 1
You can't use the sty on its own. At least the version (1997/02/13 v1.0) I found needs an accompaning class (e.g. iopart.cls). This class defines your command \newcommand{\fl}{\hspace*{-\mathindent}}.
I don't recommend the use of the class (it is very old).
Btw: Every latex run generate a log-file which contains the error messages.
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.994853 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.