Dataset Viewer
content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Advertisement
1. Code
2. HTML5
HTML5 Mastery: Encoding
by
Difficulty:IntermediateLength:MediumLanguages:
This post is part of a series called HTML5 Mastery Class.
HTML5 Mastery: Scoping Rules
HTML5 Mastery: Fragments
HTML5 Mastery
Encoding is just one of those things that need to be done right. If done wrong, everything seems to be broken and nothing works. If done right, no one will notice. This makes dealing with encoding so annoying.
Nevertheless, we are quite lucky and most of the things are already really well-prepared. We only need to ensure that our documents are saved (and transmitted) with the right encoding. The right encoding is the one we specify. It could be anything, as long as it contains all characters we need, and as long as we stay consistent.
There are three important text encoding rules for HTML:
1. Load the content with the right encoding.
2. Transmit the content with the same encoding.
3. Ensure that the client reads the content with the specified encoding.
In this article we will have a closer look at all three rules in more detail, especially the second and the third. In the end we will also look at form encoding, which has nothing to do with text encoding directly, but does indirectly. We will see why there is some connection.
Choosing the Right Encoding
Either we know directly that our content should be delivered in some exotic encoding or we should just pick UTF-8. There are many reasons why we would want to use UTF-8. It is not a great format for storing characters in memory, but it is just wonderful as a basis for data exchange and content transmission. It is basically a no-brainer. Nevertheless, one of the more common mistakes is to save files without proper encoding. As there is no text without encoding, we should choose the encoding carefully.
Users of Sublime Text and most other text editors have probably never faced a problem with wrong encoding, since these editors save in UTF-8 by default. There are editors, mostly for the Windows platform, which a use different default format, e.g., Windows-1252.
Even in Sublime Text it is one of the more standard operations to change the encoding of the file. In the File menu we select Save with Encoding and select the one we want. That’s it!
Saving Text Encoding Sublime Text
In principle every more advanced editor should have such options. Sometimes they are contained in an advanced save menu. For instance, the editor for Microsoft’s Visual Studio triggers a special dialog after clicking Advanced Save Options… in the File menu.
Visual Studio Advanced Save
We should make sure to use the right encoding. This will use the corresponding bytes for our content. UTF-8 has the major advantage of only requiring a single byte if we do not use a special character. At most 4 bytes per character are consumed. This is dynamic and makes UTF-8 an ideal format for text storage and transmission. The caveat is, however, that UTF-8 is not the best format for using strings from memory.
Controlling the Transmission
The HTTP protocol transmits data as plain text. Even if we decide to encode the transmitted content as GZip or if we use HTTPS, which encrypts the content, the underlying content is still just plain text. We’ve already learned that there is no such thing as just plain text. We always need to associate the content with some encoding to get a text representation.
An HTTP message is split in two parts. The upper part is called the headers. Separated by an empty line is the lower part: the body.
There are always at least two HTTP messages: a request and its associated response. Both types of messages share this structure. The body of a response is the content we want to transmit. The body of a request is only of interest for form submission, which we’ll care about later. If we want to provide some information on the encoding of the content, we have to supply some information in the header.
The following header tells the receiving side that the body contains a special text format called HTML, using the UTF-8 character set.
There is also the Content-Encoding header. We can easily confuse the content encoding with the actual text encoding of the content. The former is used to specify encoding of the whole package, e.g. GZip, while the latter is used as an initial setting for, e.g., parsing the provided content.
If we care about the correctness of this step we have to make sure that our web server sends the correct header. Most web frameworks offer such an ability. In PHP we could write:
In Node.js we may want to use the following, where res is the variable representing the request:
The transmitted header will set the text scanner of the HTML input to the provided setting. In the case of the previous example we use UTF-8. But wait: Initial setting! There are many ways to override this. If the actual content is not UTF-8, the scanner may recognize this and change the setting. Such a change may be triggered by Byte-Order-Mark (known as BOM) detection or by finding encoding-specific patterns in the content. In contrast, the former looks for artificially prepended patterns.
Finally, the encoding may change due to our HTML code. This can only be changed once.
Fixing the Encoding
Once the DOM constructor hits a meta tag, it will look for a charset declaration. If one is found, the character set will be extracted. If we can extract it successfully and if the encoding is valid, we set the new encoding for scanning further characters. At this point the encoding will be frozen, and no further changes are possible.
There is just one caveat. To check if the previous scanning was alright, we need to compare the characters that have already been scanned with the characters that would have been scanned. Hence we need to see if changing the encoding earlier would have made some difference. If we find a difference, we need to restart the whole parsing procedure. Otherwise the whole DOM structure may be wrong up to this point.
As a consequence we’ve already learned two lessons:
1. Place the <meta charset="utf-8"> (or some other encoding) tag as soon as possible.
2. Only use ASCII characters before specifying the charset attribute in HTML.
Finally, a good starter for a boilerplate looks as follows. As we learned in the previous article, we can omit the head and body tags. The snippet does two things right: It uses the correct document type, and it selects the character set as soon as possible.
The only remaining question is: What happens if I forget one of these three steps? Well, the first and third steps are the most important ones. The transmission is actually not that bad. If no initial encoding is given from the HTTP headers, the browser will select the initial encoding based on the user’s locale. With a German locale we get Windows-1252. This is actually the default for most countries. Some countries, like Poland or Hungary, select Latin2, also known as iso-8859-2.
In principle we do not have to worry about this initial encoding if we followed the best practices described earlier. ASCII is a subset of Unicode, and most of the listed encodings are actually just ASCII extensions to satisfy the specific needs of one or more countries. If we only use basic ASCII characters until the character set is specified, we should be fine.
Much more severe is a conflict between the stored / read or generated data, which is delivered to the client, and the statement in the meta tag. If something went wrong we may see renderings like the following. This is not a pleasant user experience.
Encoding Problem
Coming back to determining the right encoding, there are many reasons why UTF-8 would be the best choice. Any other encoding should at least be sufficient for the characters we want to display. However, if we provide form input fields, we may be in trouble. At this point we do not control the characters that are used any more. Users are allowed to input anything here. Let’s see how we can control the encoding for form input.
Submitting Forms
A form is submitted with a certain encoding type, which is not the same as the encoding type of a server’s response, e.g. GZip. The form’s encoding type determines how the form is serialized before sending it to the server. It is particularly useful in conjunction with the HTTP verb.
Ordinary form submissions use POST as HTTP verb, but GET, PUT and DELETE are also common. Only POST and PUT are supposed to use the body for content transmission in the request. The browser will construct the content with respect to the choice of the enctype attribute of the <form> element, specifying the encoding type. The encoding type is transported by setting the Content-Type header in the HTTP request.
There are three well-established encoding types:
1. URL encoded (default value, explicitly application/x-www-form-urlencoded)
2. Plain text (text/plain)
3. Multipart (multipart/form-data)
The first and the second are quite similar, but they have subtle (and very important) differences. The third variant is the most powerful method. It even allows the transporting of arbitrary files as attachments.
The key difference between the first two types is that URL encoded form transmission percent-encodes all names and values, which is not done by plain text. The percent-encoding guarantees that the receiving side can distinguish between names and values. This guarantee does not exist with plain text form submission. The third variant uses a boundary string to separate the entries, which is unique by construction.
Let’s visualize the differences by submitting a simple form. The form contains the following code:
Submitting the form without specifying any encoding type transmits the following body:
The URL encoding transforms the white-space characters to plus signs. Existing plus signs, like all “special” characters, are transformed by the percent-encoding rules. This especially applies to new lines, originally represented by \r\n, which are now displayed as %0D%0A.
Let’s see what the outcome for plain text encoding looks like.
The pairs are split by new lines. This is especially problematic for multi-line content and may lead to incorrect representations.
In a way the multipart encoding combines the advantages of plain text submission with a defined boundary, which essentially solves the problems of the plain text encoding. The only drawback is the increased content length.
The last two form encoding methods also displayed special characters exactly as we’ve entered them. Form transmission primarily uses the accept-charset attribute of the corresponding `</form>
` element. If no such attribute is given, the encoding of the page is used. Again, setting the correct encoding is important. In the future we will see a fourth encoding type, called `application/json`. As the name suggests, it will pack the form content into a JSON string. ## Conclusion Choosing the right encoding can be as easy as just picking UTF-8. Typical problems can be avoided by using the same encoding consistently. Declaring the encoding during transport is certainly useful, although not required, especially if we follow best practices for placing a `` element with the `charset` attribute. Form submission is a process that relies on the right encoding choice—not only for the text, but for the submission itself. In general we can always choose `multipart/form-data` as `enctype`, even though the default encoding type might be better (smaller) in most scenarios. In production we should never use `text/plain`. ## References * [UTF-8: The Secret of Character Encoding](https://htmlpurifier.org/docs/enduser-utf8.html) * [W3C Specification: Form Submission](http://www.w3.org/TR/html5/forms.html#attr-fs-enctype) * [W3C Specification: Encoding](http://www.w3.org/TR/encoding/) * [W3C Specification: Initial Encoding Determination](http://www.w3.org/TR/html51/syntax.html#the-input-byte-stream) * [StackOverflow: What is the boundary in multipart/form-data?](https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data)
Advertisement
Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started. | __label__pos | 0.861971 |
Program of bug simulation , JAVA Programming
You will be creating a World that consists of ants and doodlebugs. Each time you click the board each bug will do some of the following: move, bread, eat, and starve.
Ants will function in a certain way, and doodlebugs in another.
This assignment is based on Absolute Java.
900_Bug Simulation 1.png
Bug Rules
Ants
Move
1. Every time step the ant will attempt to move.
2. Pick a random direction using a random generator (up, right, down, or left).
3. If the space is on the grid, and not occupied then the ant will move there.
Breed
1. If an ant survives 3 time steps he will attempt to breed.
2. He breeds by creating a new ant in a space adjacent to himself.
3. If there is no empty space adjacent to himself to breed then he will not do so.
4. He will then wait 3 more time steps until tries to breed again.
Doodlebugs
Move
1. Every time step the doodlebug will move.
2. First he will check out each direction. If there is an ant in an adjacent space he will move there (consequently taking up the ants space and eating him!)
3. If there was no ant in an adjacent space he will move just like ants do.
4. Note: doodlebugs can't eat other doodlebugs
Breed
1. If a doodlebug survives 8 time steps he will attempt to breed.
2. He breeds in the same manner as an ant.
Starve
1. If an ant has not eaten an ant within the last 3 time steps, then at the end of the last time step he will die of starvation. You will remove him from the grid.
UML
Ants and Doodlebugs will extend from a generic Organism.
Create a UML diagram for the Organism, Ant and Doodlebug. This diagram may change as you develop your design, but having a basic flow will greatly help in the implementation.
Provided Files
1. World.java
2. Organism.java
3. Ant.java
4. Doodlebug.java
5. ant.png
6. doodlebug.png
Word
Methods you will use in your classes. Don't modify this class.
public Organism getAt(int x, int y)
1. Returns the Organism at the x, y position in the grid.
2. If there is no organism it returns null
public void setAt(int x, int y, Organism bug)
1. Sets the entry at the x, y position in the grid to the specified organism
public boolean pointInGrid(int x, int y)
1. Returns true if the point x, y is in the grid and false if it goes beyond the grid space (e.g. if x = -1 that is not in the grid)
Images
1. Put the two images in an images folder within your src
What you need to edit
1. Organism.java
2. Ant.java
3. Doodlebug.java
Organims
Here are the methods that the World calls on the Organisms. I assume you will want to make more methods, such as move...
Organism(World world, int x, int y)
1. Creates a new Organism
2. The coordinates in the grid (X and Y) are required so you can pick a new location relative to its current to move to, and breed at.
3. The World is required so you can call methods like getAt(x, y), setAt(x, y), and pointInGrid(x, y) on it.
public abstract String toString()
1. This method is written for you
2. Returns the string representation of the organism ("ant", "doodlebug"). Used by the World to determine which type of organism it is.
public void resetSimulation()
1. This method has been written for you
2. You will need to keep track of weather the organism has simulated this time step or not in an attribute of the class. This is important as it stops an organism from moving to a new place in the grid and then simulating again.
public boolean simulate()
1. This will set the attribute that keeps track of weather it has simulated to true. This method returns true if it simulates, and false if it doesn't (has already simulated)
2. If the organism was created this time step don't do the rest
3. Call move, then breed, then starve (only for doodlebugs).
4. You will then increment a time step counter
Ant and DoodleBug
1. I want you to figure out what goes here
Posted Date: 2/20/2013 1:08:00 AM | Location : United States
Related Discussions:- Program of bug simulation , Assignment Help, Ask Question on Program of bug simulation , Get Answer, Expert's Help, Program of bug simulation Discussions
Write discussion on Program of bug simulation
Your posts are moderated
Related Questions
Write nonrecursive implementations of the min() and floor() methods in BST.java. Make sure to use only one return in your method. Use an insertion sort (discussed in class) to s
Decode the Code Smugglers are becoming very smart day by day. Now they have developed a new technique of sending their messages from one smuggler to another. In their new techn
i have got project of Vending machine. would you please help me about how to start and how to use coding.thanks
Write code in JavaScript language to show the odd numbers among 20 to 100 using FOR statement. Note: No requirement to write whole HTML program. Just JavaScript code of need p
Indeed API integration and search bar fix (Java, Wordpress and PHP) I start a job portal on WP developed out of a customized template. We need an expert in integrating Indeed AP
Objective: create a simple object, put that object in a simple collection class, use that object and collection in a simple GUI application. Specification: Consider a Librar
How many JSP scripting elements and what are they? Ans) Three scripting language elements are there: a) declarations, b) scriptlets, c) expressions.
What are the different messaging paradigms JMS supports? Ans) Publish and Subscribe i.e. pub/suc and Point to Point i.e. p2p.
A value, the data assigned to a variable, may contain any sort of data. Though, JavaScript considers data to fall into many possible types. Based on the type of data, certain opera | __label__pos | 0.99176 |
File: vt_text.sql
package info (click to toggle)
virtuoso-opensource 6.1.6+dfsg2-4
• links: PTS, VCS
• area: main
• in suites: bullseye, buster, sid, stretch
• size: 260,992 kB
• ctags: 125,220
• sloc: ansic: 652,748; sql: 458,419; xml: 282,834; java: 61,031; sh: 40,031; cpp: 36,890; cs: 25,240; php: 12,692; yacc: 9,523; lex: 7,018; makefile: 6,157; jsp: 4,484; awk: 1,643; perl: 1,013; ruby: 1,003; python: 326
file content (481 lines) | stat: -rw-r--r-- 17,952 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
--
-- vt_text.sql
--
-- $Id$
--
-- Text triggers support.
--
-- This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
-- project.
--
-- Copyright (C) 1998-2012 OpenLink Software
--
-- This project is free software; you can redistribute it and/or modify it
-- under the terms of the GNU General Public License as published by the
-- Free Software Foundation; only version 2 of the License, dated June 1991.
--
-- This program is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--
--
create procedure DB.DBA.execstmt (in stmt varchar, out stat varchar, out msg varchar)
{
stat := '00000';
exec (stmt, stat, msg, vector (), 0, null, null);
if (stat <> '00000')
{
return 1;
}
return 0;
}
;
create procedure DB.DBA.vt_create_ftt (in tb varchar, in id varchar, in dbcol varchar, in is_intr integer)
{
declare stmt, stat, msg, verr varchar;
declare tbn0, tbn1, tbn2, data_table_suffix, theuser varchar;
-- tb := complete_table_name (fix_identifier_case (tb), 1);
verr := '';
tb := complete_table_name ((tb), 1);
tbn0 := name_part (tb, 0);
tbn1 := name_part (tb, 1);
tbn2 := name_part (tb, 2);
data_table_suffix := concat (tbn0, '_', tbn1, '_', tbn2);
data_table_suffix := DB.DBA.SYS_ALFANUM_NAME (replace (data_table_suffix, ' ', '_'));
theuser := user;
if (theuser = 'dba') theuser := 'DBA';
if (not exists (select 1 from DB.DBA.SYS_VT_INDEX where 0 = casemode_strcmp (VI_TABLE, tb)))
{
verr := 'FT035';
stat := '42S02';
msg := sprintf ('Text index should be enabled for the table "%s"', tb);
goto err;
}
if (not isstring (id))
select VI_ID_COL into id from DB.DBA.SYS_VT_INDEX where 0 = casemode_strcmp (VI_TABLE, tb);
if (not isstring (dbcol))
select VI_COL into dbcol from DB.DBA.SYS_VT_INDEX where 0 = casemode_strcmp (VI_TABLE, tb);
if (not exists (select 1 from DB.DBA.SYS_COLS where "TABLE" = tb and "COLUMN" = id))
{
stat := '42S22';
verr := 'FT036';
msg := sprintf ('The id column "%s" does not exist in table "%s" definition', id, tb);
goto err;
}
if (not exists (select 1 from DB.DBA.SYS_COLS where "TABLE" = tb and "COLUMN" = dbcol))
{
stat := '42S22';
verr := 'FT037';
msg := sprintf ('The data column "%s" does not exist in table "%s" definition', dbcol, tb);
goto err;
}
-- prevent making of error messages if creation is internal
if (is_intr = 2 and exists (select 1 from DB.DBA.SYS_KEYS
where KEY_TABLE = sprintf ('%s.%s.%s_%s_QUERY', tbn0, tbn1, tbn2, dbcol)))
return;
-- Upgrade an old database
if (not exists
(select 1 from DB.DBA.SYS_PROCEDURES where P_NAME = sprintf ('%I.%I.VT_HITS_%I', tbn0, tbn1, tbn2)))
{
stmt := concat (
sprintf (
'create procedure "%I"."%I"."VT_BATCH_PROCESS_%s" (inout vtb any, in doc_id int) {\n',tbn0, tbn1, data_table_suffix),
'declare invd any;\n
invd := vt_batch_strings_array (vtb);\n
if (length (invd) < 1) return;\n',
sprintf ('"%I"."%I"."VT_HITS_%I" (vtb, invd);\n', tbn0, tbn1, tbn2),
sprintf (
'log_text (''"%I"."%I"."VT_BATCH_REAL_PROCESS_%s" (?, ?)'', invd, doc_id);\n', tbn0, tbn1, data_table_suffix),
'log_enable (0);\n',
sprintf (
'"%I"."%I"."VT_BATCH_REAL_PROCESS_%s" (invd, doc_id);\n',tbn0, tbn1, data_table_suffix),
'log_enable (1);}\n');
DB.DBA.execstr (stmt);
}
-- Tables definition
stmt := sprintf ('CREATE TABLE "%I"."%I"."%I"
(TT_WORD VARCHAR, TT_ID INTEGER, TT_QUERY VARCHAR, TT_CD VARCHAR,
TT_COMMENT VARCHAR, TT_XPATH VARCHAR, TT_PREDICATE VARCHAR,
PRIMARY KEY (TT_WORD, TT_ID))',
tbn0, tbn1, concat (tbn2, '_', dbcol, '_QUERY'));
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := sprintf ('CREATE TABLE "%I"."%I"."%I"
(TTU_T_ID INTEGER, TTU_U_ID INTEGER, TTU_NOTIFY VARCHAR, TTU_COMMENT VARCHAR,
PRIMARY KEY (TTU_T_ID, TTU_U_ID))',
tbn0, tbn1, concat (tbn2, '_', dbcol, '_USER'));
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := sprintf ('CREATE TABLE "%I"."%I"."%I"
(TTH_U_ID INTEGER, TTH_D_ID any, TTH_T_ID INTEGER, TTH_TITLE VARCHAR,
TTH_URL VARCHAR, TTH_TS TIMESTAMP, TTH_NOTIFY VARCHAR,
PRIMARY KEY (TTH_U_ID, TTH_TS, TTH_D_ID, TTH_T_ID))',
tbn0, tbn1, concat (tbn2, '_', dbcol, '_HIT'));
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
-- Trigger definition
stmt := sprintf ('CREATE TRIGGER "%I_FTT_D" AFTER DELETE ON "%I"."%I"."%I" ORDER 3 %s
DELETE FROM "%I"."%I"."%I_%I_HIT" WHERE TTH_D_ID = "%I"; %s',
tbn2, tbn0, tbn1, tbn2, '{', tbn0, tbn1, tbn2, dbcol, id, '}');
-- Procedures definition
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := concat ( sprintf ('create procedure "%I"."%I"."VT_HITS_%I"', tbn0, tbn1, tbn2), '(inout vtb any, inout strs any)
{
declare tried, hits, doc_id, u_id integer;
declare len, inx int;
inx := 0;len := length (strs);tried := 0;',
sprintf ('if (registry_get (''tt_%s_%s_%s'') = ''OFF'') return;', tbn0, tbn1, tbn2),
'while (inx < len)
{
for select TT_ID, TT_QUERY, TT_COMMENT, TT_CD, TT_XPATH from ',
sprintf ('"%I"."%I"."%I"', tbn0, tbn1, concat(tbn2, '_', dbcol, '_QUERY')), '
where TT_WORD = aref (strs, inx) do
{
declare ids, ntf, xp any;
tried := tried + 1;
declare ii, is_xp int;
is_xp := 0;
if (TT_XPATH is not null and TT_XPATH <> '''')
{
xp := deserialize (TT_QUERY);
ids := vt_batch_match (vtb, xp);
is_xp := 1;
}
else
ids := vt_batch_match (vtb, TT_QUERY);
hits := hits + length (ids);
ii := 0;',
sprintf ('select TTU_NOTIFY, TTU_U_ID into ntf, u_id from "%I"."%I"."%I_%I_USER" where TTU_T_ID = TT_ID;', tbn0, tbn1, tbn2, dbcol),
'while (ii < length (ids))
{
doc_id := aref (ids, ii);
if (<INSERT_COND>)
{
', sprintf ('if ((is_xp = 0)
or (is_xp = 1 and exists (select 1 from "%I"."%I"."%I"
where "%I" = doc_id and xpath_contains ("%I", TT_XPATH))))',
tbn0, tbn1, tbn2, id, dbcol),
sprintf ('insert soft "%I"."%I"."%I" (TTH_U_ID, TTH_T_ID, TTH_D_ID, TTH_NOTIFY)
select TTU_U_ID, TT_ID, doc_id, ntf from "%I"."%I"."%I" where TTU_T_ID = TT_ID;
}
ii := ii + 1;
}
}
inx := inx + 2;
}
--dbg_obj_print ('' batch '', length (strs) / 2, ''distinct tried '', tried, '' hits '', hits);
}', tbn0, tbn1, concat (tbn2, '_', dbcol, '_HIT'),
tbn0, tbn1, concat (tbn2, '_', dbcol, '_USER')));
-- for WebDAV resources display only if user have read access
if (0 <> casemode_strcmp (tb, 'WS.WS.SYS_DAV_RES'))
stmt := replace (stmt, '<INSERT_COND>', '1 = 1');
else
stmt := replace (stmt, '<INSERT_COND>', 'WS.WS.CHECK_READ_ACCESS (u_id, doc_id)');
-- dbg_obj_print (stmt);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := sprintf (' create procedure "%I"."%I"."TT_WORD_FREQ_%I" (in w varchar)
{
declare l1, l2 integer;
l1 := 0; l2 := 0;
whenever not found goto none;
select sum (length (VT_DATA)),
sum (length (VT_LONG_DATA)) into l1, l2 from "%I"."%I"."%I_%I_WORDS"
where VT_WORD = w;
none:
return (coalesce (l1, 0) + coalesce (l2, 0));
}', tbn0, tbn1, tbn2, tbn0, tbn1, tbn2, dbcol);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := sprintf ('create procedure "%I"."%I"."TT_QUERY_%I" (in exp varchar, in u_id int, in comment varchar,
in notify varchar, in user_data varchar := null, in predicate varchar := null)
{
declare t_id, ix, len integer;
declare w any;
t_id := coalesce ((select top 1 TT_ID + 1 from "%I"."%I"."%I_%I_QUERY"
order by TT_ID desc), 1);
w := "%I"."%I"."TT_QUERY_WORD_%I" (exp, 0);
len := length (w); ix := 0;
while (ix < len) {
insert into "%I"."%I"."%I_%I_QUERY" (TT_ID, TT_QUERY, TT_WORD, TT_COMMENT, TT_CD, TT_PREDICATE)
values (t_id, exp, aref (w, ix), comment, user_data, predicate);
ix := ix + 1;
}
insert soft "%I"."%I"."%I_%I_USER" (TTU_T_ID, TTU_U_ID, TTU_NOTIFY, TTU_COMMENT)
values (t_id, u_id, notify, comment);
}', tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2, dbcol);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
-- XPATH search
stmt := sprintf ('create procedure "%I"."%I"."TT_XPATH_QUERY_%I" (in exp varchar, in u_id int, in comment varchar,
in notify varchar, in user_data varchar := null, in predicate varchar := null)
{
declare t_id, ix, len integer;
declare w any;
declare xp any;
xp := xpath_text (exp);
t_id := coalesce ((select top 1 TT_ID + 1 from "%I"."%I"."%I_%I_QUERY"
order by TT_ID desc), 1);
w := "%I"."%I"."TT_QUERY_WORD_%I" (xp, 1);
len := length (w); ix := 0;
while (ix < len) {
insert into "%I"."%I"."%I_%I_QUERY" (TT_ID, TT_QUERY, TT_WORD, TT_COMMENT, TT_XPATH, TT_CD, TT_PREDICATE)
values (t_id, serialize (xp), aref (w, ix), comment, exp, user_data, predicate);
ix := ix + 1;
}
insert soft "%I"."%I"."%I_%I_USER" (TTU_T_ID, TTU_U_ID, TTU_NOTIFY, TTU_COMMENT)
values (t_id, u_id, notify, comment);
}', tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2, dbcol);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
-- end XPATH search
declare pname varchar;
pname := sprintf ('"%I"."%I"."TT_QUERY_WORD_1_%I"', tbn0, tbn1, tbn2);
stmt := sprintf ('create procedure %s
(in tree any, inout best_w varchar, inout score integer, in topop integer, inout words any)
{
declare op integer;
if (isarray (tree))
{
op := aref (tree, 0);
if (op = 4 or op = 1210 or op = 1209)
{
declare inx int;
inx := 0;
while (inx < length (tree))
{
%s (aref (tree, inx), best_w, score, op, words);
inx := inx + 1;
}
}
else if (op = 1211)
{
%s (aref (tree, 2), best_w, score, op, words);
}
else if (op = 1)
{
declare ct int;
declare searched_word varchar;
searched_word := aref (tree, 2);
if (strchr (searched_word, ''*'') is not null)
return;
ct := "%I"."%I"."TT_WORD_FREQ_%I" (searched_word);
if (ct < score and topop <> 3)
{
score := ct;
best_w := searched_word;
}
else if (topop = 3)
best_w := searched_word;
}
else if (op = 3)
{
declare inx, sc1 int;
inx := 0;
while (inx < length (tree))
{
best_w := null;
sc1 := score;
score := 1000000000;
%s (aref (tree, inx), best_w, score, op, words);
if (words is null and best_w is not null)
words := vector (best_w);
else if (best_w is not null)
words := vector_concat (words, vector (best_w));
score := sc1;
best_w := null;
inx := inx + 1;
}
}
}
}', pname, pname, pname, tbn0, tbn1, tbn2, pname);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := sprintf ('create procedure "%I"."%I"."TT_QUERY_WORD_%I" (in exp varchar, in is_xpath integer)
{
declare tree, ws1 any;
declare w varchar;
declare sc int;
sc := 1000000000;
w := ''__'';
ws1 := null;
if (is_xpath = 0)
tree := vt_parse (exp);
else
tree := exp;
%s (tree, w, sc, 0, ws1);
if (w is not null)
return vector (w);
else if (isarray (ws1))
return ws1;
return vector (''__'');
}', tbn0, tbn1, tbn2, pname);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
stmt := sprintf ('create procedure "%I"."%I"."TT_NOTIFY_%I" () {
declare stat, msg, ntf, comment varchar;
declare _u_id, _ts, _d_id, _t_id, rc_call any;
for select distinct TTH_NOTIFY as _tt_notify from "%I"."%I"."%I_%I_HIT" where TTH_NOTIFY like ''%%@%%'' do
{
declare _message, _msg_tit varchar;
declare _cnt_hits integer;
declare _short_text varchar;
declare hits_data any;
_cnt_hits := 0;
_message := ''\\r\\nQuery/Hit Date/Document ID'';
hits_data := vector ();
for select TTH_U_ID, TTH_TS, TTH_D_ID, TTH_T_ID, TTH_NOTIFY
from "%I"."%I"."%I_%I_HIT" where TTH_NOTIFY = _tt_notify
order by TTH_TS
do
{
whenever not found goto nfq;
select coalesce (TT_COMMENT, TT_QUERY) into comment from
"%I"."%I"."%I_%I_QUERY" where TT_ID = TTH_T_ID;
nfq:
if (comment is null)
comment := ''*** no query ***'';
_cnt_hits := _cnt_hits + 1;
hits_data := vector_concat (hits_data, vector (vector (comment, TTH_TS, TTH_D_ID)));
_message := concat (_message, ''\\r\\n'', comment, ''/'',
substring (datestring (TTH_TS), 1, 19), ''/'',
cast (TTH_D_ID as varchar));
}
stat := ''00000'';
_msg_tit := concat (''Subject: Text trigger notification: New '',
cast (_cnt_hits as varchar) , '' hit(s) registered\\r\\n'');
_message := concat (_msg_tit, _message);
rc_call := 0;
if (__proc_exists (''%s.%s.%s_INFO_TEXT''))
{
rc_call := call (''%s.%s.%s_INFO_TEXT'') (_tt_notify, hits_data);
}
if (not rc_call)
{
exec (''smtp_send (null,?,?,?)'', stat, msg,
vector (_tt_notify, _tt_notify, _message));
}
update "%I"."%I"."%I_%I_HIT" set TTH_NOTIFY = '''' where TTH_NOTIFY = _tt_notify;
}
return;
}',
tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2, dbcol,
tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2,
tbn0, tbn1, tbn2, dbcol);
--dbg_obj_print (stmt);
if (DB.DBA.execstmt (stmt, stat, msg))
goto err;
insert into DB.DBA.SYS_SCHEDULED_EVENT (SE_NAME, SE_START, SE_SQL, SE_INTERVAL)
values (sprintf ('Notification for text hits on "%s.%s.%s"', tbn0, tbn1, tbn2), now (), sprintf ('"%I"."%I"."TT_NOTIFY_%I"()', tbn0, tbn1, tbn2), 10);
return 0;
err:
if (stat <> '42S01' and verr <> 'FT035' and verr <> 'FTT036' and verr <> 'FT037')
DB.DBA.vt_drop_ftt (tb, dbcol);
if (is_intr <> 2 and verr <> '')
{
signal (stat, msg, verr);
}
else if (is_intr <> 2 and verr = '')
{
signal (stat, msg);
}
}
;
create procedure DB.DBA.vt_drop_ftt (in tb varchar, in dbcol varchar)
{
declare stmt, stat, msg varchar;
declare tbn0, tbn1, tbn2 varchar;
-- tb := complete_table_name (fix_identifier_case (tb), 1);
tb := complete_table_name ((tb), 1);
tbn0 := name_part (tb, 0);
tbn1 := name_part (tb, 1);
tbn2 := name_part (tb, 2);
if (not exists (select 1 from DB.DBA.SYS_VT_INDEX where 0 = casemode_strcmp (VI_TABLE, tb)))
signal ('42S02', sprintf ('Text index not defined for "%s"', tb), 'FT034');
if (not isstring (dbcol))
select VI_COL into dbcol from DB.DBA.SYS_VT_INDEX where 0 = casemode_strcmp (VI_TABLE, tb);
stmt := sprintf ('DROP TRIGGER "%I"."%I"."%I_FTT_D"', tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."VT_HITS_%I"' , tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."TT_WORD_FREQ_%I"', tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."TT_QUERY_%I"', tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."TT_XPATH_QUERY_%I"', tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."TT_QUERY_WORD_1_%I"', tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."TT_QUERY_WORD_%I"',tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP PROCEDURE "%I"."%I"."TT_NOTIFY_%I"',tbn0, tbn1, tbn2);
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP TABLE "%I"."%I"."%I"', tbn0, tbn1, concat (tbn2, '_', dbcol,'_QUERY'));
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP TABLE "%I"."%I"."%I"', tbn0, tbn1, concat (tbn2, '_', dbcol, '_USER'));
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('DROP TABLE "%I"."%I"."%I"', tbn0, tbn1, concat (tbn2, '_', dbcol, '_HIT'));
-- make an empty procedure
DB.DBA.execstmt (stmt, stat, msg);
stmt := sprintf ('create procedure "%I"."%I"."VT_HITS_%I" (inout vtb any, inout strs any)
{ return; }', tbn0, tbn1, tbn2 );
DB.DBA.execstmt (stmt, stat, msg);
delete from DB.DBA.SYS_SCHEDULED_EVENT where SE_NAME = sprintf ('Notification for text hits on "%s.%s.%s"', tbn0, tbn1, tbn2);
return;
}
;
--#IF VER=5
--!AFTER
--#ENDIF
grant execute on DB.DBA.vt_create_text_index to public
; | __label__pos | 0.549881 |
Welcome :: Homework Help and Answers :: Mathskey.com
Welcome to Mathskey.com Question & Answers Community. Ask any math/science homework question and receive answers from other members of the community.
13,434 questions
17,804 answers
1,438 comments
59,225 users
Standard and General Form of the Circle's Equation?
+3 votes
Standard and General Form of the Circle's Equation?
Write the standard form of the equation and the general form of the equation of each circle of radius r and center (h, k).
(1) r = 3; (h, k) = (0, 0 )
(2) r = 5; (h, k) = (-5, 2)
asked Jan 16, 2013 in ALGEBRA 1 by homeworkhelp Mentor
1 Answer
+5 votes
Best answer
(1) r = 3; (h, k) = (0, 0 )
General Form equation is x2 + y2 – 2hx – 2ky + h2 + k2 – r2 = 0, where (h, k) is the centre and r, the radius.
x2 + y2 + 2(0)x – 2(0)y + 02 + 02 – 32 = 0
x2 + y2 – 32 = 0
x2 + y2 – 9 = 0
Standard Form Equation is (x – h)2 + (y – k)2 = r2 where (h, k) is the centre and r, the radius.
(x – 0) 2 + (y – 0) 2 = 32
x2 + y2 = 9 .
2) r = 5; (h, k) = (-5, 2)
General Form equation is x2 + y2 – 2hx – 2ky + h2 + k2 – r2 = 0, where (h, k) is the centre and r, the radius.
x2 + y2 –2(–5)x – 2(2)y + (–5)2 + 22 – 52 = 0
x2 + y2 + 10x – 4y + 25 + 4 – 25 = 0
x2 + y2 + 10x – 4y + 4 = 0
Standard Form Equation is (x – h)2 + (y – k)2 = r2 where (h, k) is the centre and r, the radius.
(x – (–5)) 2 + (y–2)2 = 52
(x + 5)2 + (y – 2)2 = 25
source: http://answers.yahoo.com/question/index?qid=20071125073022AADwDqu
answered Jan 16, 2013 by Naren Answers Apprentice
selected Jan 23, 2013 by homeworkhelp
Thank you!!! it helped a lot...
Related questions
... | __label__pos | 0.975044 |
Navigating Privacy and Security Concerns in Metaverse Apps
The rise of metaverse apps has ushered in a new era of virtual experiences and interactions. From gaming to socializing, these immersive platforms offer endless possibilities. However, with this new frontier comes a set of privacy and security concerns that users must navigate. In this article, we will explore the key issues surrounding privacy and security in metaverse apps and provide insights on how users can protect themselves.
Understanding Data Collection Practices
Metaverse apps often require users to create accounts and provide personal information. This data is collected for various purposes, such as user authentication, customization of virtual avatars, or targeted advertising. It is crucial for users to understand what data is being collected and how it will be used.
To ensure transparency, metaverse app developers should provide clear privacy policies that outline their data collection practices. Users should take the time to read these policies carefully before signing up or using the app. Additionally, it is advisable to choose apps that have a good track record of handling user data responsibly.
Safeguarding Personal Information
Protecting personal information is paramount when using metaverse apps. Users should be cautious about sharing sensitive data such as their full name, address, or financial information within these platforms unless absolutely necessary.
One way to safeguard personal information is by utilizing strong passwords for metaverse app accounts and enabling two-factor authentication whenever possible. This adds an extra layer of security by requiring users to verify their identity through another device or method.
Furthermore, it is essential to regularly update the metaverse app to ensure that any security vulnerabilities are patched promptly. Staying vigilant against phishing attempts or suspicious links within the app can also help prevent unauthorized access to personal information.
Managing Social Interactions
Metaverse apps thrive on social interactions between users, but this also opens up opportunities for potential privacy breaches or cyberbullying. Users should be mindful of the information they share with others and be cautious about accepting friend requests or engaging in private conversations with unknown individuals.
Most metaverse apps provide privacy settings that allow users to customize who can see their profile, interact with them, or access their personal information. Reviewing and adjusting these settings regularly can help users maintain control over their privacy within the virtual world.
In cases where inappropriate behavior or harassment occurs, users should report the incident to the app’s support team immediately. Metaverse app developers have a responsibility to address such issues promptly and take appropriate actions against offenders.
Staying Informed about App Updates
Metaverse apps are continuously evolving, which means that privacy and security concerns may arise as new features are introduced. It is essential for users to stay informed about app updates, especially those related to privacy and security enhancements.
Following official announcements from the app developer or joining user communities where updates are shared can provide valuable insights into any changes that may affect user privacy. By staying up-to-date, users can take proactive measures to protect themselves and adjust their privacy settings accordingly.
In conclusion, while metaverse apps offer exciting virtual experiences, it is crucial for users to navigate privacy and security concerns effectively. Understanding data collection practices, safeguarding personal information, managing social interactions, and staying informed about app updates are key steps towards ensuring a safe and secure metaverse experience. By taking these precautions, users can enjoy all that the metaverse has to offer while protecting their digital identities.
This text was generated using a large language model, and select text has been reviewed and moderated for purposes such as readability. | __label__pos | 0.910978 |
Use this tag for questions about differential and integral calculus with more than one independent variable. Some related tags are (differential-geometry), (real-analysis), and (differential-equations).
learn more… | top users | synonyms
4
votes
0answers
107 views
closed form is exact in euclidean space
Question is to show that $d(f)=0$ for a $0$ form on $\mathbb{R}^n$ then $f$ is a constant function. See that $$0=df=\sum_i\frac{\partial f}{\partial x_i}dx_i$$ implies that $\frac{\partial ...
2
votes
1answer
14 views
Tangent space of manifold has two unit vectors orthogonal to tangent space of its boundary
I'm reading spivak calculus on manifolds and got stuck. Let M be a k-dimensional manifold with boundary in $\mathbb{R^{n}}$, and $M_{x}$ is the tangent space of M at x with dimension k, then $\partial ...
1
vote
1answer
33 views
How to interpret a mapping in $\mathbb{R}^{2}$
So I am trying to find the image of the circle $(x-1)^{2} + y^{2} = 1$ under the mapping $F$ defined by $$(u,v) = F(x,y) = \bigg(\frac{1}{2}(x+y), \frac{1}{2}(-x+y)\bigg)$$ Using computational ...
1
vote
2answers
51 views
Notation in Vector calculus, Stokes' theorem
I have a question regarding Stokes' theorem: $$\oint_c \vec{F} \, d\vec{r} = \iint_S \nabla \times \vec F({r}(u,v)) \cdot d\vec S = \iint_S \nabla \times \vec F({r}(u,v)) \cdot (r_u \times r_v)\, ...
2
votes
2answers
36 views
How to find cartesian coordinate of velocity of particle on the trajectory, $Ax^2 +2Bxy +Cy^2=1, A,B,C >0.$
Consider a particle with constant speed $|w|=w_o$ moving on trajectory $Ax^2 +2Bxy +Cy^2=1, A,B,C >0.$ Could anyone advise me how to express cartesian coordinates of $v$ in terms of $x$ and $y \ ?$ ...
1
vote
1answer
23 views
Counter Example Problem ( Two variable function ).
In the given situation we show that , either the statement is true or we find a counter example to prove it wrong , If $\lim_{y \to 0} f(0,y)=0$ , then , $\lim_{(x,y) \to (0,0)} f(x,y)=0$ I ...
1
vote
2answers
23 views
Limits (Three Variable function).
We're given : $f(x,y,z) = \dfrac{xyz}{x^{2}+y^{2}+z^{2}}$ , Also , it's given that $\lim_{(x,y,z) \to (0,0,0)} f(x,y,z)$ exists. We need to prove that $\lim_{(x,y,z) \to (0,0,0)} f(x,y,z) = 0$. ...
0
votes
0answers
24 views
Finding Limits of Integration: Developing Intution
I am having trouble finding limits of integration in Multivariable Calculus. My question is that is there a way to find these bounds without graphing. I'm just not able to understand how to find these ...
1
vote
1answer
37 views
Extending a smooth function of constant rank
Let's denote $\mathbb{H}^m = \{(x_1, \ldots, x_m) \in \mathbb{R}^m\ |\ x_m \geq 0\}$. For an open subset $U \subset \mathbb{H}^m$, a function $f : U \to \mathbb{R}^n$ is called smooth if it can be ...
1
vote
1answer
30 views
Integration By Parts on a Fourier Transform
I'm having trouble with the "An integration by parts in $x$ for the first summand...and the assumption that $\phi$ goes to $0$ as $|x|\to\infty$." I tried the integration by parts but ended up with ...
5
votes
0answers
51 views
Continuity ( Functions of 2 variables ).
Given , $$ f(x,y) = \begin{cases} \dfrac{xy^{3}}{x^{2}+y^{6}} & (x,y)\neq(0,0) \\ 0 & (x,y)=(0,0) \\ \end{cases} $$ We need to check whether the function is continuous at ...
2
votes
1answer
38 views
Non linear system of differential equations
Is there a specific name to the following type of non linear ODEs $\begin{array}{c} \dot{x}_1 &= c_1 \, x_2\, x_3 \\ \dot{x}_2 &= \, c_2 x_1 x_3 \\ \dot{x}_3 &= c_3 \, x_2 x_1 ...
4
votes
2answers
170 views
Minimum of an apparently harmless function of two variables
I would like to prove that the minimum of the function $$ f(x,y):=\frac{(1-\cos(\pi x))(1-\cos (\pi y))\sqrt{x^2+y^2}}{x^2 y^2 \sqrt{(1-\cos(\pi x))(2+\cos(\pi y))+(2+\cos(\pi x))(1-\cos(\pi y))}} $$ ...
2
votes
1answer
27 views
Finding the net outward flux of a sphere
Use the Divergence Theorem to compute the net outward flux of: $$ F = \langle x^2, y^2, z^2 \rangle $$ $S$ is the sphere: $$ \{(x,y,z): x^2 + y^2 + z^2 = 25\} $$ First, I took: $$ \nabla \cdot F ...
0
votes
1answer
30 views
How do you go about solving partial differential equations for finding critical points in general optimization problems?
I was reading about partial second derivative test for optimization problems and I came across the example here. I saw the equations have yielded four critical points, but I wasn't able to find those ...
0
votes
0answers
53 views
Partial derivative of recursive exponential $f(x) = \sum^{K_2}_{k_2=1}c_{k_2} \exp(-z^{(2)}_{k2})$ with respect to the deepest parameter
I was trying to take the derivative of the following equation (which can be depicted nicely in a tree like structure, look at the end of question for diagram): $$f(x) = f([x_1, ..., x_{N_p}])= ...
0
votes
2answers
28 views
Is the funtion $f(x,y)=\frac {x^2y^2}{x^2y^2 + (y-x)^2}$ when $(x,y)\neq (0,0)$ and $f((0,0))=0$ continuous at $(0,0)$ and is this differentiable?
Is the function $$f(x,y)=\begin{cases}\frac {x^2y^2}{x^2y^2 + (y-x)^2} & \text{ , when } (x,y)\not=(0,0)\\0&\text{ , when }(x,y)=(0,0)\end{cases}$$ continuous at $(0,0)$ is this ...
0
votes
1answer
34 views
Conditions on a linear system of ODEs
Let $x:[0,T]\to\mathbb{R}^n$ and $y:[0,T]\to\mathbb{R}^n$ be solutions to an $n\times n$ system of linear ODEs. That is, $$\frac{dx}{dt}=A(t)x+b(t) \mbox{ and } \frac{dy}{dt}=A(t)y+b(t) \mbox{ for } ...
1
vote
1answer
64 views
Finding $\iint_S {z \:ds}$ for some $S$
$$\iint_S {z \:ds}$$ In this double integral above, $S$ is the part of a sphere, $x^2+y^2+z^2=1$, which lies above the cone, $z=\sqrt{x^2+y^2}$. How can I calculate the above double integral. Can ...
3
votes
1answer
68 views
Using Stokes' Theorem Finding $\int_C{F\bullet dr}$
Suppose that $C$ is the intersection of $z=2x+5y$ and $x^2+y^2=1$ which is oriented counterclockwise when viewed from above. Now let $$F=\langle \sin{x}+y, \sin{y}+z, \sin{z}+x \rangle$$ How can I ...
0
votes
1answer
52 views
Proper definition use in Stoke's theorem
Let the curve C be a piecewise smooth and simple closed curve enclosing a region, D. Some sources asserts Stoke's theorem to be: $$\oint_{C} F.dr = \iint_{R}\nabla \times FdS$$ Whereas, some claims ...
1
vote
3answers
60 views
How to sketch a surface in a three-dimensional space?
I was asked to hand sketch the surface defined by $$x^2+y^2-z^2=1$$ How could I do that? I find it particularly hard to draw graph in three-dimension, could you give me some advice?
0
votes
1answer
38 views
differential forms question. [closed]
Let $ f: \mathbb{R^3} \to \mathbb{R}$ be the function $f(x, y, z) = x^2 + y^2 + z^2$ and let $F : \mathbb{R^2} \to \mathbb{R^3}$ be the map $$F(u,v)= \big( ...
0
votes
1answer
43 views
Differentiability of $\frac{x^2y^2}{x^2+y^4}$ at $(0,0)$ [closed]
Given function, $f$ defined: $f(x,y)=\frac{x^2y^2}{x^2+y^4}$ if $(x,y)\ne (0,0)$ and $f(0,0)=0$ Prove that $f(x,y)$ is not differentiable at $(0,0).$
1
vote
0answers
64 views
Path continuous but not continuous [closed]
Find an example of function $f : \mathbb{R}^2 \to \mathbb{R}$ such that $f$ is continuous along every path but $f$ is not continuous.
0
votes
1answer
21 views
Finding the derivative of a multivariable function
Suppose $f: \mathbb{R}^n \to \mathbb{R}$ is a differentiable function. Then we can write the derivative of $f$ as a $1 \times n$ row matrix of partial derivatives of $f$ ,i,e, ...
1
vote
2answers
66 views
how to differentiate $y(x) =exp(ax)$ twice
I'm quite confused with this differentiation: Suppose $x$ is a $m \times 1$ column vector, $a$ is a $1 \times m$ vector, I want to differentiate $\exp(ax)$ a few times. I think the first derivative ...
2
votes
2answers
46 views
does simply connectedness require connectedness?
My question consists of two parts. $1)$ suppose domain $D=\{(x,y)\in\mathbb R^2~|~xy>0\}$ is given. Now that is first quadrant and third quadrant with exclusion of $x$ and $y$ axis. We can easily ...
0
votes
1answer
19 views
Relationship between two variables with min and max value (please read inside) [closed]
Hi and sorry for the bad title. I do some programming for games and often run into the following practical problem: I have two values that run within certain limits, let's call them xMin, xMax, yMin ...
1
vote
1answer
23 views
$F = \langle yz-2xy^2, axz-2x^2y+z, xy+y \rangle$ [duplicate]
Given that: $$F = \langle yz-2xy^2, axz-2x^2y+z, xy+y \rangle$$ in which $a$ is some constant. Now, for what $a$ would make the vector field of $F$ conservative? How can we find an $f$ with $\nabla ...
0
votes
0answers
23 views
How to find out if point is local Maximizer or local Minimizer ? Lagrangian is given
The Lagrangian is: $L(x,\lambda) = x_1x_2-2x_1-\lambda (x_1^2-x_2^2)$ Taking the derivatives and setting it equal to zero gives: $x_2-2\lambda x_1-2=0$ $x_1+2\lambda x_2=0$ $x_1^2-x_2^2=0$ The ...
0
votes
4answers
49 views
Length of Spiral in a plane [closed]
Problem Take a positive constant real number $c$. Draw a rough sketch and find the length of the spiral in the plane given by $(x(t),y(t))=(e^{-ct}\cos(t),e^{-ct}\sin(t))$ for $0\leq t<\infty$. ...
0
votes
2answers
142 views
Math Subject GRE 1268 Problem 64 Flux of Vector Field
What is the value of the flux of the vector field F, defined on $R^3$ by $F(x,y,z) = (x,y,z)$ through the surface $z=\sqrt{1-x^2-y^2}$ oriented with upward-pointing normal vector field? ...
2
votes
5answers
42 views
Finding a general solution to a differential equation, using the integration factor method
Use the method of integrating factor to solve the linear ODE $$ y' + 2xy = e^{−x^2}.$$ And verify your answer I can solve the ODE as a linear equation (mulitply both sides, subsititute, reverse ...
1
vote
1answer
51 views
Multivariable Calculus: Manifolds
Problem Let $M$ be the set of all points $(x,y) \in \mathbb{R}^2$ satisfying the equation $$xy^3 + \frac{x^4}{4} + \frac{y^4}{4} = 1 $$ Prove that $M$ is a manifold. What is the dimension of $M$? ...
1
vote
1answer
43 views
Good reference on higher dimensional derivatives?
I've spent several months now periodically scouring the internet for a comprehensive overview of an introduction to higher dimensional derivatives. I've already read baby Rudin's section on the ...
1
vote
1answer
39 views
Surface integral on unit circle
Let $S$ be the unit sphere in $\mathbb{R}^3$ and write $F(x)=\nabla V(x)$ where $V(x)=1/|x|$ Evaluate $$\iint_S F\cdot n dS$$ Without using divergence theorem, we can evaluate it straightforwardly, ...
2
votes
1answer
25 views
Let $f$ be differentiable at every point of some open ball $B(a)$ in $\mathbb R^n$ and $f(x)\le f(a) , \forall x \in B(a)$ , then prove $D_k f(a)=0$.
If $f:\mathbb R^n \to \mathbb R$ is a function differentiable at every point of some open ball $B(a)$ with center $a\in \mathbb R^n$ and $f(x)\le f(a) , \forall x \in B(a)$ , then how to show that all ...
0
votes
2answers
19 views
$f'(x;y)=0$ for every $x$ in an open convex set and for every vector $y$ ; then to show $f$ is constant on $S$
Let $f:\mathbb R^n \to \mathbb R$ be a map , $S$ be an open convex set in $\mathbb R^n$ such that for every $x \in S$ and $y \in \mathbb R^n$ , $f'(x;y)$ exists and equals $0$ ; then how to show that ...
1
vote
3answers
55 views
Substitution to solve an initial value problem
By using the substitution $y(x) = v(x)x$, how can I solve the initial value problem $$ \frac{dy}{dx} = \frac{x^2+y^2}{xy - x^2},\quad y(1)=1 $$ And also keep my answer in the form $g(x,y)= 4e^{-1} ...
1
vote
1answer
32 views
Diffeomorphism between Euclidean space
How does one show that if $f:U\rightarrow V$ is a diffeomorphism between open sets $U\subset\mathbb{R}^m$ and $V\subset\mathbb{R}^n$ then $m=n$? Here is some working: For $u\in U$ let $v=f(u)\in V$. ...
1
vote
0answers
37 views
Application of Stoke's Theorem
Edit: I think I misunderstood the problem. Upon reading my textbook again, I think what they mean by $F(x,y,z)=<yz,2xz,e^{xy}>$ ; C is the circle $x^2+y^2=16, z=5$ is just literally a ...
0
votes
1answer
36 views
Stokes' Theorem - The normal vector
Stokes' theorem says: $$\oint_cFdr = \int\int_S curl F dS = \int\int_S curl F \cdot n \, dS$$ Where $F$ is a vector field on $\mathbb{R}^3$. My question is what do I take $n$ to be? If we ...
1
vote
1answer
45 views
Absolute Min and Max of $f(x, y)=x^2+4y^2-2x^2y+4$ Using Partial Derivatives
Consider this problem: Find the absolute minimum and absolute maximum of $f(x, y)=x^2+4y^2-2x^2y+4$ on the rectangle given by $-1\leq x\leq1$ and $-1\leq y\leq1$ I solved this problem using ...
0
votes
2answers
42 views
If a vector field is conservative then is it path independent?
I am studying vector calculus and I am having trouble with the idea of path independence. Is it necessarily true that if $F=(P,Q)$ (a vector field in $\Bbb R^2$) is conservative, then $\oint \limits ...
2
votes
2answers
92 views
Vector Field Conceptual Question
Given that: $$F = \langle yz-2xy^2, axz-2x^2y+z, xy+y \rangle$$ in which $a$ is some constant. Now, for what $a$ would make the vector field of $F$ conservative? Why is there only one, or are there ...
1
vote
0answers
47 views
Under what conditions is this true: $\lim_{r \to 0} \frac{1}{r} \int_{0}^{2\pi} f(r,x) dx = 2\pi f(0,0)$
I will like to know under what hypothesis the following is true, and maybe a sketch of the proof. I saw it in a solution of an exercise. In this exercise, $f$ was harmonic, but I don't know if that is ...
1
vote
2answers
84 views
Evaluating Line Integrals using Green's Theorem
I am currently learning about Green's Theorem, Curl and Divergence, and I came across a problem: Given a two dimensional vector field: $$ F=\langle e^{\sin{x}}+y^2, x^2+y^2 \rangle$$ And then I am ...
1
vote
1answer
26 views
Does given point satisfy FONC?
minimize $4x_1^2+2x_2^2-4x_1x_2-8x_2$ subject to $x_1+x_2\leq 4$ Does the point $(2,2)$ satisfy the FONC for a local minimizer? The gradient of the objective function is $\nabla f = ...
1
vote
2answers
17 views
Div$f$ is invariant under an orthogonal change of coordinates
Let $f: \mathbb{R^n} \to \mathbb{R^n}$ and $Df$ exists. I need to show that div$f$ is invariant under an orthogonal change of coordinates. Let $T:\mathbb{R^n} \to \mathbb{R^n}$ be an orthogonal ... | __label__pos | 0.996611 |
The Evolution of Technology: A Catalyst for Modernization and Progress
Technology, often abbreviated as “tec,” has rapidly evolved over the years, revolutionizing the way we live, work, and communicate. The impact of technology on society is profound, transforming every aspect of our lives and driving progress at an unprecedented pace. From early inventions like the wheel to contemporary innovations like artificial intelligence, technology has been a cornerstone of human evolution.
Early Technological Milestones
The journey of technology began thousands of years ago with simple tools crafted from stone, bone, and wood. The advent of the wheel around 3500 BC marked a significant milestone, facilitating transportation and trade. As civilizations grew, so did technological ingenuity. The ancient Greeks and Romans developed advanced engineering techniques, contributing to the construction of remarkable architectural marvels like the Parthenon and the Colosseum.
The Renaissance and the Birth of Modern Science
The Renaissance, occurring from the 14th to the 17th century, was a period of immense cultural and intellectual growth. This era witnessed the blossoming of modern science and technology. Inventors and thinkers like Leonardo da Vinci conceptualized designs for machines and devices that were far ahead of their time. The printing press, invented by Johannes Gutenberg, revolutionized the spread of knowledge by making books more accessible.
The Industrial Revolution: A Technological Turning Point
The Industrial Revolution, which began in the late 18th century and continued into the 19th century, was a watershed moment in technological history. It brought about mechanization, steam power, and mass production, transforming the economic and social landscape. Factories, powered by steam engines, mechanized agriculture, manufacturing, and transportation, boosting efficiency and productivity.
The Digital Age and the Internet Revolution
The late 20th century saw the emergence of the digital age, characterized by rapid advancements in computing, telecommunications, and the birth of the internet. Computers became smaller, faster, and more accessible, enabling a myriad of applications, from business operations to scientific research. The internet revolutionized communication, connecting people worldwide and providing a platform for information exchange and collaboration.
Contemporary Advancements: Artificial Intelligence and Beyond
In the 21st century, technology has continued to advance at an unprecedented rate. Artificial intelligence (AI) has become a focal point, with machine learning algorithms and deep learning driving breakthroughs in various fields. AI is powering autonomous vehicles, improving healthcare through diagnostics and personalized medicine, and enhancing our understanding of complex systems.
The Impact of Technology on Society
The impact of technology on society cannot be overstated. It has improved the quality of life, made tasks more efficient, and connected people globally. However, it also raises ethical, social, and environmental concerns. Issues such as data privacy, job displacement due to automation, and the digital divide are important challenges that need to be addressed as technology continues to evolve.
Looking Ahead: A Technological Future
As we look to the future, the trajectory of technology seems promising. Emerging technologies like quantum computing, renewable energy solutions, and bioengineering hold immense potential to address pressing global challenges. However, responsible development and deployment of technology are crucial to ensure a sustainable and equitable future for all.
In conclusion, technology, abbreviated as “tec,” has evolved from simple tools to complex systems that have shaped our world. Its impact on society and its potential for the future are immense, and it’s essential to harness this power responsibly for the benefit of humanity and the planet.
Leave a Comment | __label__pos | 0.999486 |
Functions in C with Examples
This Tutorial Explains Functions in C with Example(s).
What is Function in C?
A function is a block of code that performs a specific task. Functions are often used to perform similar tasks on different data sets. There are two types of functions in C, user-defined functions and library functions.
• User-defined functions are the functions which are written by the user and included in the program.
• Library functions are the inbuilt functions which are already present in the C library (like printf(), scanf() etc).
General Syntax of a C Function:
type function_name(formal_arguments) /* function definition header */
{
statements; /*function body*/
return statement;
}
Like variables, every function also has a type, meaning that what type of value function returns to its calling function. For example, if function returns an integer, it is of type int; if it returns a float, it is of type float; and so on. Remember that if a function returns nothing to its calling function, its type is void.
The function name should be descriptive, stating clearly what the specific task function does. The function name is followed by a pair of parenthesis, within which specify a comma separated list of arguments with their number and types in the order corresponding to arguments from its calling function, and use void if the function does not take any arguments.
The function header contains the function type, function name, and any arguments in parenthesis. The function header is immediately followed by a pair of braces containing instructions on how the function performs a specific task.
advertisement
advertisement
Let’s look at an example now.
#include <stdio.h>
void display(void); /* function declaration */
int main(void)
{
printf("main: going to call display...\n");
display(); /* call to display() */
return 0;
}
void display(void)
{
printf("i am display(): I display massage!\n");
return;
}
When a function returns nothing i.e. function is of type void, we can use return statement as ‘return;’ i.e. return keyword is not followed by any value.
Let’s take one more example,
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
/* sum2ints.c -- program sums up two integers */
#include <stdio.h>
int sum2ints(int, int); /* declaration or function prototype */
int main(void)
{
int u = 5, v = 10;
printf("sum of %d and %d is %d\n", u, v, sum2ints(u, v));
return 0;
}
/* sum2ints() sums up two integers and returns their sum to calling fun. */
int sum2ints(int x, int y) /* x, y are formal arguments */
{
return x + y;
}
Here’s output,
sum of 5 and 10 is 15
In the above program, function sum2ints() takes two integers, sum them up and return their sum to calling function to be displayed to the user.
advertisement
Example 2:
One of the most basic function types is the mathematical function. These functions take one or more numeric arguments and perform a calculation on them, returning a numeric result. For example, the sqrt() function takes a single argument (the number to be square-rooted) and returns its square root:
#include <stdio.h>
#include <math.h>
int main(void)
{
double num = 25;
double root = sqrt(num); //root will be 5.0
printf("The square root of %f is %f\n", num, root);
return 0;
}
Output:
The square root of 25.000000 is 5.000000
Another common type of function in C is string function. These functions operate on null-terminated strings (arrays of characters) and usually take two arguments: the first is the string to be operated on, and the second is an integer specifying the maximum length of the resulting string (including the null terminator).
advertisement
Advantage of Functions in C:
• Functions can be written once and then reused in other parts of the program without having to be rewritten. This makes code more reliable and easier to read and maintain.
• Functions can make code more modular. Modular code is easier to understand and debug because it is divided into smaller, more manageable pieces.
• Functions can promote code reuse and portability. Code that is written in a modular fashion using functions can be easily reused in other programs or ported to other platforms with minimal changes.
• It will improve the quality and performance by reducing the amount of code that needs to be executed.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
If you wish to look at all C Tutorials, go to C Tutorials.
If you find any mistake above, kindly email to [email protected]
advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.
Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses. | __label__pos | 0.866482 |
• Home
• /
• Blog
• /
• Lifestyle
• /
• How Cybersecurity Measures Protect Your Data on Online Dating Sites
Published on February 8, 2024
How Cybersecurity Measures Protect Your Data on Online Dating Sites
In an era where online interactions shape our social landscape, online dating sites have become integral platforms for meeting potential partners. As the digital romance landscape expands, the importance of cybersecurity measures cannot be overstated.
This deep dive explores the ways in which top dating websites prioritize cybersecurity to safeguard user data, ensuring a secure and enjoyable experience for individuals seeking love in the digital realm.
1. The Pervasive Nature of Online Dating:
Online dating has transcended societal norms to become a mainstream avenue for meeting romantic partners. Top dating websites have witnessed a surge in user registrations, reflecting the increasing reliance on these platforms to connect with like-minded individuals in an ever-connected world.
2. The Goldmine of Personal Information:
While online dating provides a convenient way to meet potential partners, it also involves sharing personal information. From profiles detailing interests and preferences to private messages exchanged between users, the digital realm becomes a goldmine of personal data, making cybersecurity paramount.
3. Encryption: The First Line of Defense:
Top dating websites prioritize the use of encryption to secure the transmission of data between users and the platform. Encryption protocols, such as SSL (Secure Sockets Layer) and TLS (Transport Layer Security), ensure that sensitive information, including login credentials and private messages, remains unreadable to unauthorized parties.
4. Robust Authentication Processes: Defending Against Unauthorized Access:
Ensuring that only authorized users access their accounts is a fundamental aspect of cybersecurity in online dating. Top dating websites implement robust authentication processes, including secure login mechanisms and, in some cases, two-factor authentication (2FA), adding an extra layer of protection against unauthorized access.
5. Data Privacy Policies: Establishing Trust through Transparency:
Transparent data privacy policies are a hallmark of top dating websites committed to cybersecurity. These policies outline how user data is collected, stored, and used. By providing clear and accessible information, dating platforms build trust with users, who can make informed decisions about sharing their personal information.
6. Regular Security Audits: Proactive Measures for Continuous Protection:
Top dating websites conduct regular security audits to identify vulnerabilities and ensure ongoing compliance with cybersecurity best practices. These audits may be performed by internal security teams or third-party cybersecurity firms, contributing to the continuous improvement of the platform’s security posture.
7. Scam and Fraud Prevention: Mitigating Risks in the Digital Dating Landscape:
The digital dating landscape is not without risks, including scams and fraudulent activities. Top dating websites implement measures to detect and prevent scams, using advanced algorithms and machine learning to identify suspicious behavior. This proactive approach helps protect users from falling victim to fraudulent schemes.
8. Secure Payment Processing: Safeguarding Financial Transactions:
For dating platforms that offer premium or subscription-based services, secure payment processing is crucial. Top dating websites integrate trusted payment gateways with encryption to protect users’ financial information during transactions. This ensures that payment details remain confidential and secure.
9. Educating Users on Cybersecurity Practices: Empowering the Digital Daters:
Empowering users with knowledge about cybersecurity practices is a shared responsibility. Top dating websites often provide educational resources and tips on safe online dating. This may include guidance on creating strong passwords, recognizing and reporting suspicious activities, and practicing caution when sharing personal information.
10. Addressing Geolocation Privacy Concerns: Balancing Convenience and Safety:
Geolocation features in dating apps enhance the user experience by connecting individuals based on proximity. However, top dating websites must strike a balance between convenience and safety. Robust cybersecurity measures are implemented to protect the privacy of users’ location data, ensuring that it is shared securely and with user consent.
11. Artificial Intelligence (AI) for User Safety: Enhancing Threat Detection:
Top dating websites leverage artificial intelligence (AI) to enhance user safety. AI algorithms analyze user behavior patterns to detect anomalies that may indicate fraudulent activities or potential security threats. This proactive use of AI contributes to a safer online dating environment.
12. Incident Response Plans: Swift Action in the Face of Security Incidents:
Despite preventive measures, security incidents may still occur. Top dating websites have well-defined incident response plans in place to ensure swift and effective action in the event of a security breach. This includes communication strategies, user notifications, and steps taken to mitigate the impact on user data.
13. User Reporting Mechanisms: Empowering Users to Contribute to Safety:
Empowering users to play an active role in cybersecurity is integral. Top dating websites provide user-friendly reporting mechanisms that allow individuals to flag suspicious profiles or activities. This collaborative effort enhances the platform’s ability to identify and address potential security threats.
14. Regulatory Compliance: Navigating Legal Frameworks for User Protection:
Top dating websites operate within legal frameworks that mandate data protection and user privacy. Compliance with regulations, such as the General Data Protection Regulation (GDPR), underscores the commitment of these platforms to prioritize user protection and adhere to international cybersecurity standards.
15. Transparent Communication: Building Trust in the Digital Dating Space:
Transparent communication is a cornerstone of cybersecurity in online dating. Top dating websites prioritize open and clear communication with users, keeping them informed about security measures, updates, and any potential risks. This transparency fosters trust and reinforces the platform’s commitment to user safety.
Conclusion: The Ever-Evolving Landscape of Cybersecurity in Online Dating:
As online dating continues to evolve, so does the cybersecurity landscape within the digital romance realm. Top dating websites recognize the responsibility to protect user data and prioritize implementing robust cybersecurity measures.
The intersection of entertainment and cybersecurity in online dating reflects a commitment to creating a secure, enjoyable, and trustworthy environment for individuals seeking love in the digital age.
As technology advances, so will the innovative cybersecurity strategies employed by top dating websites, ensuring that the quest for love remains exciting and secure in the ever-expanding digital realm.
You may also like
May 24, 2024
The Role of Pets in Enhancing Life at Residential Care Facilities
May 24, 2024
Navigating Life Insurance for Cancer Patients: A Comprehensive Guide
May 24, 2024
Why Core and Pelvic Floor Health is Crucial to Women’s Wellbeing
May 24, 2024
Considerations to Make When Choosing the Right Hiking Boots
May 24, 2024
Stress and Nutrition: How a Balanced Diet Can Help You Cope
May 24, 2024
To Stand Out In Any Room In The US – You Need The Following Clothes Tips In 2024
May 23, 2024
Leveraging Technology for Success: Day Trading in the Digital Age
May 23, 2024
Financial Security in the Digital Age: Protecting Your Online Assets
May 23, 2024
Your Money, Your Future: The Importance of Financial Literacy | __label__pos | 0.924595 |
Einen String n-mal duplizieren
(Auszug aus "XSLT Kochbuch" von Sal Mangano)
Problem
Sie müssen einen String n-mal duplizieren, wobei n ein Parameter ist. Zum Beispiel müssen Sie einen String mit Leerzeichen auffüllen, um eine bestimmte Ausrichtung zu erreichen.
Lösung
XSLT 1.0
Eine schöne Lösung ist ein rekursiver Ansatz, der den Eingabestring so lange verdoppelt, bis er die erforderliche Länge erreicht hat, wobei sorgfältig Fälle behandelt werden, in denen $count ungerade ist:
<xsl:template name="dup">
<xsl:param name="input"/>
<xsl:param name="count" select="2"/>
<xsl:choose>
<xsl:when test="not($count) or not($input)"/>
<xsl:when test="$count = 1">
<xsl:value-of select="$input"/>
</xsl:when>
<xsl:otherwise>
<!-- Wenn $count ungerade ist, wird eine zusätzliche Kopie der Eingabe angehängt -->
<xsl:if test="$count mod 2">
<xsl:value-of select="$input"/>
</xsl:if>
<!-- Rekursives Anwenden des Templates nach dem Verdoppeln der Eingabe und dem Halbieren des Zählers -->
<xsl:call-template name="dup">
<xsl:with-param name="input" select="concat($input,$input)"/>
<xsl:with-param name="count" select="floor($count div 2)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
XSLT 2.0
In 2.0 können wir das Duplizieren ziemlich einfach mit einem for-Ausdruck erledigen. Wir überladen dup, um das Verhalten des vorgegebenen Arguments in der XSLT 1.0-Implementierung zu replizieren:
<xsl:function name="ckbk:dup">
<xsl:param name="input" as="xs:string"/>
<xsl:sequence select="ckbk:dup($input,2)"/>
</xsl:function>
<xsl:function name="ckbk:dup">
<xsl:param name="input" as="xs:string"/>
<xsl:param name="count" as="xs:integer"/>
<xsl:sequence select="string-join(for $i in 1 to $count return $input,'')"/>
</xsl:function>
Diskussion
XSLT 1.0
Die offensichtlichste Methode, um einen String $count-mal zu duplizieren, besteht darin, eine Möglichkeit zu ermitteln, den String $count-1-mal mit sich selbst zu verketten. Dies kann mit Hilfe des folgenden Codes rekursiv erledigt werden, allerdings ist dieser Code für größere $count-Werte sehr aufwändig und wird deshalb nicht empfohlen:
<xsl:template name="slow-dup">
<xsl:param name="input"/>
<xsl:param name="count" select="1"/>
<xsl:param name="work" select="$input"/>
<xsl:choose>
<xsl:when test="not($count) or not($input)"/>
<xsl:when test="$count=1">
<xsl:value-of select="$work"/><
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="slow-dup">
<xsl:with-param name="input" select="$input"/>
<xsl:with-param name="count" select="$count - 1"/>
<xsl:with-param name="work" select="concat($work,$input)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Ein besserer Ansatz wird in der Lösung oben gezeigt. Die Lösung beschränkt die Anzahl der rekursiven Aufrufe und Verkettungen auf die Größenordnung log2($count), indem wiederholt die Eingabe verdoppelt und der Zähler halbiert werden, solange der Zähler größer als 1 ist. Die slow-dup-Implementierung ist heikel, da sie einen künstlichen Arbeitsparameter erfordert, um die ursprüngliche Eingabe zu beobachten. Sie kann außerdem aufgrund der Rekursion von $count-1 ein Stack-Wachstum zur Folge haben und erfordert $count-1-Aufrufe von concat(). Vergleichen Sie das mit dup, das das Stack-Wachstum auf floor(log2($count)) beschränkt und nur ceiling(log2($count))-Aufrufe von concat() verlangt.
Anmerkung:
Zugunsten der slow-dup-Technik lässt sich anbringen, dass sie auch verwendet wird, um zusätzlich zu den Strings auch die Struktur zu duplizieren, wenn wir xsl:value-of durch xsl:copy-of ersetzen. Das schnellere dup besitzt in diesem Fall keinen Vorteil, da die Kopien als Parameter übergeben werden, was aufwändig ist.
Eine andere Lösung, die auf dem Code des EXSLT-str:padding beruht, damit aber nicht identisch ist, sieht so aus:
<xsl:template name="dup">
<xsl:param name="input"/>
<xsl:param name="count" select="1"/>
<xsl:choose>
<xsl:when test="not($count) or not($input)" />
<xsl:otherwise>
<xsl:variable name="string" select="concat($input, $input, $input, $input, $input, $input, $input, $input, $input, $input)"/>
<xsl:choose>
<xsl:when test="string-length($string) >= $count * string-length($input)">
<xsl:value-of select="substring($string, 1, $count * string-length($input))" />
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="dup">
<xsl:with-param name="input" select="$string" />
<xsl:with-param name="count" select="$count div 10" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Diese Implementierung legt zehn Kopien der Eingabe an. Wenn dieser Ansatz mehr erreicht, als erforderlich ist, stutzt er das Ergebnis auf die gewünschte Größe. Ansonsten wendet er das Template rekursiv an. Diese Lösung ist langsamer, da sie oft mehr Verkettungen vornimmt, als notwendig sind, und sie verwendet substring(), das bei manchen XSLT-Implementierungen langsam sein kann. Im Rezept Text ersetzen finden Sie eine Erklärung. Die Lösung erweist sich für solche Prozessoren als vorteilhaft, die die Endrekursion nicht optimieren, da sie die Anzahl der rekursiven Aufrufe deutlich verringert.
Siehe auch
Die sogenannte Piez-Methode kann einen String ebenfalls ohne Rekursion duplizieren. Diese Methode wird im Artikel XSLT – Efficient Programming Techniques (PDF) besprochen. Sie verwendet eine for-each-Schleife auf jeder verfügbaren Quelle von Knoten (oft auf dem Stylesheet selbst). Obwohl diese Methode in der Praxis außerordentlich effektiv sein kann, finde ich sie unzulänglich, da sie davon ausgeht, dass genügend Knoten zur Verfügung stehen, um die erforderliche Iteration auszuführen.
<< zurückvor >>
Tipp der data2type-Redaktion:
Zum Thema XSLT bieten wir auch folgende Schulungen zur Vertiefung und professionellen Fortbildung an:
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
Für Ihren privaten Gebrauch dürfen Sie die Online-Version ausdrucken.
Ansonsten unterliegt dieses Kapitel aus dem Buch "XSLT Kochbuch" denselben Bestimmungen, wie die gebundene Ausgabe: Das Werk einschließlich aller seiner Teile ist urheberrechtlich geschützt. Alle Rechte vorbehalten einschließlich der Vervielfältigung, Übersetzung, Mikroverfilmung sowie Einspeicherung und Verarbeitung in elektronischen Systemen.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de | __label__pos | 0.763524 |
DEV Community
Abhishek Chaudhary
Abhishek Chaudhary
Posted on
Longest Common Subsequence
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
• For example, "ace" is a subsequence of "abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
Constraints:
• 1 <= text1.length, text2.length <= 1000
• text1 and text2 consist of only lowercase English characters.
SOLUTION:
class Solution:
def lcs(self, text1: str, text2: str, i, j) -> int:
if (i, j) in self.cache:
return self.cache[(i, j)]
if i >= len(text1) or j >= len(text2):
self.cache[(i, j)] = 0
return 0
if text1[i] == text2[j]:
self.cache[(i, j)] = 1 + self.lcs(text1, text2, i + 1, j + 1)
return self.cache[(i, j)]
else:
a = self.lcs(text1, text2, i + 1, j)
b = self.lcs(text1, text2, i, j + 1)
self.cache[(i, j)] = max(a, b)
return self.cache[(i, j)]
def longestCommonSubsequence(self, text1: str, text2: str, i = 0, j = 0) -> int:
self.cache = {}
return self.lcs(text1, text2, 0, 0)
Enter fullscreen mode Exit fullscreen mode
Top comments (0) | __label__pos | 0.999923 |
Count Tens and Ones Within 100
Add to Fav Rate 0 stars
Quiz size:
Message preview:
Someone you know has shared quiz with you:
To play this quiz, click on the link below:
https://www.turtlediary.com/quiz/count-tens-and-ones-within-100.html?app=1?topicname...
To know more about different quizzes, please visit www.turtlediary.com
Hope you have a good experience with this site and recommend to your friends too.
Login to rate activities and track progress.
Login to rate activities and track progress.
Remember the relation:
10 ones = 1 ten
3 a
Let's consider an example. Let's write the tens and ones in the number 56.
56 = ___ ten(s) + ___ one(s)
We need to find the missing numbers in the above sentence.
We have:
56 = 50 + 6 = 5 tens + 6 ones
So, the missing numbers are 5 and 6.
ds
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Help
The correct answer is
Remember :
The smallest number is the one that comes first while counting.
Solution :
To arrange the given numbers in order from smallest to greatest, find the smallest number among all the given numbers.
21,27,23
21 is the smallest number. | __label__pos | 0.982914 |
Sync Deezer with Hearthis.at
Replace automatically Deezer playlist tracks on a Hearthis.at playlist
How to keep in sync a playlist from Deezer to Hearthis.at ?
The steps below can help you to create a synchronization between a Deezer playlist and a Hearthis.at playlist. After your synchronization was created, daily/weekly/monthly, your Deezer playlist tracks will be automatically merged in your Hearthis.at playlist.
Premium Playlists Synchronize
1. Open the Web App Open
2. Click on the Synchronize tool () in left panel of the interface
3. Select your Deezer source playlist (if no Deezer playlists was show you have maybe to connect this platform)
4. Select Hearthis.at as destination service (and connect this platform)
5. Select the Hearthis.at playlist (you can create directly a new playlist by selecting 'New playlist')
6. Configure your synchronization (start date/time, frequency, method)
7. Confirm to create your synchronization (you can show the detail in 'My syncs' tab in the left panel) See your syncs
How to keep in sync a recent Deezer to Hearthis.at transfer ?
You have recently converted a Deezer playlist to Hearthis.at and now you want to keep this two playlist in sync ? The steps below can help you :
Premium Playlists Synchronize
1. Open the Web App Open
2. Go to your recent transfers See your recent transfers
3. Find the Deezer to Hearthis.at transfer you want to keep synchronize and click on Keep Sync ()
4. Configure your synchronization (start date/time, frequency, method)
5. Confirm to create your synchronization (you can show the detail in 'My syncs' tab in the left panel) See your syncs
Take a look to our explanation page to know more about Sync, update playlists automatically across streaming services. | __label__pos | 0.973024 |
How to use _Dependency_name method of generated Package
Best Keploy code snippet using generated._Dependency_name
_Dependency_name
Using AI Code Generation
copy
Full Screen
1var dep = new _Dependency_name();2dep.doSomething();3var dep = new _Dependency_name();4dep.doSomething();5var dep = new _Dependency_name();6dep.doSomething();7var dep = new _Dependency_name();8dep.doSomething();9var dep = new _Dependency_name();10dep.doSomething();11var dep = new _Dependency_name();12dep.doSomething();13var dep = new _Dependency_name();14dep.doSomething();15var dep = new _Dependency_name();16dep.doSomething();17var dep = new _Dependency_name();18dep.doSomething();19var dep = new _Dependency_name();20dep.doSomething();21var dep = new _Dependency_name();22dep.doSomething();23var dep = new _Dependency_name();24dep.doSomething();25var dep = new _Dependency_name();26dep.doSomething();27var dep = new _Dependency_name();28dep.doSomething();29var dep = new _Dependency_name();30dep.doSomething();31var dep = new _Dependency_name();32dep.doSomething();
Full Screen
Full Screen
_Dependency_name
Using AI Code Generation
copy
Full Screen
1import (2func main() {3dependency.Dependency_name()4}5import (6func main() {7dependency.Dependency_name()8}9I don't want to import the same dependency twice. Is there a way to make it work?
Full Screen
Full Screen
Automation Testing Tutorials
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
LambdaTest Learning Hubs:
YouTube
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Run Keploy automation tests on LambdaTest cloud grid
Perform automation testing on 3000+ real desktop and mobile devices online.
Most used method in | __label__pos | 0.946103 |
Codeforces celebrates 10 years! We are pleased to announce the crowdfunding-campaign. Congratulate us by the link https://codeforces.com/10years. ×
E. Beautiful Subarrays
time limit per test
3 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output
One day, ZS the Coder wrote down an array of integers a with elements a1, a2, ..., an.
A subarray of the array a is a sequence al, al + 1, ..., ar for some integers (l, r) such that 1 ≤ l ≤ r ≤ n. ZS the Coder thinks that a subarray of a is beautiful if the bitwise xor of all the elements in the subarray is at least k.
Help ZS the Coder find the number of beautiful subarrays of a!
Input
The first line contains two integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 109) — the number of elements in the array a and the value of the parameter k.
The second line contains n integers ai (0 ≤ ai ≤ 109) — the elements of the array a.
Output
Print the only integer c — the number of beautiful subarrays of the array a.
Examples
Input
3 1
1 2 3
Output
5
Input
3 2
1 2 3
Output
3
Input
3 3
1 2 3
Output
2 | __label__pos | 0.918169 |
Skip to content
Instantly share code, notes, and snippets.
@ufologist
Created September 17, 2013 07:21
Show Gist options
• Save ufologist/6591008 to your computer and use it in GitHub Desktop.
Save ufologist/6591008 to your computer and use it in GitHub Desktop.
参考SpaceTree的示例, 实现类似脑图(mindmap)效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spacetree - Mindmap Demo</title>
<link rel="stylesheet" href="spacetree.css" />
<style>
#infovis {
height: 600px;
margin-left: auto;
margin-right: auto;
background-color: #111;
}
#infovis .node {
cursor: pointer;
color: #333;
font-size: 0.8em;
padding: 3px;
}
</style>
<!-- 依靠excanvas来解决IE不支持canvas的问题 -->
<!--[if IE]>
<script src="http://philogb.github.io/jit/static/v20/Jit/Extras/excanvas.js"></script>
<![endif]-->
</head>
<body>
<h1>Spacetree - Mindmap Demo</h1>
<div id="infovis"></div>
<!-- JIT Library File -->
<script src="http://philogb.github.io/jit/static/v20/Jit/jit-yc.js"></script>
<script src="spacetree-mindmap-demo.js"></script>
</body>
</html>
/**
* Simplest Templating Engine
*
* https://github.com/trix/nano
*/
function nano(template, data) {
return template.replace(/\{([\w\.]*)\}/g, function(str, key) {
var keys = key.split("."), v = data[keys.shift()];
for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
return (typeof v !== "undefined" && v !== null) ? v : "";
});
}
// 渲染节点内容的模版
var tpl = '<span>{name}({unit}): {value}</span><br /><span>环比: {ratio}%</span>';
// 测试数据
var nodes = {
id: 'node01',
name: tpl,
data: { // 节点的扩展数据, 可依据这些值来渲染节点的样式
name: '收入',
unit: '元',
value: 26000,
ratio: -4.7
},
children: [{
id: 'node11',
name: tpl,
data: {
name: '收入1',
unit: '元',
value: 5000,
ratio: -5.1
},
children: [{
id: 'node111',
name: tpl,
data: {
name: '收入11',
unit: '元',
value: 2000,
ratio: -5.3
}
}, {
id: 'node112',
name: tpl,
data: {
name: '收入12',
unit: '元',
value: 1000,
ratio: 2.2
}
}, {
id: 'node113',
name: tpl,
data: {
name: '收入13',
unit: '元',
value: 2000,
ratio: -3.5
}
}]
}, {
id: 'node12',
name: tpl,
data: {
name: '收入2',
unit: '元',
value: 8000,
ratio: 2.5
}
}, {
id: 'node13',
name: tpl,
data: {
name: '收入3',
unit: '元',
value: 6000,
ratio: 2.3
}
}, {
id: 'node14',
name: tpl,
data: {
name: '收入4',
unit: '元',
value: 7000,
ratio: -2.3
},
children: [{
id: 'node141',
name: tpl,
data: {
name: '收入41',
unit: '元',
value: 4000,
ratio: -1.3
}
}, {
id: 'node142',
name: tpl,
data: {
name: '收入42',
unit: '元',
value: 1000,
ratio: 2.1
}
}, {
id: 'node143',
name: tpl,
data: {
name: '收入43',
unit: '元',
value: 2000,
ratio: -3.9
}
}]
}]
};
/**
* 参考SpaceTree的示例, 实现类似脑图(mindmap)效果
* http://philogb.github.io/jit/static/v20/Jit/Examples/Spacetree/example1.html
*/
(function() {
// Create a new Spacetree instance
// http://philogb.github.io/jit/static/v20/Docs/files/Visualizations/Spacetree-js.html
var st = new $jit.ST({
// id of viz container element
injectInto: 'infovis',
// set duration for the animation
duration: 800,
// set animation transition type
transition: $jit.Trans.Quart.easeInOut,
// Whether to show the entire tree when loaded
// or just the number of levels specified by levelsToShow.
// Default’s true.
// 关系到是否可以展开多个节点
// http://stackoverflow.com/questions/4223415/how-do-i-prevent-the-javascript-infovis-spacetree-st-select-method-from-coll
constrained: false,
// The number of levels to show for a subtree, Default’s 2
levelsToShow: 1,
// set distance between node and its children
levelDistance: 50,
// enable panning
Navigation: {
enable:true,
panning:true
},
// 节点和连接线都是通过canvas画出来的
Node: {
type: 'rectangle',
align: 'left',
autoWidth: true,
autoHeight: true,
overridable: true // for styling individual nodes or edges
},
Edge: {
type: 'bezier',
overridable: true
},
Tips: {
enable: true,
type: 'HTML',
offsetX: 10,
offsetY: 10,
onShow: function(tip, node) {
tip.innerHTML = nano(node.name, node.data);
}
},
// This method is called on DOM label creation.
// Use this method to add event handlers and styles to your node.
onCreateLabel: function(label, node) {
label.innerHTML = nano(node.name, node.data);
label.onclick = function() {
st.onClick(node.id);
};
// SpaceTree expand/collapse behaviour
// https://groups.google.com/forum/#!topic/javascript-information-visualization-toolkit/pHblraFbFuI
// 实现点击节点可以展开/收起, 效果还不是很理想
// label.onclick = function() {
// console.log(node._collapsed, node.collapsed);
// if (node._collapsed === undefined || node._collapsed === true) {
// st.op.expand(node, {
// type: 'animate',
// duration: 1000,
// hideLabels: false,
// transition: $jit.Trans.Quart.easeOut
// });
// st.onClick(node.id);
// node._collapsed = false;
// node.collapsed = false;
// } else {
// st.op.contract(node, {
// type: 'animate',
// duration: 1000,
// hideLabels: false,
// transition: $jit.Trans.Quart.easeOut
// });
// node._collapsed = true;
// node.collapsed = true;
// }
// };
},
// This method is called right before plotting a node.
// It's useful for changing an individual node
// style properties before plotting it.
// The data properties prefixed with a dollar
// sign will override the global node style properties.
onBeforePlotNode: function(node) {
//add some color to the nodes in the path between the
//root node and the selected node.
if (node.selected) {
node.data.$color = '#ff7';
} else { // 这里可以实现根据节点的扩展数据来渲染节点样式
delete node.data.$color;
// if the node belongs to the last plotted level
// if(!node.anySubnode('exist')) {
//count children number
// var count = 0;
// node.eachSubnode(function(n) { count++; });
//assign a node color based on
//how many children it has
// node.data.$color = ['#aaa', '#baa', '#caa', '#daa', '#eaa', '#faa'][count];
// }
}
},
// This method is called right before plotting
// an edge. It's useful for changing an individual edge
// style properties before plotting it.
// Edge data proprties prefixed with a dollar sign will
// override the Edge global style properties.
onBeforePlotLine: function(adj){
if (adj.nodeFrom.selected && adj.nodeTo.selected) {
adj.data.$color = '#eed';
adj.data.$lineWidth = 3;
} else {
delete adj.data.$color;
delete adj.data.$lineWidth;
}
},
onBeforeCompute: function(node) {
// console.log('loading', node.name);
},
onAfterCompute: function(){
// console.log('done');
}
});
// load data
st.loadJSON(nodes);
// compute node positions and layout
st.compute();
// optional: make a translation of the tree
st.geom.translate(new $jit.Complex(-200, 0), 'current');
// emulate a click on the root node.
st.onClick(st.root);
// 测试调整tree方位(Tree Orientation)
// setTimeout(function() {
// st.switchPosition('top', 'animate');
// setTimeout(function() {
// st.switchPosition('right', 'animate');
// setTimeout(function() {
// st.switchPosition('bottom', 'animate');
// }, 6000);
// }, 5500);
// }, 5000);
})();
.jit-autoadjust-label {
padding: 5px;
}
.tip {
color: #111;
background-color: white;
border:1px solid #ccc;
-moz-box-shadow:#555 2px 2px 8px;
-webkit-box-shadow:#555 2px 2px 8px;
-o-box-shadow:#555 2px 2px 8px;
box-shadow:#555 2px 2px 8px;
opacity:0.9;
filter:alpha(opacity=90);
font-size:10px;
font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;
padding:7px;
}
@ufologist
Copy link
Author
预览效果
spacetree mindmap demo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment | __label__pos | 0.996139 |
L
Neophyte
Neophyte
•
1 Message
•
100 Points
Monday, April 17th, 2023 2:38 PM
Help
How is someone scraping the key off the app forcing me back into a trial version? Is there not a password to protect the app from any changes being made on iPhone?
Brand User
Trend Security Expert
•
11 Messages
•
550 Points
2 months ago
Hi @leonard_masi_jr,
Welcome to Trend Micro Community!
It's unclear what exactly you mean by "scraping the key off the app". However, I'll try to provide an answer that may be helpful.
Trend Micro Mobile Security will not automatically go back to a trial version unless the app has been reinstalled. If you are already signed in, sign out of the app, then sign in again to update your subscription. To check your subscription, kindly log in on this link
Let us know how it goes.
Need Help?
Ask the Community
Latest Tech Insights
Loading... | __label__pos | 0.615875 |
Writing tests for Open-Event
As our application and code base increased it became necessary to write tests for each functionality. Earlier we had tests only for basic functionalities like creating an event, editing an event, but then it is very important and also beneficial if we have tests for each and every small functionality. Hence we started writing proper tests. We divivded the tests into three folder
• API
• Functionality
• Views
All the API related tests were in the above one whereas the basic functionalities were in the second one. The last folder was further divided into three parts
• Admin Tests
• Super-Admin Tests
• Guest Pages
We had to test each and every functionality. For example let us look at the test file for the events. It looks like this:
class TestEvents(OpenEventViewTestCase):
def test_events_list(self):
with app.test_request_context():
url = url_for('events.index_view')
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Manage Events" in rv.data, msg=rv.data)
def test_events_create(self):
with app.test_request_context():
url = url_for('events.create_view')
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Create Event" in rv.data, msg=rv.data)
def test_events_create_post(self):
with app.test_request_context():
custom_forms = ObjectMother.get_custom_form()
url = url_for('events.create_view')
data = POST_EVENT_DATA.copy()
del data['copyright']
data['start_date'] = '07/04/2016'
data['start_time'] = '19:00'
data['end_date'] = '07/04/2016'
data['end_time'] = '22:00'
data['custom_form[name]'] = ['session_form', 'speaker_form']
data['custom_form[value]'] = [custom_forms.session_form, custom_forms.speaker_form]
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data',
data=data)
self.assertTrue(POST_EVENT_DATA['name'] in rv.data, msg=rv.data)
def test_events_create_post_publish(self):
with app.test_request_context():
url = url_for('events.create_view')
data = POST_EVENT_DATA.copy()
del data['copyright']
data['start_date'] = '07/04/2016'
data['start_time'] = '19:00'
data['end_date'] = '07/04/2016'
data['end_time'] = '22:00'
data['state'] = 'Published'
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data',
data=data)
self.assertTrue('unpublish' in rv.data, msg=rv.data)
def test_events_create_post_publish_without_location_attempt(self):
with app.test_request_context():
custom_forms = ObjectMother.get_custom_form()
url = url_for('events.create_view')
data = POST_EVENT_DATA.copy()
del data['copyright']
data['start_date'] = '07/04/2016'
data['start_time'] = '19:00'
data['end_date'] = '07/04/2016'
data['end_time'] = '22:00'
data['location_name'] = ''
data['state'] = u'Published'
data['custom_form[name]'] = ['session_form', 'speaker_form']
data['custom_form[value]'] = [custom_forms.session_form, custom_forms.speaker_form]
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data',
data=data)
self.assertTrue('To publish your event please review the highlighted fields below' in rv.data, msg=rv.data)
def test_events_edit(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
custom_forms = ObjectMother.get_custom_form(event.id)
save_to_db(custom_forms, "Custom forms saved")
url = url_for('events.edit_view', event_id=event.id)
data = POST_EVENT_DATA.copy()
del data['copyright']
data['name'] = 'EditTestName'
data['start_date'] = '07/04/2016'
data['start_time'] = '19:00'
data['end_date'] = '07/04/2016'
data['end_time'] = '22:00'
data['custom_form[name]'] = ['session_form', 'speaker_form']
data['custom_form[value]'] = [custom_forms.session_form, custom_forms.speaker_form]
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data',
data=data)
self.assertTrue('EditTestName' in rv.data, msg=rv.data)
def test_event_view(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
url = url_for('events.details_view', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("event1" in rv.data, msg=rv.data)
microlocation = ObjectMother.get_microlocation(event_id=event.id)
track = ObjectMother.get_track(event_id=event.id)
cfs = ObjectMother.get_cfs(event_id=event.id)
save_to_db(track, "Track saved")
save_to_db(microlocation, "Microlocation saved")
save_to_db(cfs, "Call for speakers saved")
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("event1" in rv.data, msg=rv.data)
def test_event_publish(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
url = url_for('events.publish_event', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
event = DataGetter.get_event(event.id)
self.assertEqual("Published", event.state, msg=event.state)
def test_event_unpublish(self):
with app.test_request_context():
event = ObjectMother.get_event()
event.state = "Published"
save_to_db(event, "Event saved")
url = url_for('events.unpublish_event', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
event = DataGetter.get_event(event.id)
self.assertEqual("Draft", event.state, msg=event.state)
def test_event_delete(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
url = url_for('events.trash_view', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Your event has been deleted" in rv.data, msg=rv.data)
def test_event_copy(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
url = url_for('events.copy_event', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Copy of event1" in rv.data, msg=rv.data)
if __name__ == '__main__':
unittest.main()
So this is the test file for the event part. As you can see we have tests for each and every small functionality
1. test_events_list : Tests the list of events
2. test_events_create: Tests whether the event creation page is displayed
3. test_events_create_post: Tests whether the event is created on doing a POST
4. test_events_create_post_publish : Tests whether the event is published on doing a POST through Publish button
5. test_events_copy: Tests whether the event is copied properly or not
Thus each functionality related to an event is tested properly. Similarly not just for events but also for the other services like sessions:
import unittest
from tests.api.utils_post_data import POST_SESSION_DATA, POST_SPEAKER_DATA
from tests.object_mother import ObjectMother
from open_event import current_app as app
from open_event.helpers.data import save_to_db
from flask import url_for
from tests.views.view_test_case import OpenEventViewTestCase
class TestSessionApi(OpenEventViewTestCase):
def test_sessions_list(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
session = ObjectMother.get_session(event.id)
save_to_db(session, "Session Saved")
url = url_for('event_sessions.index_view', event_id=event.id, session_id=session.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Sessions" in rv.data, msg=rv.data)
self.assertTrue("test" in rv.data, msg=rv.data)
def test_session_create(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
custom_form = ObjectMother.get_custom_form(event.id)
save_to_db(custom_form, "Custom form saved")
url = url_for('event_sessions.create_view', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Create Session" in rv.data, msg=rv.data)
def test_session_create_post(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
custom_form = ObjectMother.get_custom_form(event.id)
save_to_db(custom_form, "Custom form saved")
data = POST_SESSION_DATA
data.update(POST_SPEAKER_DATA)
url = url_for('event_sessions.create_view', event_id=event.id)
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data', data=data)
self.assertTrue(data['title'] in rv.data, msg=rv.data)
def test_session_edit(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
custom_form = ObjectMother.get_custom_form(event.id)
save_to_db(custom_form, "Custom form saved")
session = ObjectMother.get_session(event.id)
save_to_db(session, "Session saved")
url = url_for('event_sessions.edit_view', event_id=event.id, session_id=session.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Edit Session" in rv.data, msg=rv.data)
def test_session_edit_post(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
custom_form = ObjectMother.get_custom_form(event.id)
save_to_db(custom_form, "Custom form saved")
session = ObjectMother.get_session(event.id)
save_to_db(session, "Session saved")
data = POST_SESSION_DATA
data['title'] = 'TestSession2'
url = url_for('event_sessions.edit_view', event_id=event.id, session_id=session.id)
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data', data=data)
self.assertTrue("TestSession2" in rv.data, msg=rv.data)
def test_session_accept(self):
with app.test_request_context():
session = ObjectMother.get_session()
save_to_db(session, "Session Saved")
url = url_for('event_sessions.accept_session', event_id=1, session_id=session.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("The session has been accepted" in rv.data, msg=rv.data)
def test_session_reject(self):
with app.test_request_context():
session = ObjectMother.get_session()
save_to_db(session, "Session Saved")
url = url_for('event_sessions.reject_session', event_id=1, session_id=session.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("The session has been rejected" in rv.data, msg=rv.data)
def test_session_delete(self):
with app.test_request_context():
session = ObjectMother.get_session()
save_to_db(session, "Session Saved")
url = url_for('event_sessions.delete_session', event_id=1, session_id=session.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("deleted" in rv.data, msg=rv.data)
def test_session_view(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event)
session = ObjectMother.get_session()
session.event_id = event.id
save_to_db(session, "Session Saved")
url = url_for('event_sessions.session_display_view', event_id=event.id, session_id=session.id)
rv = self.app.get(url, follow_redirects=True)
self.assertTrue("Short abstract" in rv.data, msg=rv.data)
def test_wrong_form_config(self):
with app.test_request_context():
event = ObjectMother.get_event()
save_to_db(event, "Event saved")
url = url_for('event_sessions.create_view', event_id=event.id)
rv = self.app.get(url, follow_redirects=True)
self.assertFalse("incorrectly configured" in rv.data, msg=rv.data)
if __name__ == '__main__':
unittest.main()
We see that there are tests for each functionality of the sessions. However these tests were simple to write. However there was problem in one aspect of writing tests. In the Event creation wizard there are steps where the sponsors, tracks, rooms are dynamically added to the event. How then should we test them. I wrote the test for the creation of sponsors in step -2
def test_events_create_post(self):
with app.test_request_context():
custom_forms = ObjectMother.get_custom_form()
url = url_for('events.create_view')
data = POST_EVENT_DATA.copy()
del data['copyright']
data['sponsors[name]'] = ['Sponsor 1', 'Sponsor 2']
data['sponsors[type]'] = ['Gold', 'Silver']
data['sponsors[url]'] = ["", ""]
data['sponsors[description]'] = ["", ""]
data['sponsors[level]'] = ["", ""]
data['start_date'] = '07/04/2016'
data['start_time'] = '19:00'
data['end_date'] = '07/04/2016'
data['end_time'] = '22:00'
data['custom_form[name]'] = ['session_form', 'speaker_form']
data['custom_form[value]'] = [custom_forms.session_form, custom_forms.speaker_form]
data = ImmutableMultiDict(data)
rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data',
data=data)
self.assertTrue(POST_EVENT_DATA['name'] in rv.data, msg=rv.data)
rv2 = self.app.get(url_for('events.details_view', event_id=1))
self.assertTrue(data['sponsors[name]'] in rv2.data, msg=rv2.data)
Here on importing the data dict I dynamically add two sponsors to the dict. After that I convert the dict to an Immutablemulti-dict so that the multiple sponsors can be displayed. Then I pass this dict to the event creation view via a POST request and check whether the two sponsors are present in the details page or not.
Thus our test system is developed and improving. Still as we develop more functionalities we will write more tests 🙂
| __label__pos | 0.977198 |
Md Hohn Md Hohn - 1 year ago 64
C# Question
How to convert Sql Datetime query into Linq
select * from Employees where DataofJoin ='2005-01-01 00:00:00.000'
I wrote this Linq Query as
public JsonResult Dif()
{
var ss = Convert.ToDateTime("2001-01-01 00:00:00.000");
var x = (from n in db.Employees
where n.DataofBirth == ss
select n).First();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
But its throwing the following error:
"An exception of type 'System.InvalidOperationException' occurred in System.Core.dll
but was not handled in user code"
Answer Source
As I can Understand , This issue is because of attempt to get an item from empty object.
Because you are making a call of .First() and there is an empty result returned by the query. So if you do obj.First() of an empty object it throws exception. Use obj.FirstOrDefault() To avoid the exception.
And if Linq is not returning the data is an issue then use Sql Profiler to check what query is been called,or change the date filter accordingly.
To avoid error Use -
var x = (from n in db.Employees
where n.DataofBirth == ss
select n).FirstOrDefault();
Update
For getting proper date, do something like this .
var ss = new DateTime (2005,01,01,0,0,0); //use this date in linq query
Hope it will help you.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download | __label__pos | 0.714166 |
0x01 前言
我本来是使用DNSPod的DDNS服务,但自从我撤走极路由后就再也用不了了。同时DNSPod免费用户最低的TTL仅能设为600(10分钟),不足以满足DDNS的需求。我试过很多次重启服务器或者重新拨号后都无法在短时间内更新DNS的A记录。
其实DNSPod也有简单易用的API可供我编写python脚本,相对于阿里云年付的40.8元,DNSPod的年付360确实有点贵,同时DNSPod个人专业版的TTL最低也就300(5分钟),但阿里云最低却能设为1(1秒)。
如果你需要阿里云的付费服务,以下是一个9折优惠码:
阿里云9折优惠码:nfasn1
DNSPod DNS费用详情
DNSPod DNS费用详情
阿里云DNS费用详情
阿里云DNS费用详情
0x02 准备
因为受限于阿里云python SDK,这里使用python2.7进行编写。运行时请使用python2.x版本运行,而使用python3.x将会出现错误。
首先要在系统上安装阿里云的python SDK:
#新安装的系统没有python pip,所以先安装它和其他依赖包
[[email protected] ~]# yum install python-pip gcc gcc-devel autoconf automake python-devel python-pip python-crypto python-cryptography -y
#安装alidns python DSK
[[email protected] ~]# pip install aliyun-python-sdk-alidns
还需要准备以下账号内容:
1. Access Key ID
2. Access Key Secret
3. 账号ID
准备好上面的内容后,将你的域名添加到阿里云解析DNS中:
WechatIMG23
完成后再在这个域名下添加一个主机A记录:
WechatIMG24
至此,准备工作已经完成。下面来获取域名的关键信息。
0x03 关键信息
通过脚本更新DNS记录需要几个关键的信息,如下:
1. 一级域名(你的域名)
2. 主机记录(你的二级域名)
3. 记录类型(你的本地IP地址)
4. 记录ID(这个解析记录的ID)
5. 记录TTL(记录有效生存时间)
0x03.1 记录ID
其中1,2,3,5是可以确定的,而4则需要通过阿里云API获取:
def check_records(dns_domain):
clt = client.AcsClient(access_key_id, access_Key_secret, 'cn-hangzhou')
request = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()
request.set_DomainName(dns_domain)
request.set_accept_format(rc_format)
result = clt.do_action_with_exception(request)
result = result.decode()
result_dict = json.JSONDecoder().decode(result)
result_list = result_dict['DomainRecords']['Record']
for j in result_list:
print('Subdomain:' + j['RR'].encode() + ' ' + '| RecordId:' + j['RecordId'].encode())
return
返还的内容如下:
[[email protected] aliyun_ddns]# python aliyun_ddns.py
Subdomain:subdomain_1 | RecordId:3331111111111111
Subdomain:subdomain_2 | RecordId:3331111111111111
Subdomain:subdomain_3 | RecordId:3331111111111111
Subdomain:subdomain_4 | RecordId:3331111111111111
Subdomain:subdomain_5 | RecordId:3331111111111111
Subdomain:subdomain_6 | RecordId:3331111111111111
0x03.2 本机IP
而获取本机IP,我选用ip.cn这个网站。当使用curl访问这个网站时,它会返还IP归属地和IP地址。使用脚本获取:
WechatIMG25
def my_ip_method_1():
get_ip_method = os.popen('curl -s ip.cn')
get_ip_responses = get_ip_method.readlines()[0]
get_ip_pattern = re.compile(r'\d+\.\d+\.\d+\.\d+')
get_ip_value = get_ip_pattern.findall(get_ip_responses)[0]
return get_ip_value
可能因为ip.cn这个站点受到攻击,他们的服务目前不太稳定,请使用my_ip_method_2或my_ip_method_3这两种本地IP的获取方式。
0x04 对比 | 更新
怎样才能知道IP地址是否有改变?
在获取本地IP后,再通过阿里云DNS API获取上一次的记录,两者相对比,如果不一致则更新DNS记录。
0x04.1 上一次的记录
def old_ip():
clt = client.AcsClient(access_key_id, access_Key_secret, 'cn-hangzhou')
request = DescribeDomainRecordInfoRequest.DescribeDomainRecordInfoRequest()
request.set_RecordId(rc_record_id)
request.set_accept_format(rc_format)
result = clt.do_action(request)
result = json.JSONDecoder().decode(result)
result = result['Value']
return result
0x04.2 更新记录
def update_dns(dns_rr, dns_type, dns_value, dns_record_id, dns_ttl, dns_format):
clt = client.AcsClient(access_key_id, access_Key_secret, 'cn-hangzhou')
request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
request.set_RR(dns_rr)
request.set_Type(dns_type)
request.set_Value(dns_value)
request.set_RecordId(dns_record_id)
request.set_TTL(dns_ttl)
request.set_accept_format(dns_format)
result = clt.do_action(request)
return result
0x04.3 对比
if rc_value_old == rc_value:
print 'The specified value of parameter Value is the same as old'
else:
update_dns(rc_rr, rc_type, rc_value, rc_record_id, rc_ttl, rc_format)
0x05 记录
我不但想要更新DDNS记录,我还想记录下每一次重新拨号后获取的IP,说不定日后能做个分析什么的。那么将记录写入文件:
def write_to_file():
time_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
current_script_path = sys.path[7]
print current_script_path
log_file = current_script_path + '/' + 'aliyun_ddns_log.txt'
write = open(log_file, 'a')
write.write(time_now + ' ' + str(rc_value) + '\n')
write.close()
return
0x06 完整脚本
最新完整脚本请移步至GitHub:阿里云DDNS python脚本
# -*- coding: UTF-8 -*-
import json
import os
import re
import sys
from datetime import datetime
import requests
from aliyunsdkalidns.request.v20150109 import UpdateDomainRecordRequest, DescribeDomainRecordsRequest, \
DescribeDomainRecordInfoRequest
from aliyunsdkcore import client
access_key_id = ""
access_Key_secret = ""
# 请填写你的账号ID
account_id = ""
# 如果填写yes,则运行程序后仅显示域名信息,并不会更新记录,用于获取解析记录ID。
# 如果填写no,则运行程序后不显示域名信息,仅更新记录。
i_dont_know_record_id = 'yes'
# 请填写你的一级域名
rc_domain = ''
# 请填写你的解析记录
rc_rr = ''
# 请填写你的记录类型,DDNS请填写A,表示A记录
rc_type = 'A'
# 请填写解析记录ID
rc_record_id = ''
# 请填写解析有效生存时间TTL,单位:秒
rc_ttl = '30'
# 请填写返还内容格式,json,xml
rc_format = 'json'
def my_ip_method_1():
get_ip_method = os.popen('curl -s ip.cn')
get_ip_responses = get_ip_method.readlines()[0]
get_ip_pattern = re.compile(r'\d+\.\d+\.\d+\.\d+')
get_ip_value = get_ip_pattern.findall(get_ip_responses)[0]
return get_ip_value
def my_ip_method_2():
get_ip_method = os.popen('curl -s http://ip-api.com/json')
get_ip_responses = get_ip_method.readlines()[0]
get_ip_responses = eval(str(get_ip_responses))
get_ip_value = get_ip_responses['query']
return get_ip_value
def my_ip_method_3():
get_ip_method = requests.get('http://ifconfig.co/json').content
get_ip_value = eval(get_ip_method)
get_ip_value = get_ip_value['ip']
return get_ip_value
def check_records(dns_domain):
clt = client.AcsClient(access_key_id, access_Key_secret, 'cn-hangzhou')
request = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()
request.set_DomainName(dns_domain)
request.set_accept_format(rc_format)
result = clt.do_action_with_exception(request)
result = result.decode()
result_dict = json.JSONDecoder().decode(result)
result_list = result_dict['DomainRecords']['Record']
for j in result_list:
print('Subdomain:' + j['RR'].encode() + ' ' + '| RecordId:' + j['RecordId'].encode())
return
def old_ip():
clt = client.AcsClient(access_key_id, access_Key_secret, 'cn-hangzhou')
request = DescribeDomainRecordInfoRequest.DescribeDomainRecordInfoRequest()
request.set_RecordId(rc_record_id)
request.set_accept_format(rc_format)
result = clt.do_action_with_exception(request).decode()
result = json.JSONDecoder().decode(result)
result = result['Value']
return result
def update_dns(dns_rr, dns_type, dns_value, dns_record_id, dns_ttl, dns_format):
clt = client.AcsClient(access_key_id, access_Key_secret, 'cn-hangzhou')
request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
request.set_RR(dns_rr)
request.set_Type(dns_type)
request.set_Value(dns_value)
request.set_RecordId(dns_record_id)
request.set_TTL(dns_ttl)
request.set_accept_format(dns_format)
result = clt.do_action_with_exception(request)
return result
def write_to_file():
time_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
current_script_path = sys.path[1]
log_file = current_script_path + '/' + 'aliyun_ddns_log.txt'
write = open(log_file, 'a')
write.write(time_now + ' ' + str(rc_value) + '\n')
write.close()
return
if i_dont_know_record_id == 'yes':
check_records(rc_domain)
elif i_dont_know_record_id == 'no':
rc_value = my_ip_method_3()
rc_value_old = old_ip()
if rc_value_old == rc_value:
print('The specified value of parameter Value is the same as old')
else:
print(update_dns(rc_rr, rc_type, rc_value, rc_record_id, rc_ttl, rc_format))
write_to_file()
可能因为ip.cn这个站点收到攻击,他们的服务目前不太稳定,请使用my_ip_method_2或my_ip_method_3这两种本地IP的获取方式。
修改第117行即可修改本地IP的获取方式。
0x07 运行
将程序通过crontab每分钟运行一次,请将脚本路径修改为你的实际路径:
*/1 * * * * root /usr/bin/python2.7 /usr/local/shell/aliyun_ddns.py > /dev/null 1>/dev/null
0x08 结语
其实这个脚本也可以更新其他类型的DNS记录,例如:CNAME,TXT等,只要知道解析记录ID即可。
经过近3天的运行,一切正常。 | __label__pos | 0.968458 |
1//===- MsgPackWriter.h - Simple MsgPack writer ------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains a MessagePack writer.
11///
12/// See https://github.com/msgpack/msgpack/blob/master/spec.md for the full
13/// specification.
14///
15/// Typical usage:
16/// \code
17/// raw_ostream output = GetOutputStream();
18/// msgpack::Writer MPWriter(output);
19/// MPWriter.writeNil();
20/// MPWriter.write(false);
21/// MPWriter.write("string");
22/// // ...
23/// \endcode
24///
25///
26//===----------------------------------------------------------------------===//
27
28#ifndef LLVM_BINARYFORMAT_MSGPACKWRITER_H
29#define LLVM_BINARYFORMAT_MSGPACKWRITER_H
30
31#include "llvm/BinaryFormat/MsgPack.h"
32#include "llvm/Support/EndianStream.h"
33#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/raw_ostream.h"
35
36namespace llvm {
37namespace msgpack {
38
39/// Writes MessagePack objects to an output stream, one at a time.
40class Writer {
41public:
42 /// Construct a writer, optionally enabling "Compatibility Mode" as defined
43 /// in the MessagePack specification.
44 ///
45 /// When in \p Compatible mode, the writer will write \c Str16 formats
46 /// instead of \c Str8 formats, and will refuse to write any \c Bin formats.
47 ///
48 /// \param OS stream to output MessagePack objects to.
49 /// \param Compatible when set, write in "Compatibility Mode".
50 Writer(raw_ostream &OS, bool Compatible = false);
51
52 Writer(const Writer &) = delete;
53 Writer &operator=(const Writer &) = delete;
54
55 /// Write a \em Nil to the output stream.
56 ///
57 /// The output will be the \em nil format.
58 void writeNil();
59
60 /// Write a \em Boolean to the output stream.
61 ///
62 /// The output will be a \em bool format.
63 void write(bool b);
64
65 /// Write a signed integer to the output stream.
66 ///
67 /// The output will be in the smallest possible \em int format.
68 ///
69 /// The format chosen may be for an unsigned integer.
70 void write(int64_t i);
71
72 /// Write an unsigned integer to the output stream.
73 ///
74 /// The output will be in the smallest possible \em int format.
75 void write(uint64_t u);
76
77 /// Write a floating point number to the output stream.
78 ///
79 /// The output will be in the smallest possible \em float format.
80 void write(double d);
81
82 /// Write a string to the output stream.
83 ///
84 /// The output will be in the smallest possible \em str format.
85 void write(StringRef s);
86
87 /// Write a memory buffer to the output stream.
88 ///
89 /// The output will be in the smallest possible \em bin format.
90 ///
91 /// \warning Do not use this overload if in \c Compatible mode.
92 void write(MemoryBufferRef Buffer);
93
94 /// Write the header for an \em Array of the given size.
95 ///
96 /// The output will be in the smallest possible \em array format.
97 //
98 /// The header contains an identifier for the \em array format used, as well
99 /// as an encoding of the size of the array.
100 ///
101 /// N.B. The caller must subsequently call \c Write an additional \p Size
102 /// times to complete the array.
103 void writeArraySize(uint32_t Size);
104
105 /// Write the header for a \em Map of the given size.
106 ///
107 /// The output will be in the smallest possible \em map format.
108 //
109 /// The header contains an identifier for the \em map format used, as well
110 /// as an encoding of the size of the map.
111 ///
112 /// N.B. The caller must subsequently call \c Write and additional \c Size*2
113 /// times to complete the map. Each even numbered call to \c Write defines a
114 /// new key, and each odd numbered call defines the previous key's value.
115 void writeMapSize(uint32_t Size);
116
117 /// Write a typed memory buffer (an extension type) to the output stream.
118 ///
119 /// The output will be in the smallest possible \em ext format.
120 void writeExt(int8_t Type, MemoryBufferRef Buffer);
121
122private:
123 support::endian::Writer EW;
124 bool Compatible;
125};
126
127} // end namespace msgpack
128} // end namespace llvm
129
130#endif // LLVM_BINARYFORMAT_MSGPACKWRITER_H
131 | __label__pos | 0.937465 |
LibreOffice Module sw (master) 1
fldref.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20 #include <swtypes.hxx>
21 #include <view.hxx>
22 #include <IMark.hxx>
23 #include <expfld.hxx>
24 #include <swmodule.hxx>
25 #include "fldref.hxx"
26 #include <reffld.hxx>
27 #include <wrtsh.hxx>
28
29 #include <fldref.hrc>
30 #include <globals.hrc>
31 #include <strings.hrc>
32 #include <SwNodeNum.hxx>
33 #include <IDocumentMarkAccess.hxx>
34 #include <ndtxt.hxx>
35 #include <unotools/configmgr.hxx>
37 #include <unotools/charclass.hxx>
38
39 #include <comphelper/string.hxx>
40
41 #define REFFLDFLAG 0x4000
42 #define REFFLDFLAG_BOOKMARK 0x4800
43 #define REFFLDFLAG_FOOTNOTE 0x5000
44 #define REFFLDFLAG_ENDNOTE 0x6000
45 // #i83479#
46 #define REFFLDFLAG_HEADING 0x7100
47 #define REFFLDFLAG_NUMITEM 0x7200
48
49 static sal_uInt16 nFieldDlgFormatSel = 0;
50
51 #define USER_DATA_VERSION_1 "1"
52 #define USER_DATA_VERSION USER_DATA_VERSION_1
53
55 : SwFieldPage(pPage, pController, "modules/swriter/ui/fldrefpage.ui", "FieldRefPage", pCoreSet)
56 , maOutlineNodes()
57 , maNumItems()
58 , mpSavedSelectedTextNode(nullptr)
59 , mnSavedSelectedPos(0)
60 , m_xTypeLB(m_xBuilder->weld_tree_view("type"))
61 , m_xSelection(m_xBuilder->weld_widget("selectframe"))
62 , m_xSelectionLB(m_xBuilder->weld_tree_view("select"))
63 , m_xSelectionToolTipLB(m_xBuilder->weld_tree_view("selecttip"))
64 , m_xFormat(m_xBuilder->weld_widget("formatframe"))
65 , m_xFormatLB(m_xBuilder->weld_tree_view("format"))
66 , m_xNameFT(m_xBuilder->weld_label("nameft"))
67 , m_xNameED(m_xBuilder->weld_entry("name"))
68 , m_xValueED(m_xBuilder->weld_entry("value"))
69 , m_xFilterED(m_xBuilder->weld_entry("filter"))
70 {
71 m_xSelectionLB->make_sorted();
72 // #i83479#
73 for (size_t i = 0; i < SAL_N_ELEMENTS(FLD_REF_PAGE_TYPES); ++i)
74 {
75 m_xTypeLB->append_text(SwResId(FLD_REF_PAGE_TYPES[i]));
76 m_xFormatLB->append_text(SwResId(FLD_REF_PAGE_TYPES[i]));
77 }
78
79 sBookmarkText = m_xTypeLB->get_text(0);
80 sFootnoteText = m_xTypeLB->get_text(1);
81 sEndnoteText = m_xTypeLB->get_text(2);
82 // #i83479#
83 sHeadingText = m_xTypeLB->get_text(3);
84 sNumItemText = m_xTypeLB->get_text(4);
85
86 auto nHeight = m_xTypeLB->get_height_rows(8);
87 auto nWidth = m_xTypeLB->get_approximate_digit_width() * FIELD_COLUMN_WIDTH;
88 m_xTypeLB->set_size_request(nWidth, nHeight);
89 m_xFormatLB->set_size_request(nWidth, nHeight);
90 m_xSelection->set_size_request(nWidth * 2, nHeight);
91 nHeight = m_xTypeLB->get_height_rows(20);
92 m_xSelectionToolTipLB->set_size_request(nHeight, nWidth*2);
93
94 m_xTypeLB->clear();
95
96 m_xNameED->connect_changed(LINK(this, SwFieldRefPage, ModifyHdl));
97 m_xFilterED->connect_changed( LINK( this, SwFieldRefPage, ModifyHdl_Impl ) );
98
99 m_xTypeLB->connect_row_activated(LINK(this, SwFieldRefPage, TreeViewInsertHdl));
100 m_xTypeLB->connect_changed(LINK(this, SwFieldRefPage, TypeHdl));
101 m_xSelectionLB->connect_changed(LINK(this, SwFieldRefPage, SubTypeListBoxHdl));
102 m_xSelectionLB->connect_row_activated(LINK(this, SwFieldRefPage, TreeViewInsertHdl));
103 m_xFormatLB->connect_row_activated(LINK(this, SwFieldRefPage, TreeViewInsertHdl));
104
105 // #i83479#
106 m_xSelectionToolTipLB->connect_changed( LINK(this, SwFieldRefPage, SubTypeTreeListBoxHdl) );
107 m_xSelectionToolTipLB->connect_row_activated( LINK(this, SwFieldRefPage, TreeViewInsertHdl) );
108 m_xFilterED->grab_focus();
109 }
110
112 {
113 }
114
116 {
117 UpdateSubType(comphelper::string::strip(m_xFilterED->get_text(), ' '));
118 }
119
120 // #i83479#
122 {
123 mpSavedSelectedTextNode = nullptr;
124 mnSavedSelectedPos = 0;
125 if ( m_xSelectionToolTipLB->get_visible() )
126 {
127 int nEntry = m_xSelectionToolTipLB->get_selected_index();
128 if (nEntry != -1)
129 {
130 const sal_uInt16 nTypeId = m_xTypeLB->get_id(GetTypeSel()).toUInt32();
131
132 if ( nTypeId == REFFLDFLAG_HEADING )
133 {
134 mnSavedSelectedPos = m_xSelectionToolTipLB->get_id(nEntry).toUInt32();
135 if ( mnSavedSelectedPos < maOutlineNodes.size() )
136 {
138 }
139 }
140 else if ( nTypeId == REFFLDFLAG_NUMITEM )
141 {
142 mnSavedSelectedPos = m_xSelectionToolTipLB->get_id(nEntry).toUInt32();
143 if ( mnSavedSelectedPos < maNumItems.size() )
144 {
146 }
147 }
148 }
149 }
150 }
151
153 {
154 if (!IsFieldEdit())
155 {
156 SavePos(*m_xTypeLB);
157 // #i83479#
159 }
160 SetSelectionSel(-1);
161 SetTypeSel(-1);
162 Init(); // general initialisation
163
164 // initialise TypeListBox
165 m_xTypeLB->freeze();
166 m_xTypeLB->clear();
167
168 // fill Type-Listbox
169
170 // set/insert reference
172
173 for (short i = rRg.nStart; i < rRg.nEnd; ++i)
174 {
175 const SwFieldTypesEnum nTypeId = SwFieldMgr::GetTypeId(i);
176
177 if (!IsFieldEdit() || nTypeId != SwFieldTypesEnum::SetRef)
178 {
179 m_xTypeLB->append(OUString::number(static_cast<sal_uInt16>(nTypeId)), SwFieldMgr::GetTypeStr(i));
180 }
181 }
182
183 // #i83479#
184 // entries for headings and numbered items
185 m_xTypeLB->append(OUString::number(REFFLDFLAG_HEADING), sHeadingText);
186 m_xTypeLB->append(OUString::number(REFFLDFLAG_NUMITEM), sNumItemText);
187
188 // fill up with the sequence types
189 SwWrtShell *pSh = GetWrtShell();
190 if (!pSh)
191 pSh = ::GetActiveWrtShell();
192
193 if (!pSh)
194 return;
195
196 const size_t nFieldTypeCnt = pSh->GetFieldTypeCount(SwFieldIds::SetExp);
197
198 OSL_ENSURE( nFieldTypeCnt < static_cast<size_t>(REFFLDFLAG), "<SwFieldRefPage::Reset> - Item index will overlap flags!" );
199
200 for (size_t n = 0; n < nFieldTypeCnt; ++n)
201 {
203
204 if ((nsSwGetSetExpType::GSE_SEQ & pType->GetType()) && pType->HasWriterListeners() && pSh->IsUsed(*pType))
205 {
206 m_xTypeLB->append(OUString::number(REFFLDFLAG | n), pType->GetName());
207 }
208 }
209
210 // text marks - now always (because of globaldocuments)
211 m_xTypeLB->append(OUString::number(REFFLDFLAG_BOOKMARK), sBookmarkText);
212
213 // footnotes:
214 if( pSh->HasFootnotes() )
215 {
216 m_xTypeLB->append(OUString::number(REFFLDFLAG_FOOTNOTE), sFootnoteText);
217 }
218
219 // endnotes:
220 if ( pSh->HasFootnotes(true) )
221 {
222 m_xTypeLB->append(OUString::number(REFFLDFLAG_ENDNOTE), sEndnoteText);
223 }
224
225 m_xTypeLB->thaw();
226
227 // select old Pos
228 if (!IsFieldEdit())
230
231 nFieldDlgFormatSel = 0;
232
233 sal_uInt16 nFormatBoxPosition = USHRT_MAX;
234 if( !IsRefresh() )
235 {
236 sal_Int32 nIdx{ 0 };
237 const OUString sUserData = GetUserData();
238 if(!IsRefresh() && sUserData.getToken(0, ';', nIdx).
239 equalsIgnoreAsciiCase(USER_DATA_VERSION_1))
240 {
241 const sal_uInt16 nVal = static_cast< sal_uInt16 >(sUserData.getToken(0, ';', nIdx).toInt32());
242 if(nVal != USHRT_MAX)
243 {
244 for(sal_Int32 i = 0, nEntryCount = m_xTypeLB->n_children(); i < nEntryCount; ++i)
245 {
246 if (nVal == m_xTypeLB->get_id(i).toUInt32())
247 {
248 m_xTypeLB->select(i);
249 break;
250 }
251 }
252 if (nIdx>=0 && nIdx<sUserData.getLength())
253 {
254 nFormatBoxPosition = static_cast< sal_uInt16 >(sUserData.getToken(0, ';', nIdx).toInt32());
255 }
256 }
257 }
258 }
259 TypeHdl(*m_xTypeLB);
260 if (nFormatBoxPosition < m_xFormatLB->n_children())
261 {
262 m_xFormatLB->select(nFormatBoxPosition);
263 }
264 if (IsFieldEdit())
265 {
266 m_xTypeLB->save_value();
267 m_xSelectionLB->save_value();
268 m_xFormatLB->save_value();
269 m_xNameED->save_value();
270 m_xValueED->save_value();
271 m_xFilterED->set_text(OUString());
272 }
273 }
274
276 {
277 // save old ListBoxPos
278 const sal_Int32 nOld = GetTypeSel();
279
280 // current ListBoxPos
281 SetTypeSel(m_xTypeLB->get_selected_index());
282
283 if(GetTypeSel() == -1)
284 {
285 if (IsFieldEdit())
286 {
287 // select positions
288 OUString sName;
289 sal_uInt16 nFlag = 0;
290
291 switch( GetCurField()->GetSubType() )
292 {
293 case REF_BOOKMARK:
294 {
295 // #i83479#
296 SwGetRefField* pRefField = dynamic_cast<SwGetRefField*>(GetCurField());
297 if ( pRefField &&
298 pRefField->IsRefToHeadingCrossRefBookmark() )
299 {
300 sName = sHeadingText;
301 nFlag = REFFLDFLAG_HEADING;
302 }
303 else if ( pRefField &&
304 pRefField->IsRefToNumItemCrossRefBookmark() )
305 {
306 sName = sNumItemText;
307 nFlag = REFFLDFLAG_NUMITEM;
308 }
309 else
310 {
311 sName = sBookmarkText;
312 nFlag = REFFLDFLAG_BOOKMARK;
313 }
314 }
315 break;
316
317 case REF_FOOTNOTE:
318 sName = sFootnoteText;
319 nFlag = REFFLDFLAG_FOOTNOTE;
320 break;
321
322 case REF_ENDNOTE:
323 sName = sEndnoteText;
324 nFlag = REFFLDFLAG_ENDNOTE;
325 break;
326
327 case REF_SETREFATTR:
328 sName = SwResId(STR_GETREFFLD);
329 nFlag = REF_SETREFATTR;
330 break;
331
332 case REF_SEQUENCEFLD:
333 sName = static_cast<SwGetRefField*>(GetCurField())->GetSetRefName();
334 nFlag = REFFLDFLAG;
335 break;
336 }
337
338 if (m_xTypeLB->find_text(sName) == -1) // reference to deleted mark
339 {
340 m_xTypeLB->append(OUString::number(nFlag), sName);
341 }
342
343 m_xTypeLB->select_text(sName);
344 SetTypeSel(m_xTypeLB->get_selected_index());
345 }
346 else
347 {
348 SetTypeSel(0);
349 m_xTypeLB->select(0);
350 }
351 }
352
353 if (nOld == GetTypeSel())
354 return;
355
356 sal_uInt16 nTypeId = m_xTypeLB->get_id(GetTypeSel()).toUInt32();
357
358 // fill selection-ListBox
359 UpdateSubType(comphelper::string::strip(m_xFilterED->get_text(), ' '));
360
361 bool bName = false;
362 nFieldDlgFormatSel = 0;
363
364 if ( ( !IsFieldEdit() || m_xSelectionLB->n_children() ) &&
365 nOld != -1 )
366 {
367 m_xNameED->set_text(OUString());
368 m_xValueED->set_text(OUString());
369 m_xFilterED->set_text(OUString());
370 }
371
372 switch (nTypeId)
373 {
374 case static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef):
375 if (nOld != -1 && REFFLDFLAG & m_xTypeLB->get_id(nOld).toUInt32())
376 // the old one stays
377 nFieldDlgFormatSel = m_xFormatLB->get_selected_index();
378 bName = true;
379 break;
380
381 case static_cast<sal_uInt16>(SwFieldTypesEnum::SetRef):
382 bName = true;
383 break;
384
385 case REFFLDFLAG_BOOKMARK:
386 bName = true;
387 [[fallthrough]];
388 default:
389 if( REFFLDFLAG & nTypeId )
390 {
391 const sal_uInt16 nOldId = nOld != -1 ? m_xTypeLB->get_id(nOld).toUInt32() : 0;
392 if( nOldId & REFFLDFLAG || nOldId == static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef) )
393 // then the old one stays
394 nFieldDlgFormatSel = m_xFormatLB->get_selected_index();
395 }
396 break;
397 }
398
399 m_xNameED->set_sensitive(bName);
400 m_xNameFT->set_sensitive(bName);
401
402 // fill Format-Listbox
403 sal_Int32 nSize = FillFormatLB(nTypeId);
404 bool bFormat = nSize != 0;
405 m_xFormat->set_sensitive(bFormat);
406
407 SubTypeHdl();
408 ModifyHdl(*m_xNameED);
409 ModifyHdl(*m_xFilterED);
410 }
411
412 IMPL_LINK_NOARG(SwFieldRefPage, SubTypeTreeListBoxHdl, weld::TreeView&, void)
413 {
414 SubTypeHdl();
415 }
416
417 IMPL_LINK_NOARG(SwFieldRefPage, SubTypeListBoxHdl, weld::TreeView&, void)
418 {
419 SubTypeHdl();
420 }
421
423 {
424 sal_uInt16 nTypeId = m_xTypeLB->get_id(GetTypeSel()).toUInt32();
425
426 switch(nTypeId)
427 {
428 case static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef):
429 if (!IsFieldEdit() || m_xSelectionLB->get_selected_index() != -1)
430 {
431 m_xNameED->set_text(m_xSelectionLB->get_selected_text());
432 ModifyHdl(*m_xNameED);
433 }
434 break;
435
436 case static_cast<sal_uInt16>(SwFieldTypesEnum::SetRef):
437 {
438 SwWrtShell *pSh = GetWrtShell();
439 if(!pSh)
440 pSh = ::GetActiveWrtShell();
441 if(pSh)
442 {
443 m_xValueED->set_text(pSh->GetSelText());
444 }
445
446 }
447 break;
448 // #i83479#
449 case REFFLDFLAG_HEADING:
450 case REFFLDFLAG_NUMITEM:
451 {
452 int nEntry = m_xSelectionToolTipLB->get_selected_index();
453 if (nEntry != -1)
454 m_xNameED->set_text(m_xSelectionToolTipLB->get_text(nEntry));
455 }
456 break;
457
458 default:
459 if (!IsFieldEdit() || m_xSelectionLB->get_selected_index() != -1)
460 m_xNameED->set_text(m_xSelectionLB->get_selected_text());
461 break;
462 }
463 }
464
465 // renew types in SelectionLB after filtering
466 void SwFieldRefPage::UpdateSubType(const OUString& filterString)
467 {
468 SwWrtShell *pSh = GetWrtShell();
469 if(!pSh)
470 pSh = ::GetActiveWrtShell();
471 SwGetRefField* pRefField = static_cast<SwGetRefField*>(GetCurField());
472 const sal_uInt16 nTypeId = m_xTypeLB->get_id(GetTypeSel()).toUInt32();
473
474 OUString sOldSel;
475 // #i83479#
476 if ( m_xSelectionLB->get_visible() )
477 {
478 const sal_Int32 nSelectionSel = m_xSelectionLB->get_selected_index();
479 if (nSelectionSel != -1)
480 sOldSel = m_xSelectionLB->get_text(nSelectionSel);
481 }
482 if (IsFieldEdit() && sOldSel.isEmpty())
483 sOldSel = OUString::number( pRefField->GetSeqNo() + 1 );
484
485 m_xSelectionLB->freeze();
486 m_xSelectionLB->clear();
487
488 if (REFFLDFLAG & nTypeId)
489 {
490 if (nTypeId == REFFLDFLAG_FOOTNOTE || nTypeId == REFFLDFLAG_ENDNOTE)
491 {
492 m_xSelectionLB->thaw();
493 m_xSelectionLB->make_unsorted();
494 m_xSelectionLB->freeze();
495 }
496 // #i83479#
497 else if (nTypeId != REFFLDFLAG_HEADING && nTypeId != REFFLDFLAG_NUMITEM)
498 {
499 m_xSelectionLB->thaw();
500 m_xSelectionLB->make_sorted();
501 m_xSelectionLB->freeze();
502 }
503 }
504
505 // #i83479#
506 m_xSelectionToolTipLB->freeze();
507 m_xSelectionToolTipLB->clear();
508 OUString m_sSelectionToolTipLBId;
509 bool bShowSelectionToolTipLB( false );
510
511 if( REFFLDFLAG & nTypeId )
512 {
513 if (nTypeId == REFFLDFLAG_BOOKMARK) // text marks!
514 {
515 // get all text marks
516 IDocumentMarkAccess* const pMarkAccess = pSh->getIDocumentMarkAccess();
517 for(IDocumentMarkAccess::const_iterator_t ppMark = pMarkAccess->getBookmarksBegin();
518 ppMark != pMarkAccess->getBookmarksEnd();
519 ++ppMark)
520 {
521 const ::sw::mark::IMark* pBkmk = *ppMark;
523 {
524 bool isSubstring = MatchSubstring(pBkmk->GetName(), filterString);
525 if(isSubstring)
526 {
527 m_xSelectionLB->append_text( pBkmk->GetName() );
528 }
529 }
530 }
531 if (IsFieldEdit())
532 sOldSel = pRefField->GetSetRefName();
533 }
534 else if (nTypeId == REFFLDFLAG_FOOTNOTE)
535 {
537 const size_t nCnt = pSh->GetSeqFootnoteList( aArr );
538
539 for( size_t n = 0; n < nCnt; ++n )
540 {
541 bool isSubstring = MatchSubstring(aArr[ n ].sDlgEntry, filterString);
542 if(isSubstring)
543 {
544 m_xSelectionLB->append_text( aArr[ n ].sDlgEntry );
545 }
546 if (IsFieldEdit() && pRefField->GetSeqNo() == aArr[ n ].nSeqNo)
547 sOldSel = aArr[n].sDlgEntry;
548 }
549 }
550 else if (nTypeId == REFFLDFLAG_ENDNOTE)
551 {
553 const size_t nCnt = pSh->GetSeqFootnoteList( aArr, true );
554
555 for( size_t n = 0; n < nCnt; ++n )
556 {
557 bool isSubstring = MatchSubstring(aArr[ n ].sDlgEntry, filterString);
558 if(isSubstring)
559 {
560 m_xSelectionLB->append_text( aArr[ n ].sDlgEntry );
561 }
562 if (IsFieldEdit() && pRefField->GetSeqNo() == aArr[ n ].nSeqNo)
563 sOldSel = aArr[n].sDlgEntry;
564 }
565 }
566 // #i83479#
567 else if ( nTypeId == REFFLDFLAG_HEADING )
568 {
569 bShowSelectionToolTipLB = true;
570
573 bool bCertainTextNodeSelected( false );
574 for ( size_t nOutlIdx = 0; nOutlIdx < maOutlineNodes.size(); ++nOutlIdx )
575 {
576 if (!pIDoc->isOutlineInLayout(nOutlIdx, *pSh->GetLayout()))
577 {
578 continue; // skip it
579 }
580 bool isSubstring = MatchSubstring(pIDoc->getOutlineText(nOutlIdx, pSh->GetLayout(), true, true, false), filterString);
581 if(isSubstring)
582 {
583 OUString sId(OUString::number(nOutlIdx));
584 m_xSelectionToolTipLB->append(sId,
585 pIDoc->getOutlineText(nOutlIdx, pSh->GetLayout(), true, true, false));
586 if ( ( IsFieldEdit() &&
587 pRefField->GetReferencedTextNode() == maOutlineNodes[nOutlIdx] ) ||
589 {
590 m_sSelectionToolTipLBId = sId;
591 sOldSel.clear();
592 bCertainTextNodeSelected = true;
593 }
594 else if ( !bCertainTextNodeSelected && mnSavedSelectedPos == nOutlIdx )
595 {
596 m_sSelectionToolTipLBId = sId;
597 sOldSel.clear();
598 }
599 }
600 }
601 }
602 else if ( nTypeId == REFFLDFLAG_NUMITEM )
603 {
604 bShowSelectionToolTipLB = true;
605
606 const IDocumentListItems* pIDoc( pSh->getIDocumentListItemsAccess() );
607 pIDoc->getNumItems( maNumItems );
608 bool bCertainTextNodeSelected( false );
609 for ( size_t nNumItemIdx = 0; nNumItemIdx < maNumItems.size(); ++nNumItemIdx )
610 {
611 if (!pIDoc->isNumberedInLayout(*maNumItems[nNumItemIdx], *pSh->GetLayout()))
612 {
613 continue; // skip it
614 }
615 bool isSubstring = MatchSubstring(pIDoc->getListItemText(*maNumItems[nNumItemIdx], *pSh->GetLayout()), filterString);
616 if(isSubstring)
617 {
618 OUString sId(OUString::number(nNumItemIdx));
619 m_xSelectionToolTipLB->append(sId,
620 pIDoc->getListItemText(*maNumItems[nNumItemIdx], *pSh->GetLayout()));
621 if ( ( IsFieldEdit() &&
622 pRefField->GetReferencedTextNode() == maNumItems[nNumItemIdx]->GetTextNode() ) ||
623 mpSavedSelectedTextNode == maNumItems[nNumItemIdx]->GetTextNode() )
624 {
625 m_sSelectionToolTipLBId = sId;
626 sOldSel.clear();
627 bCertainTextNodeSelected = true;
628 }
629 else if ( !bCertainTextNodeSelected && mnSavedSelectedPos == nNumItemIdx )
630 {
631 m_sSelectionToolTipLBId = sId;
632 sOldSel.clear();
633 }
634 }
635 }
636 }
637 else
638 {
639 // get the fields to Seq-FieldType:
640
641 SwSetExpFieldType* pType = static_cast<SwSetExpFieldType*>(pSh->GetFieldType(
642 nTypeId & ~REFFLDFLAG, SwFieldIds::SetExp ));
643 if( pType )
644 {
646 // old selection should be kept in non-edit mode
647 if(IsFieldEdit())
648 sOldSel.clear();
649
650 const size_t nCnt = pType->GetSeqFieldList(aArr, pSh->GetLayout());
651 for( size_t n = 0; n < nCnt; ++n )
652 {
653 bool isSubstring = MatchSubstring(aArr[ n ].sDlgEntry, filterString);
654 if(isSubstring)
655 {
656 m_xSelectionLB->append_text( aArr[ n ].sDlgEntry );
657 }
658 if (IsFieldEdit() && sOldSel.isEmpty() &&
659 aArr[ n ].nSeqNo == pRefField->GetSeqNo())
660 sOldSel = aArr[ n ].sDlgEntry;
661 }
662
663 if (IsFieldEdit() && sOldSel.isEmpty())
664 sOldSel = OUString::number( pRefField->GetSeqNo() + 1);
665 }
666 }
667 }
668 else
669 {
670 std::vector<OUString> aLst;
671 GetFieldMgr().GetSubTypes(static_cast<SwFieldTypesEnum>(nTypeId), aLst);
672 for(const OUString & i : aLst)
673 {
674 bool isSubstring = MatchSubstring( i , filterString );
675 if(isSubstring)
676 {
677 m_xSelectionLB->append_text(i);
678 }
679 }
680
681 if (IsFieldEdit())
682 sOldSel = pRefField->GetSetRefName();
683 }
684
685 // #i83479#
686 m_xSelectionLB->thaw();
687 m_xSelectionToolTipLB->thaw();
688 if (!m_sSelectionToolTipLBId.isEmpty())
689 m_xSelectionToolTipLB->select_id(m_sSelectionToolTipLBId);
690 m_xSelectionToolTipLB->set_visible( bShowSelectionToolTipLB );
691 m_xSelectionLB->set_visible( !bShowSelectionToolTipLB );
692 if ( bShowSelectionToolTipLB )
693 {
694 bool bEnable = m_xSelectionToolTipLB->n_children() != 0;
695 m_xSelection->set_sensitive( bEnable );
696
697 int nEntry = m_xSelectionToolTipLB->get_selected_index();
698 if (nEntry != -1)
699 m_xSelectionToolTipLB->scroll_to_row(nEntry);
700
701 if (IsFieldEdit() && nEntry == -1)
702 {
703 m_xNameED->set_text(sOldSel);
704 }
705 }
706 else
707 {
708 // enable or disable
709 bool bEnable = m_xSelectionLB->n_children() != 0;
710 m_xSelection->set_sensitive( bEnable );
711
712 if ( bEnable )
713 {
714 m_xSelectionLB->select_text(sOldSel);
715 if (m_xSelectionLB->get_selected_index() == -1 && !IsFieldEdit())
716 m_xSelectionLB->select(0);
717 }
718
719 if (IsFieldEdit() && m_xSelectionLB->get_selected_index() == -1) // in case the reference was already deleted...
720 m_xNameED->set_text(sOldSel);
721 }
722 }
723
724 bool SwFieldRefPage::MatchSubstring( const OUString& rListString, const OUString& rSubstr )
725 {
726 if(rSubstr.isEmpty())
727 return true;
728 OUString aListString = GetAppCharClass().lowercase(rListString);
729 OUString aSubstr = GetAppCharClass().lowercase(rSubstr);
730 return aListString.indexOf(aSubstr) >= 0;
731 }
732
733 namespace {
734
736 {
737 FMT_REF_PAGE_IDX = 0,
738 FMT_REF_CHAPTER_IDX = 1,
739 FMT_REF_TEXT_IDX = 2,
740 FMT_REF_UPDOWN_IDX = 3,
741 FMT_REF_PAGE_PGDSC_IDX = 4,
742 FMT_REF_ONLYNUMBER_IDX = 5,
743 FMT_REF_ONLYCAPTION_IDX = 6,
744 FMT_REF_ONLYSEQNO_IDX = 7,
745 FMT_REF_NUMBER_IDX = 8,
746 FMT_REF_NUMBER_NO_CONTEXT_IDX = 9,
747 FMT_REF_NUMBER_FULL_CONTEXT_IDX = 10
748 };
749
750 }
751
752 static const char* FMT_REF_ARY[] =
753 {
754 FMT_REF_PAGE,
755 FMT_REF_CHAPTER,
756 FMT_REF_TEXT,
757 FMT_REF_UPDOWN,
758 FMT_REF_PAGE_PGDSC,
759 FMT_REF_ONLYNUMBER,
760 FMT_REF_ONLYCAPTION,
761 FMT_REF_ONLYSEQNO,
762 FMT_REF_NUMBER,
763 FMT_REF_NUMBER_NO_CONTEXT,
764 FMT_REF_NUMBER_FULL_CONTEXT
765 };
766
767 sal_Int32 SwFieldRefPage::FillFormatLB(sal_uInt16 nTypeId)
768 {
769 OUString sOldSel;
770
771 sal_Int32 nFormatSel = m_xFormatLB->get_selected_index();
772 if (nFormatSel != -1)
773 sOldSel = m_xFormatLB->get_text(nFormatSel);
774
775 // fill Format-Listbox
776 m_xFormatLB->clear();
777
778 // reference has less that the annotation
779 sal_uInt16 nSize( 0 );
780 bool bAddCrossRefFormats( false );
781 switch (nTypeId)
782 {
783 // #i83479#
784 case REFFLDFLAG_HEADING:
785 case REFFLDFLAG_NUMITEM:
786 bAddCrossRefFormats = true;
787 [[fallthrough]];
788
789 case static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef):
790 case REFFLDFLAG_BOOKMARK:
791 case REFFLDFLAG_FOOTNOTE:
792 case REFFLDFLAG_ENDNOTE:
793 nSize = FMT_REF_PAGE_PGDSC_IDX + 1;
794 break;
795
796 default:
797 // #i83479#
798
799 if ( REFFLDFLAG & nTypeId )
800 {
801 nSize = FMT_REF_ONLYSEQNO_IDX + 1;
802 }
803 else
804 {
805 nSize = GetFieldMgr().GetFormatCount( static_cast<SwFieldTypesEnum>(nTypeId), IsFieldDlgHtmlMode() );
806 }
807 break;
808 }
809
810 if (REFFLDFLAG & nTypeId)
811 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
812
813 SwFieldTypesEnum nFieldType = static_cast<SwFieldTypesEnum>(nTypeId);
814 for (sal_uInt16 i = 0; i < nSize; i++)
815 {
816 OUString sId(OUString::number(GetFieldMgr().GetFormatId( nFieldType, i )));
817 m_xFormatLB->append(sId, GetFieldMgr().GetFormatStr(nFieldType, i));
818 }
819 // #i83479#
820
821 sal_uInt16 nExtraSize( 0 );
822 if ( bAddCrossRefFormats )
823 {
824 sal_uInt16 nFormat = FMT_REF_NUMBER_IDX;
825 OUString sId(OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat)));
826 m_xFormatLB->append(sId, GetFieldMgr().GetFormatStr( nFieldType, nFormat ));
827 nFormat = FMT_REF_NUMBER_NO_CONTEXT_IDX;
828 sId = OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat));
829 m_xFormatLB->append(sId, GetFieldMgr().GetFormatStr( nFieldType, nFormat ));
830 nFormat = FMT_REF_NUMBER_FULL_CONTEXT_IDX;
831 sId = OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat));
832 m_xFormatLB->append(sId, GetFieldMgr().GetFormatStr( nFieldType, nFormat ));
833 nExtraSize = 3;
834 }
835
836 // extra list items optionally, depending from reference-language
837 SvtSysLocaleOptions aSysLocaleOptions;
838 static const LanguageTag& rLang = aSysLocaleOptions.GetRealLanguageTag();
839
840 if (rLang.getLanguage() == "hu")
841 {
842 for (sal_uInt16 i = 0; i < nSize; i++)
843 {
844 OUString sId(OUString::number(GetFieldMgr().GetFormatId( nFieldType, i + SAL_N_ELEMENTS(FMT_REF_ARY))));
845 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_LOWERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, i ));
846 }
847 nExtraSize += nSize;
848
849 if ( bAddCrossRefFormats )
850 {
851 sal_uInt16 nFormat = FMT_REF_NUMBER_IDX + SAL_N_ELEMENTS(FMT_REF_ARY);
852 OUString sId(OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat)));
853 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_LOWERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, nFormat % SAL_N_ELEMENTS(FMT_REF_ARY)));
854 nFormat = FMT_REF_NUMBER_NO_CONTEXT_IDX + SAL_N_ELEMENTS(FMT_REF_ARY);
855 sId = OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat));
856 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_LOWERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, nFormat % SAL_N_ELEMENTS(FMT_REF_ARY)));
857 nFormat = FMT_REF_NUMBER_FULL_CONTEXT_IDX + SAL_N_ELEMENTS(FMT_REF_ARY);
858 sId = OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat));
859 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_LOWERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, nFormat % SAL_N_ELEMENTS(FMT_REF_ARY)));
860 nExtraSize += 3;
861 }
862 // uppercase article
863 for (sal_uInt16 i = 0; i < nSize; i++)
864 {
865 OUString sId(OUString::number(GetFieldMgr().GetFormatId( nFieldType, i + 2 * SAL_N_ELEMENTS(FMT_REF_ARY))));
866 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_UPPERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, i ));
867 }
868 nExtraSize += nSize;
869 if ( bAddCrossRefFormats )
870 {
871 sal_uInt16 nFormat = FMT_REF_NUMBER_IDX + 2 * SAL_N_ELEMENTS(FMT_REF_ARY);
872 OUString sId(OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat)));
873 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_UPPERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, nFormat % SAL_N_ELEMENTS(FMT_REF_ARY)));
874 nFormat = FMT_REF_NUMBER_NO_CONTEXT_IDX + 2 * SAL_N_ELEMENTS(FMT_REF_ARY);
875 sId = OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat));
876 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_UPPERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, nFormat % SAL_N_ELEMENTS(FMT_REF_ARY)));
877 nFormat = FMT_REF_NUMBER_FULL_CONTEXT_IDX + 2 * SAL_N_ELEMENTS(FMT_REF_ARY);
878 sId = OUString::number(GetFieldMgr().GetFormatId(nFieldType, nFormat));
879 m_xFormatLB->append(sId, SwResId(FMT_REF_WITH_UPPERCASE_HU_ARTICLE) + GetFieldMgr().GetFormatStr( nFieldType, nFormat % SAL_N_ELEMENTS(FMT_REF_ARY)));
880 nExtraSize += 3;
881 }
882 }
883
884 nSize += nExtraSize;
885
886 // select a certain entry
887 if (nSize)
888 {
889 if (!IsFieldEdit())
890 m_xFormatLB->select_text(sOldSel);
891 else
892 m_xFormatLB->select_text(SwResId(FMT_REF_ARY[GetCurField()->GetFormat() % SAL_N_ELEMENTS(FMT_REF_ARY)]));
893
894 if (m_xFormatLB->get_selected_index() == -1)
895 {
896 if (nFieldDlgFormatSel < m_xFormatLB->n_children())
898 else
899 m_xFormatLB->select(0);
900 }
901 }
902
903 return nSize;
904 }
905
906 // Modify
908 {
909 OUString aName(m_xNameED->get_text());
910 const bool bEmptyName = aName.isEmpty();
911
912 bool bEnable = true;
913 sal_uInt16 nTypeId = m_xTypeLB->get_id(GetTypeSel()).toUInt32();
914
915 if ((nTypeId == static_cast<sal_uInt16>(SwFieldTypesEnum::SetRef) && !GetFieldMgr().CanInsertRefMark(aName)) ||
916 (bEmptyName && (nTypeId == static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef) || nTypeId == static_cast<sal_uInt16>(SwFieldTypesEnum::SetRef) ||
917 nTypeId == REFFLDFLAG_BOOKMARK)))
918 bEnable = false;
919
920 EnableInsert(bEnable);
921
922 m_xSelectionLB->select_text(aName);
923 }
924
926 {
927 bool bModified = false;
928 sal_uInt16 nTypeId = m_xTypeLB->get_id(GetTypeSel()).toUInt32();
929
930 sal_uInt16 nSubType = 0;
931 const sal_Int32 nEntryPos = m_xFormatLB->get_selected_index();
932 const sal_uLong nFormat = (nEntryPos == -1)
933 ? 0 : m_xFormatLB->get_id(nEntryPos).toUInt32();
934
935 OUString aVal(m_xValueED->get_text());
936 OUString aName(m_xNameED->get_text());
937
938 switch(nTypeId)
939 {
940 case static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef):
941 nSubType = REF_SETREFATTR;
942 break;
943
944 case static_cast<sal_uInt16>(SwFieldTypesEnum::SetRef):
945 {
947
948 if(!pType) // Only insert when the name doesn't exist yet
949 {
950 m_xSelectionLB->append_text(aName);
951 m_xSelection->set_sensitive(true);
952 }
953 break;
954 }
955 }
956
957 SwGetRefField* pRefField = static_cast<SwGetRefField*>(GetCurField());
958
959 if (REFFLDFLAG & nTypeId)
960 {
961 SwWrtShell *pSh = GetWrtShell();
962 if(!pSh)
963 {
964 pSh = ::GetActiveWrtShell();
965 }
966 if (nTypeId == REFFLDFLAG_BOOKMARK) // text marks!
967 {
968 aName = m_xNameED->get_text();
969 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
970 nSubType = REF_BOOKMARK;
971 }
972 else if (REFFLDFLAG_FOOTNOTE == nTypeId) // footnotes
973 {
975 SeqFieldLstElem aElem( m_xSelectionLB->get_selected_text(), 0 );
976
977 size_t nPos = 0;
978
979 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
980 nSubType = REF_FOOTNOTE;
981 aName.clear();
982
983 if (pSh->GetSeqFootnoteList(aArr) && aArr.SeekEntry(aElem, &nPos))
984 {
985 aVal = OUString::number( aArr[nPos].nSeqNo );
986
987 if (IsFieldEdit() && aArr[nPos].nSeqNo == pRefField->GetSeqNo())
988 bModified = true; // can happen with fields of which the references were deleted
989 }
990 else if (IsFieldEdit())
991 aVal = OUString::number( pRefField->GetSeqNo() );
992 }
993 else if (REFFLDFLAG_ENDNOTE == nTypeId) // endnotes
994 {
996 SeqFieldLstElem aElem( m_xSelectionLB->get_selected_text(), 0 );
997
998 size_t nPos = 0;
999
1000 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
1001 nSubType = REF_ENDNOTE;
1002 aName.clear();
1003
1004 if (pSh->GetSeqFootnoteList(aArr, true) && aArr.SeekEntry(aElem, &nPos))
1005 {
1006 aVal = OUString::number( aArr[nPos].nSeqNo );
1007
1008 if (IsFieldEdit() && aArr[nPos].nSeqNo == pRefField->GetSeqNo())
1009 bModified = true; // can happen with fields of which the reference was deleted
1010 }
1011 else if (IsFieldEdit())
1012 aVal = OUString::number( pRefField->GetSeqNo() );
1013 }
1014 // #i83479#
1015 else if ( nTypeId == REFFLDFLAG_HEADING )
1016 {
1017 int nEntry = m_xSelectionToolTipLB->get_selected_index();
1018 OSL_ENSURE( nEntry != -1,
1019 "<SwFieldRefPage::FillItemSet(..)> - no entry selected in selection tool tip listbox!" );
1020 if (nEntry != -1)
1021 {
1022 const size_t nOutlIdx(m_xSelectionToolTipLB->get_id(nEntry).toUInt32());
1024 if ( nOutlIdx < maOutlineNodes.size() )
1025 {
1026 ::sw::mark::IMark const * const pMark = pSh->getIDocumentMarkAccess()->getMarkForTextNode(
1027 *(maOutlineNodes[nOutlIdx]),
1029 aName = pMark->GetName();
1030 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
1031 nSubType = REF_BOOKMARK;
1032 }
1033 }
1034 }
1035 else if ( nTypeId == REFFLDFLAG_NUMITEM )
1036 {
1037 int nEntry = m_xSelectionToolTipLB->get_selected_index();
1038 OSL_ENSURE( nEntry != -1,
1039 "<SwFieldRefPage::FillItemSet(..)> - no entry selected in selection tool tip listbox!" );
1040 if (nEntry != -1)
1041 {
1042 const size_t nNumItemIdx(m_xSelectionToolTipLB->get_id(nEntry).toUInt32());
1044 if ( nNumItemIdx < maNumItems.size() )
1045 {
1046 ::sw::mark::IMark const * const pMark = pSh->getIDocumentMarkAccess()->getMarkForTextNode(
1047 *(maNumItems[nNumItemIdx]->GetTextNode()),
1049 aName = pMark->GetName();
1050 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
1051 nSubType = REF_BOOKMARK;
1052 }
1053 }
1054 }
1055 else // SequenceFields
1056 {
1057 // get fields for Seq-FieldType:
1058 SwSetExpFieldType* pType = static_cast<SwSetExpFieldType*>(pSh->GetFieldType(
1059 nTypeId & ~REFFLDFLAG, SwFieldIds::SetExp ));
1060 if( pType )
1061 {
1063 SeqFieldLstElem aElem( m_xSelectionLB->get_selected_text(), 0 );
1064
1065 size_t nPos = 0;
1066
1067 nTypeId = static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef);
1068 nSubType = REF_SEQUENCEFLD;
1069 aName = pType->GetName();
1070
1071 if (pType->GetSeqFieldList(aArr, pSh->GetLayout())
1072 && aArr.SeekEntry(aElem, &nPos))
1073 {
1074 aVal = OUString::number( aArr[nPos].nSeqNo );
1075
1076 if (IsFieldEdit() && aArr[nPos].nSeqNo == pRefField->GetSeqNo())
1077 bModified = true; // can happen with fields of which the reference was deleted
1078 }
1079 else if (IsFieldEdit())
1080 aVal = OUString::number( pRefField->GetSeqNo() );
1081 }
1082 }
1083 }
1084
1085 if (IsFieldEdit() && nTypeId == static_cast<sal_uInt16>(SwFieldTypesEnum::GetRef))
1086 {
1087 aVal = OUString::number(nSubType) + "|" + aVal;
1088 }
1089
1090 if (!IsFieldEdit() || bModified ||
1091 m_xNameED->get_value_changed_from_saved() ||
1092 m_xValueED->get_value_changed_from_saved() ||
1093 m_xTypeLB->get_value_changed_from_saved() ||
1094 m_xSelectionLB->get_value_changed_from_saved() ||
1095 m_xFormatLB->get_value_changed_from_saved())
1096 {
1097 InsertField( static_cast<SwFieldTypesEnum>(nTypeId), nSubType, aName, aVal, nFormat );
1098 }
1099
1100 ModifyHdl(*m_xNameED); // enable/disable insert if applicable
1101
1102 return false;
1103 }
1104
1105 std::unique_ptr<SfxTabPage> SwFieldRefPage::Create( weld::Container* pPage, weld::DialogController* pController,
1106 const SfxItemSet *const pAttrSet)
1107 {
1108 return std::make_unique<SwFieldRefPage>(pPage, pController, pAttrSet);
1109 }
1110
1112 {
1113 return GRP_REF;
1114 }
1115
1117 {
1118 const sal_Int32 nEntryPos = m_xTypeLB->get_selected_index();
1119 const sal_uInt16 nTypeSel = ( -1 == nEntryPos )
1120 ? USHRT_MAX
1121 : m_xTypeLB->get_id(nEntryPos).toUInt32();
1122 const sal_Int32 nFormatEntryPos = m_xFormatLB->get_selected_index();
1123 const sal_uInt32 nFormatSel = -1 == nFormatEntryPos ? USHRT_MAX : nFormatEntryPos;
1125 OUString::number( nTypeSel ) + ";" +
1126 OUString::number( nFormatSel ));
1127 }
1128
1129 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
SwFieldType * GetFieldType(size_t nField, SwFieldIds nResId=SwFieldIds::Unknown) const
get field types with a ResId, if 0 get all
Definition: edfld.cxx:64
SwFieldType * GetFieldType(SwFieldIds nResId, size_t nField=0) const
Definition: fldmgr.cxx:409
Instances of SwFields and those derived from it occur 0 to n times.
Definition: fldbas.hxx:234
virtual void getNumItems(IDocumentListItems::tSortedNodeNumList &orNodeNumList) const =0
get vector of all list items, which are numbered
sal_uInt16 const nStart
Definition: fldmgr.hxx:63
IMPL_LINK_NOARG(SwFieldRefPage, ModifyHdl_Impl, weld::Entry &, void)
Definition: fldref.cxx:115
IDocumentListItems::tSortedNodeNumList maNumItems
Definition: fldref.hxx:39
virtual const OUString & GetName() const =0
OUString sNumItemText
Definition: fldref.hxx:36
void RestorePos(weld::TreeView &rLst1)
Definition: fldpage.cxx:294
virtual sal_uInt16 GetGroup() override
Definition: fldref.cxx:1111
std::unique_ptr< weld::Entry > m_xValueED
Definition: fldref.hxx:56
void SetUserData(const OUString &rString)
#define REFFLDFLAG_ENDNOTE
Definition: fldref.cxx:44
#define USER_DATA_VERSION
Definition: fldref.cxx:52
const IDocumentOutlineNodes * getIDocumentOutlineNodesAccess() const
Definition: viewsh.cxx:2605
wrapper iterator: wraps iterator of implementation while hiding MarkBase class; only IMark instances ...
sal_uIntPtr sal_uLong
Provides numbered items of a document.
static SW_DLLPUBLIC MarkType GetType(const ::sw::mark::IMark &rMark)
Returns the MarkType used to create the mark.
Definition: docbm.cxx:474
IDocumentOutlineNodes::tSortedOutlineNodeList maOutlineNodes
Definition: fldref.hxx:38
sal_Int64 n
SwWrtShell * GetActiveWrtShell()
Definition: swmodul1.cxx:107
Provides access to the marks of a document.
void SubTypeHdl()
Definition: fldref.cxx:422
void SaveSelectedTextNode()
Definition: fldref.cxx:121
std::unique_ptr< weld::Entry > m_xFilterED
Definition: fldref.hxx:57
bool HasWriterListeners() const
Definition: calbck.hxx:208
#define REFFLDFLAG
Definition: fldref.cxx:41
Used by the UI to modify the document model.
Definition: wrtsh.hxx:90
virtual ~SwFieldRefPage() override
Definition: fldref.cxx:111
static sal_uInt16 nFieldDlgFormatSel
Definition: fldref.cxx:49
SwFieldMgr & GetFieldMgr()
Definition: fldpage.hxx:81
std::unique_ptr< weld::Widget > m_xSelection
Definition: fldref.hxx:48
static SwFieldTypesEnum GetTypeId(sal_uInt16 nPos)
Definition: fldmgr.cxx:520
OUString getLanguage() const
virtual void getOutlineNodes(IDocumentOutlineNodes::tSortedOutlineNodeList &orOutlineNodeList) const =0
bool SeekEntry(const SeqFieldLstElem &rNew, size_t *pPos) const
Definition: expfld.cxx:752
const SwTextNode * mpSavedSelectedTextNode
Definition: fldref.hxx:43
virtual bool FillItemSet(SfxItemSet *rSet) override
Definition: fldref.cxx:925
void SetSelectionSel(sal_Int32 nSet)
Definition: fldpage.hxx:48
const OUString & GetUserData() const
sal_uInt16 GetFormatCount(SwFieldTypesEnum nTypeId, bool bHtmlMode) const
Definition: fldmgr.cxx:670
#define REFFLDFLAG_NUMITEM
Definition: fldref.cxx:47
bool IsFieldDlgHtmlMode() const
Definition: fldpage.hxx:49
const IDocumentMarkAccess * getIDocumentMarkAccess() const
Provides access to the document bookmark interface.
Definition: viewsh.cxx:2582
const char * sName
#define SAL_N_ELEMENTS(arr)
std::unique_ptr< weld::TreeView > m_xSelectionToolTipLB
Definition: fldref.hxx:51
virtual const_iterator_t getBookmarksEnd() const =0
returns a STL-like random access iterator to the end of the sequence of IBookmarks.
bool IsRefToNumItemCrossRefBookmark() const
Definition: reffld.cxx:385
#define REFFLDFLAG_BOOKMARK
Definition: fldref.cxx:42
void SavePos(const weld::TreeView &rLst1)
Definition: fldpage.cxx:284
static bool MatchSubstring(const OUString &list_string, const OUString &substr)
Definition: fldref.cxx:724
int i
SwFieldTypesEnum
List of FieldTypes at UI.
Definition: fldbas.hxx:87
void Init()
Definition: fldpage.cxx:65
const SvxPageUsage aArr[]
size_t GetFieldTypeCount(SwFieldIds nResId=SwFieldIds::Unknown) const
count field types with a ResId, if SwFieldIds::Unknown count all
Definition: edfld.cxx:43
bool IsRefresh() const
Definition: fldpage.hxx:50
bool IsUsed(const SwModify &) const
Query if the paragraph-/character-/frame-/page-style is used.
Definition: edfmt.cxx:139
void InsertField(SwFieldTypesEnum nTypeId, sal_uInt16 nSubType, const OUString &rPar1, const OUString &rPar2, sal_uInt32 nFormatId, sal_Unicode cDelim= ' ', bool bIsAutomaticLanguage=true)
Definition: fldpage.cxx:117
sal_Int32 GetTypeSel() const
Definition: fldpage.hxx:45
virtual void Reset(const SfxItemSet *rSet) override
Definition: fldref.cxx:152
size_t GetSeqFootnoteList(SwSeqFieldList &rList, bool bEndNotes=false)
Give a List of all footnotes and their beginning texts.
Definition: edattr.cxx:454
SwField * GetCurField()
Definition: fldpage.hxx:51
OUString SwResId(const char *pId)
Definition: swmodule.cxx:178
OUString lowercase(const OUString &rStr, sal_Int32 nPos, sal_Int32 nCount) const
void UpdateSubType(const OUString &filterString)
Definition: fldref.cxx:466
OUString sFootnoteText
Definition: fldref.hxx:32
#define FIELD_COLUMN_WIDTH
Definition: fldpage.hxx:25
sal_uInt16 const nEnd
Definition: fldmgr.hxx:64
virtual OUString GetName() const override
Only in derived classes.
Definition: expfld.cxx:527
FMT_REF_IDX
Definition: fldref.cxx:735
OUString sBookmarkText
Definition: fldref.hxx:31
const LanguageTag & GetRealLanguageTag() const
OUString sHeadingText
Definition: fldref.hxx:35
SwWrtShell * GetWrtShell()
Definition: fldpage.hxx:52
const SwGetSetExpType GSE_SEQ
Sequence.
Definition: fldbas.hxx:198
sal_uInt16 GetSeqNo() const
Get/set SequenceNo (of interest only for REF_SEQUENCEFLD).
Definition: reffld.hxx:132
virtual ::sw::mark::IMark * getMarkForTextNode(const SwTextNode &rTextNode, MarkType eMark)=0
Returns a mark in the document for a paragraph.
bool IsRefToHeadingCrossRefBookmark() const
Definition: reffld.cxx:379
const IDocumentListItems * getIDocumentListItemsAccess() const
Definition: viewsh.cxx:2600
bool HasFootnotes(bool bEndNotes=false) const
Definition: edattr.cxx:441
std::unique_ptr< weld::TreeView > m_xFormatLB
Definition: fldref.hxx:53
Provides outline nodes of a document.
const o3tl::enumarray< SvxAdjust, unsigned short > aSvxToUnoAdjust USHRT_MAX
Definition: unosett.cxx:253
OUString GetSelText() const
get selected text of a node at current cursor
Definition: crsrsh.cxx:2515
virtual const_iterator_t getBookmarksBegin() const =0
returns a STL-like random access iterator to the begin of the sequence the IBookmarks.
OUString aName
OString strip(const OString &rIn, char c)
virtual void FillUserData() override
Definition: fldref.cxx:1116
const OUString & GetSetRefName() const
Definition: reffld.hxx:107
std::unique_ptr< weld::TreeView > m_xTypeLB
Definition: fldref.hxx:47
static const char * FMT_REF_ARY[]
Definition: fldref.cxx:752
static OUString GetTypeStr(sal_uInt16 nPos)
Definition: fldmgr.cxx:526
OUString sId
bool IsFieldEdit() const
Definition: fldpage.hxx:62
#define REFFLDFLAG_HEADING
Definition: fldref.cxx:46
static std::unique_ptr< SfxTabPage > Create(weld::Container *pPage, weld::DialogController *pController, const SfxItemSet *rAttrSet)
Definition: fldref.cxx:1105
sal_uInt16 GetType() const
Definition: expfld.hxx:193
static const SwFieldGroupRgn & GetGroupRange(bool bHtmlMode, sal_uInt16 nGrpId)
Definition: fldmgr.cxx:464
sal_Int32 FillFormatLB(sal_uInt16 nTypeId)
Definition: fldref.cxx:767
SwRootFrame * GetLayout() const
Definition: viewsh.cxx:2062
CharClass & GetAppCharClass()
Definition: init.cxx:709
OUString sEndnoteText
Definition: fldref.hxx:33
size_t mnSavedSelectedPos
Definition: fldref.hxx:45
#define REFFLDFLAG_FOOTNOTE
Definition: fldref.cxx:43
std::unique_ptr< weld::TreeView > m_xSelectionLB
Definition: fldref.hxx:49
const SwTextNode * GetReferencedTextNode() const
Definition: reffld.cxx:391
void SetTypeSel(sal_Int32 nSet)
Definition: fldpage.hxx:46
sal_uInt16 nPos
size_t GetSeqFieldList(SwSeqFieldList &rList, SwRootFrame const *pLayout)
Definition: expfld.cxx:618
void GetSubTypes(SwFieldTypesEnum nId, std::vector< OUString > &rToFill)
Definition: fldmgr.cxx:567
SwFieldRefPage(weld::Container *pPage, weld::DialogController *pController, const SfxItemSet *pSet)
Definition: fldref.cxx:54
std::unique_ptr< weld::Entry > m_xNameED
Definition: fldref.hxx:55
#define USER_DATA_VERSION_1
Definition: fldref.cxx:51 | __label__pos | 0.964704 |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 9