content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
Skip to content
Permalink
Browse files
Issue detection bug fixed: build TS problem fixed
• Loading branch information
dspavlov committed Jul 1, 2019
1 parent 9801cc6 commit 5573467d04eedbe9f79dd2b19e9675b76af78985
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 46 deletions.
@@ -17,6 +17,8 @@
package org.apache.ignite.ci.issue;
import com.google.common.base.MoreObjects;
public class ChangeUi {
public final String username;
public final String webUrl;
@@ -41,4 +43,12 @@ public String toSlackMarkup() {
public String toPlainText() {
return username + " " + webUrl;
}
/** {@inheritDoc} */
@Override public String toString() {
return MoreObjects.toStringHelper(this)
.add("username", username)
.add("webUrl", webUrl)
.toString();
}
}
@@ -57,7 +57,7 @@ public class Issue {
@Nullable
public String displayName;
/** Build start timestamp. */
/** Build start timestamp. Builds which is older that 10 days not notified. */
@Nullable public Long buildStartTs;
/** Detected timestamp. */
@@ -66,11 +66,13 @@ public class Issue {
/** Set of build tags detected. */
public Set<String> buildTags = new TreeSet<>();
public Issue(IssueKey issueKey, IssueType type) {
public Issue(IssueKey issueKey, IssueType type,
@Nullable Long buildStartTs) {
this.issueKey = issueKey;
this.detectedTs = System.currentTimeMillis();
this.type = type.code();
this.displayType = type.displayName();
this.buildStartTs = buildStartTs;
}
public void addChange(String username, String webUrl) {
@@ -19,9 +19,9 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
@@ -32,22 +32,25 @@
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.ci.issue.Issue;
import org.apache.ignite.ci.issue.IssueKey;
import org.apache.ignite.ci.issue.IssuesStorage;
import org.apache.ignite.ci.tcbot.user.UserAndSessionsStorage;
import org.apache.ignite.tcservice.model.hist.BuildRef;
import org.apache.ignite.tcservice.model.result.Build;
import org.apache.ignite.ci.teamcity.ignited.BuildRefCompacted;
import org.apache.ignite.tcignited.ITeamcityIgnited;
import org.apache.ignite.tcbot.persistence.IgniteStringCompactor;
import org.apache.ignite.tcignited.buildref.BuildRefDao;
import org.apache.ignite.ci.teamcity.ignited.fatbuild.FatBuildCompacted;
import org.apache.ignite.tcignited.build.FatBuildDao;
import org.apache.ignite.tcignited.history.RunHistCompactedDao;
import org.apache.ignite.ci.user.TcHelperUser;
import org.apache.ignite.tcservice.util.XmlUtil;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.logger.slf4j.Slf4jLogger;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.tcbot.persistence.IgniteStringCompactor;
import org.apache.ignite.tcignited.ITeamcityIgnited;
import org.apache.ignite.tcignited.build.FatBuildDao;
import org.apache.ignite.tcignited.buildref.BuildRefDao;
import org.apache.ignite.tcignited.history.RunHistCompactedDao;
import org.apache.ignite.tcservice.model.hist.BuildRef;
import org.apache.ignite.tcservice.model.result.Build;
import org.apache.ignite.tcservice.util.XmlUtil;
import org.jetbrains.annotations.NotNull;
import static org.apache.ignite.tcignited.history.RunHistCompactedDao.BUILD_START_TIME_CACHE_NAME;
@@ -64,10 +67,38 @@ public class RemoteClientTmpHelper {
* @param args Args.
*/
public static void main(String[] args) {
// mainDumpFatBuildStartTime(args);
// mainDumpIssues(args);
System.err.println("Please insert option of main");
}
public static void mainDumpIssues(String[] args) {
try (Ignite ignite = tcbotServerConnectedClient()) {
IgniteCache<IssueKey, Issue> bst = ignite.cache(IssuesStorage.BOT_DETECTED_ISSUES);
Iterator<Cache.Entry<IssueKey, Issue>> iter = bst.iterator();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(dumpsDir(),
"Issues.txt")))) {
while (iter.hasNext()) {
Cache.Entry<IssueKey, Issue> next = iter.next();
Issue val = next.getValue();
long ageDays = -1;
if (val != null && val.buildStartTs != null)
ageDays = Duration.ofMillis(System.currentTimeMillis() - val.buildStartTs).toDays();
writer.write(next.getKey() + " " + val + " " +
ageDays + "\n");
}
writer.flush();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
dumpDictionary(ignite);
}
}
public static void mainDumpFatBuildStartTime(String[] args) {
try (Ignite ignite = tcbotServerConnectedClient()) {
@@ -255,18 +286,12 @@ private static void setupDisco(IgniteConfiguration cfg) {
cfg.setDiscoverySpi(spi);
}
public static void mainExport(String[] args) throws IOException {
public static void mainExport(String[] args) {
final Ignite ignite = tcbotServerConnectedClient();
if (dumpDict) {
IgniteCache<String, Object> strings = ignite.cache(IgniteStringCompactor.STRINGS_CACHE);
try (FileWriter writer = new FileWriter("Dictionary.txt")) {
for (Cache.Entry<String, Object> next1 : strings) {
writer.write(next1.getValue().toString()
+ "\n");
}
}
}
if (dumpDict)
dumpDictionary(ignite);
if (false) {
IgniteCache<Long, FatBuildCompacted> cache1 = ignite.cache(FatBuildDao.TEAMCITY_FAT_BUILD_CACHE_NAME);
@@ -283,6 +308,21 @@ public static void mainExport(String[] args) throws IOException {
}
}
public static void dumpDictionary(Ignite ignite) {
IgniteCache<String, Object> strings = ignite.cache(IgniteStringCompactor.STRINGS_CACHE);
try {
try (FileWriter writer = new FileWriter(new File(dumpsDir(), "Dictionary.txt"))) {
for (Cache.Entry<String, Object> next1 : strings) {
writer.write(next1.getValue().toString()
+ "\n");
}
}
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public static Ignite tcbotServerConnectedClient() {
final IgniteConfiguration cfg = new IgniteConfiguration();
@@ -19,28 +19,45 @@
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.ignite.ci.issue.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Provider;
import org.apache.ignite.ci.issue.Issue;
import org.apache.ignite.ci.issue.IssueKey;
import org.apache.ignite.ci.issue.IssueType;
import org.apache.ignite.ci.jobs.CheckQueueJob;
import org.apache.ignite.ci.mail.EmailSender;
import org.apache.ignite.ci.mail.SlackSender;
import org.apache.ignite.tcbot.engine.issue.EventTemplate;
import org.apache.ignite.tcbot.engine.issue.EventTemplates;
import org.apache.ignite.tcbot.engine.tracked.TrackedBranchChainsProcessor;
import org.apache.ignite.ci.tcbot.user.IUserStorage;
import org.apache.ignite.ci.teamcity.ignited.change.ChangeCompacted;
import org.apache.ignite.ci.teamcity.ignited.fatbuild.FatBuildCompacted;
import org.apache.ignite.ci.teamcity.ignited.runhist.InvocationData;
import org.apache.ignite.ci.user.ITcBotUserCreds;
import org.apache.ignite.ci.user.TcHelperUser;
import org.apache.ignite.tcbot.engine.ui.DsChainUi;
import org.apache.ignite.tcbot.engine.ui.DsSuiteUi;
import org.apache.ignite.tcbot.engine.ui.DsTestFailureUi;
import org.apache.ignite.tcbot.engine.ui.DsSummaryUi;
import org.apache.ignite.tcbot.common.interceptor.AutoProfiling;
import org.apache.ignite.tcbot.common.interceptor.MonitoredTask;
import org.apache.ignite.tcbot.engine.conf.INotificationChannel;
import org.apache.ignite.tcbot.engine.conf.ITcBotConfig;
import org.apache.ignite.tcbot.engine.conf.NotificationsConfig;
import org.apache.ignite.tcbot.engine.issue.EventTemplate;
import org.apache.ignite.tcbot.engine.issue.EventTemplates;
import org.apache.ignite.tcbot.engine.tracked.TrackedBranchChainsProcessor;
import org.apache.ignite.tcbot.engine.ui.DsChainUi;
import org.apache.ignite.tcbot.engine.ui.DsSuiteUi;
import org.apache.ignite.tcbot.engine.ui.DsSummaryUi;
import org.apache.ignite.tcbot.engine.ui.DsTestFailureUi;
import org.apache.ignite.tcbot.persistence.IStringCompactor;
import org.apache.ignite.tcignited.ITeamcityIgnited;
import org.apache.ignite.tcignited.ITeamcityIgnitedProvider;
@@ -50,17 +67,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Provider;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.ignite.tcignited.history.RunHistSync.normalizeBranch;
/**
@@ -150,9 +156,17 @@ protected String sendNewNotificationsEx() throws IOException {
long detected = issue.detectedTs == null ? 0 : issue.detectedTs;
long issueAgeMs = System.currentTimeMillis() - detected;
return issueAgeMs <= TimeUnit.HOURS.toMillis(2);
long bound = TimeUnit.HOURS.toMillis(2);
//temporary to issue missed notifications
if (issue.buildStartTs == null)
bound = TimeUnit.DAYS.toMillis(InvocationData.MAX_DAYS) / 2;
return issueAgeMs <= bound;
})
.filter(issue -> {
if (issue.buildStartTs == null)
return true; // exception due to bug in issue detection; field was not filled
long buildStartTs = issue.buildStartTs == null ? 0 : issue.buildStartTs;
long buildAgeMs = System.currentTimeMillis() - buildStartTs;
long maxBuildAgeToNotify = TimeUnit.DAYS.toMillis(InvocationData.MAX_DAYS) / 2;
@@ -337,11 +351,10 @@ private boolean registerSuiteFailIssues(ITeamcityIgnited tcIgnited,
@NotNull
private Issue createIssueForSuite(ITeamcityIgnited tcIgnited, DsSuiteUi suiteFailure, String trackedBranch,
IssueKey issueKey, IssueType issType) {
Issue issue = new Issue(issueKey, issType);
Issue issue = new Issue(issueKey, issType, tcIgnited.getBuildStartTs(issueKey.buildId));
issue.trackedBranchName = trackedBranch;
issue.displayName = suiteFailure.name;
issue.webUrl = suiteFailure.webToHist;
issue.buildStartTs = tcIgnited.getBuildStartTs(issueKey.buildId);
issue.buildTags.addAll(suiteFailure.tags);
@@ -419,7 +432,7 @@ private boolean registerTestFailIssues(ITeamcityIgnited tcIgnited,
if (issuesStorage.containsIssueKey(issueKey))
return false; //duplicate
Issue issue = new Issue(issueKey, type);
Issue issue = new Issue(issueKey, type, tcIgnited.getBuildStartTs(issueKey.buildId));
issue.trackedBranchName = trackedBranch;
issue.displayName = testFailure.testName;
issue.webUrl = testFailure.webUrl;
@@ -28,7 +28,7 @@
public static final String GITHUB_REF = "https://github.com/apache/ignite-teamcity-bot";
/** TC Bot Version. */
public static final String VERSION = "20190626";
public static final String VERSION = "20190701";
/** Java version, where Web App is running. */
public String javaVer;
0 comments on commit 5573467
Please sign in to comment. | __label__pos | 0.943045 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
How to use stored procedure in ADO.NET Entity Framework?
My Table : MyCustomer
Columns:
CustomerID PK int
Name nvarchar(50)
SurName nvarchar(50)
My stored procedure
ALTER procedure [dbo].[proc_MyCustomerAdd]
(@Name nvarchar(50),
@SurName nvarchar(50)
)
as
begin
insert into dbo.MyCustomer([Name], SurName) values(@name,@surname)
end
My C# code
private void btnSave_Click(object sender, EventArgs e)
{
entityContext.MyCustomerAdd(textName.Text.Trim(), textSurName.Text.Trim());
entityContext.SaveChanges();
}
The error:
The data reader is incompatible with the specified 'TestAdonetEntity2Model.MyCustomer'. A member of the type, 'CustomerID', does not have a corresponding column in the data reader with the same name.
Error occured below the last code line (call to ExecuteFunction):
global::System.Data.Objects.ObjectParameter surNameParameter;
if ((surName != null))
{
surNameParameter = new global::System.Data.Objects.ObjectParameter("SurName", surName);
}
else
{
surNameParameter = new global::System.Data.Objects.ObjectParameter("SurName", typeof(string));
}
<b>return base.ExecuteFunction<MyCustomer>("MyCustomerAdd", nameParameter, surNameParameter);</b>
Added is ok. Every added process is ok. But after editing, above error occurs.
share|improve this question
3 Answers 3
I think what you need to do it a function import with the EF tooling and calling the imported function like
DataContext.MyFunctionName(storedProcedureParamer1, storedProcedureParamer2)
How to: Import a Stored Procedure
share|improve this answer
Just a wild guess (I haven't used EF with stored procs): wouldn't the name of the function used in "ExecuteFunction" have to be the same as the stored proc's name??
return base.ExecuteFunction("MyCustomerAdd", nameParameter, surNameParameter);
ALTER procedure [dbo].[proc_MyCustomerAdd]
Can you try to use:
return base.ExecuteFunction("proc_MyCustomerAdd", nameParameter, surNameParameter);
Does that make any difference?
Marc
share|improve this answer
i find solution. Thanks alot. – Penguen Jun 14 '09 at 19:48
You can change sp name in C# " proc_MyCustomerAdd--->MyCustomerAdd" – Penguen Jun 14 '09 at 19:51
Yes, you can change the name of the procedure in C# - but the stored proc is still called "proc_MyCustomerAdd", and when calling base.ExecuteFunction, I understand you have to give it the name of the stored procedure - no matter what your C# function is called.... – marc_s Jun 14 '09 at 20:27
@Penguen if you 'find solution' you should really post it as an answer and accept it for other people to see. – Seph Dec 21 '11 at 6:00
try
{
entityContext.MyCustomerAdd(textName.Text.Trim(), textSurName.Text.Trim())
}
catch (Exception ex)
{
;
}
Added Process runs correctly. On the other hand ; after added process, give Above error.But My solution run correct!!!
share|improve this answer
Just a question..But is there a way to do this without try/catch? – Luke101 Nov 18 '09 at 7:02
Never have an empty catch block. you will never know what's happening with your code. – David Kemp Jul 22 '11 at 15:42
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.686468 |
Adrian Petrescu Adrian Petrescu - 9 months ago 38
Java Question
Why can't you have multiple interfaces in a bounded wildcard generic?
I know there's all sorts of counter-intuitive properties of Java's generic types. Here's one in particular that I don't understand, and which I'm hoping someone can explain to me. When specifying a type parameter for a class or interface, you can bound it so that it must implement multiple interfaces with
public class Foo<T extends InterfaceA & InterfaceB>
. However, if you're instantiating an actual object, this doesn't work anymore.
List<? extends InterfaceA>
is fine, but
List<? extends InterfaceA & InterfaceB>
fails to compile. Consider the following complete snippet:
import java.util.List;
public class Test {
static interface A {
public int getSomething();
}
static interface B {
public int getSomethingElse();
}
static class AandB implements A, B {
public int getSomething() { return 1; }
public int getSomethingElse() { return 2; }
}
// Notice the multiple bounds here. This works.
static class AandBList<T extends A & B> {
List<T> list;
public List<T> getList() { return list; }
}
public static void main(String [] args) {
AandBList<AandB> foo = new AandBList<AandB>(); // This works fine!
foo.getList().add(new AandB());
List<? extends A> bar = new LinkedList<AandB>(); // This is fine too
// This last one fails to compile!
List<? extends A & B> foobar = new LinkedList<AandB>();
}
}
It seems the semantics of
bar
should be well-defined -- I can't think of any loss of type-safety by allowing an intersection of two types rather than just one. I'm sure there's an explanation though. Does anyone know what it is?
Answer Source
Interestingly, interface java.lang.reflect.WildcardType looks like it supports both upper bounds and lower bounds for a wildcard arg; and each can contain multiple bounds
Type[] getUpperBounds();
Type[] getLowerBounds();
This is way beyond what the language allows. There's a hidden comment in the source code
// one or many? Up to language spec; currently only one, but this API
// allows for generalization.
The author of the interface seems to consider that this is an accidental limitation.
The canned answer to your question is, generics is already too complicated as it is; adding more complexity might prove to be the last straw.
To allow a wildcard to have multiple upper bounds, one has to scan through the spec and make sure the entire system still works.
One trouble I know would be in the type inference. The current inference rules simply can't deal with intercection types. There's no rule to reduce a constraint A&B << C. If we reduced it to
A<<C
or
A<<B
any current inference engine has to go through major overhaul to allow such bifurcation. But the real serious problem is, this allows multiple solutions, but there's no justification to prefer one over another.
However, inference is not essential to type safety; we can simply refuse to infer in this case, and ask programmer to explicitly fill in type arguments. Therefore, difficulty in inference is not a strong argument against intercection types. | __label__pos | 0.965544 |
DadsWorksheets.com - Thousands of printable math worksheets for teachers, home schooling or general study!
Math Worksheets
Worksheet News
Number Patterns: Mixed Operation Patterns
Number patterns using both addition and subtraction operations in the same (more complex) pattern.
The number pattern worksheets on this page are similar to the 'two step' pattern worksheets found separately in the addition and subtraction number pattern worksheet pages. Each of the number patterns on these worksheets has a rule that involves alternating steps. A student should work these problems by first computing the difference between each pair of numbers in the sequence part of the problem, and then the corresponding two step rule will be readily apparent. These are more advanced problems that are better suited for 5th grade and 6th grade students. | __label__pos | 0.962136 |
Note the upgraded forum! If you are experiencing issues logging in, you may need to reset your password which should send an email. If the email doesn't arrive, be sure to check your spam folder just in case.
Filter in a simple module using a join in list items.
I've had good success with filters in a simple module as long as the field I am filtering on is in that model's table.
If I am doing a join in my list_items function, I haven't been able to find a way to make a filter drop down using a field from the joined table. Neither of the following have been successful for me.
$filters['foreign_key'] = array(
'label' => 'Category',
'type' => 'select',
'options' => $this->categories_model->options_list(),
'first_option' => 'Show All'
);
$filters['fuel_relationships.foreign_key'] = array(
'label' => 'Category',
'type' => 'select',
'options' => $this->categories_model->options_list(),
'first_option' => 'Show All'
);
If I don't add the table name it tries to do the where clause using the models table, if I do add the field name no error is thrown but it refreshes the page with nothing filtered (all results returned).
Any thoughts?
Comments
• edited 7:47PM
A couple questions:
1. What version of FUEL?
2. Can you output the query by perhaps adding the following item at the end of your model::list_items method and see what the query result is?
$this->debug_query();
Also, more as an FYI and may not be something that pertains to this situation, in 1.0, you can provide a "filter" method on your model to do custom filtering. The method will be automatically passed the models filters and should return an array of filters that you've further processed.
• edited July 2013
Version 1.0
My filters code:
function filters($filters = array()){
$filters['status_id'] = array(
'label' => 'Status',
'type' => 'select',
'options' => $this->status_model->options_list(),
'first_option' => 'Show All'
);
$filters['foreign_key'] = array(
'label' => 'Category',
'type' => 'select',
'options' => $this->categories_model->options_list(),
'first_option' => 'Show All'
);
return $filters;
}
Error message:
Unknown column 'fuel_experiences.foreign_key' in 'where clause'
SELECT fuel_experiences.id, fuel_experiences.title, fuel_experiences.city, fuel_experiences.website, fuel_experiences.created FROM (`fuel_experiences`) LEFT JOIN `fuel_relationships` ON `fuel_relationships`.`candidate_key` = `fuel_experiences`.`id` LEFT JOIN `fuel_experiences_dates` ON `fuel_experiences_dates`.`experience_id` = `fuel_experiences`.`id` WHERE (LOWER(fuel_experiences.foreign_key) LIKE "%43%") GROUP BY `fuel_experiences`.`id`
• edited 7:47PM
And what is the query when you use the key "fuel_relationships.foreign_key" ?
• edited 7:47PM
No errors, but the filter doesn't work, returns everything. The query is below.
SELECT fuel_experiences.id, fuel_experiences.title, fuel_experiences.city, fuel_experiences.website, fuel_experiences.created FROM (`fuel_experiences`) LEFT JOIN `fuel_relationships` ON `fuel_relationships`.`candidate_key` = `fuel_experiences`.`id` LEFT JOIN `fuel_experiences_dates` ON `fuel_experiences_dates`.`experience_id` = `fuel_experiences`.`id` GROUP BY `fuel_experiences`.`id` ORDER BY `slug` asc LIMIT 50
• edited 7:47PM
I think I see the issue. It's because PHP transforms periods to underscores automatically in $_GET.
http://stackoverflow.com/questions/68651/get-php-to-stop-replacing-characters-in-get-or-post-arrays
I've posted an updated that will allow for the use of colons ":" instead of periods to separate.
• edited 7:47PM
Just pulled down the update, works great. Thanks for taking a look at it so quickly.
• edited 7:47PM
The fix actually created a regression bug that would occur when using the blog_comments module. This has been fixed now in the latest FUEL 1.0 commit.
• edited December 2013
I'm having a similar issue and I bet it's because I don't completely understand the list_items function. I wish there were a brief way to explain this. Will do my best...
I have a games_model, players_model, plays_model and a campaigns_model that are all related in various ways. Simply put - 'players' 'play' 'games' that belong to a promotional 'campaign'.
I'm using the players_model to list distinct players and their information in the CMS. I have a filters method as well. Here's a screenshot of the tables mentioned above.
image
My players_model contains the standard list_items method but I have filters that should determine what gets included in the list. There's a signup_date field that has a start and end date filter in an advanced search display and it works like a charm. However, I have another filter for getting only players info that have played a game belonging to a particular campaign. I can't figure out how to get that to work. I'm looking for the $_POST vars in the list_items method and running methods created to create the db->where array accordingly. As I said, the date filters work but not the campaign filter. In fact, it doesn't seem to ever reach the campaign_filtered_results() method. Instead, I get this error...
Error Number: 1054 Unknown column 'players.campaign_id' in 'where clause' SELECT DISTINCT players.id, players.signup_date, players.email, players.status, players.power_play_balance, players.opt_in, players_to_clients.exported FROM (`players_to_clients`, `clients`, `players`) WHERE clients.id = 1 AND players_to_clients.client_id = 1 AND players_to_clients.player_id = players.id AND (players.campaign_id=1) Filename: /Applications/MAMP/htdocs/mpgsweeps/fuel/modules/fuel/models/base_module_model.php Line Number: 291
Notice the query. In campaign_filtered_results() the select line is...
$this->db->select('DISTINCT players.email, players.first_name, players.last_name, players.email, players.status, plays.campaign_id', FALSE);
So, it's looking for campaign_id in the players model rather than the plays model.
What the heck am I doing wrong?
Here's the players model...
class Players_model extends Base_module_model { public $required = array('first_name','last_name', 'email', 'password'); public $filters = array('first_name', 'last_name', 'email'); public $foreign_keys = array('player_id' => 'plays_model'); function __construct() { parent::__construct('players'); //table } function list_items($limit = NULL, $offset = NULL, $col = 'signup_date', $order = 'desc') { $CI =& get_instance(); $user = $CI->fuel_auth->user_data(); if ( $user['super_admin'] == 'no' ) { $this->load->model('clients_model'); $this->load->model('players_to_clients_model'); $this->load->model('plays_model'); $client_id = find_client_id(); if(isset($_POST['campaign_id'])) { $this->filter_join = array('campaign_id' => 'and'); $where = $this->campaign_filtered_results(); } elseif(isset($_POST['signup_date_fromequal'])) { $this->filter_join = array('signup_date_fromequal' => 'and'); $where = $this->date_filtered_results($client_id); } else { $where = $this->client_filtered_results($client_id); } $this->db->where($where, NULL, FALSE); } else { $this->db->select('DISTINCT players.id, players.first_name, players.last_name, players.email, players.status, players.power_play_balance', FALSE); } $data = parent::list_items($limit, $offset, $col, $order); return $data; } function campaign_filtered_results() { $this->db->select('DISTINCT players.email, players.first_name, players.last_name, players.email, players.status, plays.campaign_id', FALSE); $this->db->from('plays'); if(!empty($this->filters['campaign_id'])) { $campaign_id = $this->filters['campaign_id']; $where['plays.campaign_id = '] = $campaign_id; } elseif(isset($_POST['campaign_id'])) { $campaign_id = $_POST['campaign_id']; $where['plays.campaign_id = '] = $campaign_id; } $where = array( 'players.id' => 'plays.player_id', 'plays.campaign_id' => $campaign_id ); return $where; } function client_filtered_results($client_id) { $this->db->select("DISTINCT players.id, players.signup_date, players.email, players.status, players.power_play_balance, players.opt_in, players_to_clients.exported", FALSE); $this->db->from("players_to_clients,clients"); $where = array( 'clients.id' => (int)($client_id), 'players_to_clients.client_id' => (int)($client_id), 'players_to_clients.player_id' => 'players.id' ); return $where; } function date_filtered_results($client_id) { $this->db->select("DISTINCT players.id, players.signup_date, players.email, players.status, players.power_play_balance, players.opt_in, players_to_clients.exported", FALSE); $this->db->from("players_to_clients,clients"); $where = array( 'clients.id' => (int)($client_id), 'players_to_clients.client_id' => (int)($client_id), 'players_to_clients.player_id' => 'players.id' ); if(!empty($this->filters['signup_date_fromequal'])) { $signupfrom = $this->filters['signup_date_fromequal']; $signupto = $this->filters['signup_date_toequal']; $where['signup_date >= '] = "'".$signupfrom."'"; $where['signup_date <= '] = "'".$signupto."'"; } elseif(isset($_POST['signup_date_fromequal'])) { $datefrom = $_POST['signup_date_fromequal']; $dateto = $_POST['signup_date_toequal']; // will be in mm/dd/yyyy format. need to convert $signupfrom = $this->changeto_sqldate($datefrom); $signupto = $this->changeto_sqldate($dateto); $where['signup_date >= '] = "'".$signupfrom."'"; $where['signup_date <= '] = "'".$signupto."'"; } return $where; } // more stuff after this...
Here's the filters method...
function filters(){ $filters['signup_date_fromequal'] = array('type' => 'datetime'); $filters['signup_date_toequal'] = array('type' => 'datetime'); $client_id = find_client_id(); $campaigns = $this->get_campaigns($client_id); if(!empty($campaigns)) { foreach ($campaigns as $campaign) { $options[$campaign['id']] = $campaign['name']; } $filters['campaign_id'] = array('label' => 'Filter by campaign', 'type' => 'select', 'options' => $options, 'first_option' => 'Select campaign...'); } return $filters; }
Thanks!
• edited 7:47PM
What if you use $this->input->get_post('campaign_id'); to look in the $_GET array instead of the $_POST
• edited December 2013
hmm. Ok. I changed the list_items method to:
function list_items($limit = NULL, $offset = NULL, $col = 'signup_date', $order = 'desc') { $CI =& get_instance(); $user = $CI->fuel_auth->user_data(); if ( $user['super_admin'] == 'no' ) { $this->load->model('clients_model'); $this->load->model('players_to_clients_model'); $this->load->model('plays_model'); $client_id = find_client_id(); $campaign_id = $this->input->get_post('campaign_id'); if($campaign_id != null) { // $this->filter_join = array('campaign_id' => 'and'); $where = $this->campaign_filtered_results($campaign_id); } elseif(isset($_POST['signup_date_fromequal'])) { $this->filter_join = array('signup_date_fromequal' => 'and'); $where = $this->date_filtered_results($client_id); } else { // echo "cid: ".$campaign_id; $where = $this->client_filtered_results($client_id); } $this->db->where($where, NULL, FALSE); } else { $this->db->select('DISTINCT players.id, players.first_name, players.last_name, players.email, players.status, players.power_play_balance', FALSE); } $data = parent::list_items($limit, $offset, $col, $order); return $data; }and the campaign_filtered_results method to...
function campaign_filtered_results($campaign_id) { $this->db->select('DISTINCT players.email, players.first_name, players.last_name, players.email, players.status, plays.campaign_id', FALSE); $this->db->from('plays'); $where = array( 'players.id' => 'plays.player_id', 'plays.campaign_id' => (int)($campaign_id) ); return $where; }Now the error is:Error Number: 1054 Unknown column 'plays.campaign_id' in 'field list' SELECT DISTINCT players.email, players.first_name, players.last_name, players.email, players.status, plays.campaign_id FROM (`plays`,`players`) WHERE players.id = plays.player_id AND plays.campaign_id = 1 AND (players.campaign_id=1) Filename: /Applications/MAMP/htdocs/mpgsweeps/fuel/modules/fuel/models/base_module_model.php Line Number: 291
It looks like no matter what, the query gets written with players.campaign_id in it. If the last part of the above query is removed...
AND (players.campaign_id=1)
The query works perfectly. Trying to figure out what's forcing that last part onto the end of the query
• edited 7:47PM
I wonder if the call to the parent is adding that:
$data = parent::list_items($limit, $offset, $col, $order);
• edited 7:47PM
It sure seems to be the case. I just can't figure out where that's happening. If I call it from outside the list_items method, like players_model->list_items() it doesn't do that.
• edited 7:47PM
It's probably being added in the base_module_model::_list_items_query method that is used in the list_items method. This method looks at the model's filters property to create certain where conditions. I'd poke around in that method.
Sign In or Register to comment. | __label__pos | 0.768311 |
Facebook BOT – Auto Like Your Friends Status
0
118
function run_like(){var run = casper_like("ACCESS TOKEN");} // set triger per menit
function casper_like(token){
var t = new Date();
t = t.getTime();
t = t+"";
t = t.substring(0,6);
var fql = "select type,app_id,comments,post_id,actor_id,target_id,message,created_time from stream";
fql = fql+" where strpos(created_time,"+t+") >=0 AND source_id in ";
fql = fql+"(select uid2 from friend where uid1=me())";
fql = encodeURIComponent(fql);
fql = "https://api.facebook.com/method/fql.query?query="+fql+"&limit=50&format=json&access_token=";
if(token&&token!=""){
var me = get_cr_url("https://graph.beta.facebook.com/me?access_token="+token);
if(me&&me.id){
fql = get_cr_url(fql+token);
if(fql&&fql.length!=0){
var hit = 0;
for(x in fql){
if(fql[x].type==46){
var cek_daftar = "https://graph.beta.facebook.com/"+fql[x].post_id+"/likes?limit=100&access_token=";
cek_daftar = get_cr_url(cek_daftar+token);
var can_cr = 1;
if(cek_daftar&&cek_daftar.data&&cek_daftar.data.length!=0){
for(y in cek_daftar.data){
if(cek_daftar.data[y].id==me.id){
can_cr = 0;
break;
}
}
}
if(can_cr==1){
hit = hit+1;
var jempol = "https://graph.beta.facebook.com/"+fql[x].post_id+"/likes?method=post&access_token=";
jempol = get_cr_url(jempol+token);
}
}
}
}
}
}
}
function get_cr_url(almt){
var url_cr = UrlFetchApp.fetch(almt);
var json_cr = Utilities.jsonParse(url_cr.getContentText());
return json_cr;
} | __label__pos | 0.996194 |
W3C home > Mailing lists > Public > [email protected] > September to December 1996
Re: Calculating Age Question
From: Henrik Frystyk Nielsen <[email protected]>
Date: Mon, 25 Nov 1996 22:01:25 -0500
Message-Id: <[email protected]>
To: Paul Hethmon <[email protected]>, HTTP-WG <http-wg%[email protected]>
At 08:46 PM 11/25/96 EST, Paul Hethmon wrote:
>I don't mean to bring this up for discusion, rather clarification.
>In going through the mailing list archives and over draft 07, I
>wanted to be sure I understood the calculations of the Age value
>correctly.
I have included how I implement it libwww 5.0a which is available from
http://www.w3.org/pub/WWW/Library/
The function is part of the HTCache.c module.
Hope this helps,
Henrik
-----------------------------------------------------------------
/*
** Calculate the corrected_initial_age of the object. We use the time
** when this function is called as the response_time as this is when
** we have received the complete response. This may cause a delay if
** the reponse header is very big but should not cause any incorrect
** behavior.
*/
PRIVATE BOOL calculate_time (HTCache * me, HTRequest * request,
HTResponse * response)
{
if (me && request) {
HTParentAnchor * anchor = HTRequest_anchor(request);
time_t date = HTAnchor_date(anchor);
me->response_time = time(NULL);
me->expires = HTAnchor_expires(anchor);
{
time_t apparent_age = HTMAX(0, me->response_time - date);
time_t corrected_received_age = HTMAX(apparent_age,
HTAnchor_age(anchor));
time_t response_delay = me->response_time -
HTRequest_date(request);
me->corrected_initial_age = corrected_received_age +
response_delay;
}
/*
** Estimate an expires time using the max-age and expires time. If we
** don't have an explicit expires time then set it to 10% of the LM
** date. If no LM date is available then use 24 hours.
*/
{
time_t freshness_lifetime = HTResponse_maxAge(response);
if (freshness_lifetime < 0) {
if (me->expires < 0) {
time_t lm = HTAnchor_lastModified(anchor);
if (lm < 0)
freshness_lifetime = 24*3600; /* 24 hours */
else
freshness_lifetime = (date - lm) / 10;
} else
freshness_lifetime = me->expires - date;
}
me->freshness_lifetime = HTMAX(0, freshness_lifetime);
}
if (CACHE_TRACE) {
HTTrace("Cache....... Received Age %d, corrected %d, freshness
lifetime %d\n",
HTAnchor_age(anchor),
me->corrected_initial_age,
me->freshness_lifetime);
}
return YES;
}
return NO;
}
Received on Monday, 25 November 1996 19:06:07 EST
This archive was generated by hypermail pre-2.1.9 : Wednesday, 24 September 2003 06:32:18 EDT | __label__pos | 0.942041 |
Take the 2-minute tour ×
User Experience Stack Exchange is a question and answer site for user experience researchers and experts. It's 100% free, no registration required.
For example, an "Edit" button. In most pages, it is a secondary button ("Submit" may be the primary one). But there can be a case where in "Edit" is primary action for the page.
Is it good practice to make it stand-out on such pages? Or should secondary buttons remain secondary on every page for consistency?
share|improve this question
4 Answers 4
up vote 7 down vote accepted
Choose the buttons to be primary or secondary depending upon the context of the page. Your buttons must align with the objective of the page and the styling,design and placement must be done accordingly to ensure that they help the page achieve its objective. To quote this article about call to actions
Choose contrasting colors and size your call-to-action button accordingly to help set it apart from other visual elements on your pages
If offering two call-to-action choices (such as a Sign Up button and a Free Trial), make the buttons color-coded according to the most important action you want users to take first.
Hence dont get caught up in the aspect of maintaining the design for all similar buttons even though their expected impact on the page might be different.
share|improve this answer
When you want the 'Edit' button to be primary you need a secondary button like 'Cancel' the edit button will act as a Submit button. so in other terms something like 'Save'
So instead of changing the 'Edit' button to primary you should make a new Primary button called something like 'Save edit' or something similar to that.
In my opinion it is better to leave the normal 'Edit' button secondary so you have a better structure in your pages.
share|improve this answer
It depends on how often a particular button (say 'edit') is the primary action on a page. If it is secondary 95% of the time, then it is better to maintain consistency with how people recognise the button and keep it styled as a secondary button even if it is a primary action on a page.
However, if there is more of a balance between when it is the primary and secondary actions, it may be better to style it accordingly.
You have to take into account your app flow in making these decisions, and test it with your users. That is the only way that you will know for sure whether this is confusing for them or not.
share|improve this answer
Context over consistency.
Don’t mistake consistency for uniformity.
share|improve this answer
Could you add a reference to your statement making your answer more credible. As of now this is just opinion... Thank you! – Benny Skogberg Apr 17 '13 at 6:27
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.551436 |
// // NSArray+IGKAdditions.m // Ingredients // // Created by Alex Gordon on 18/06/2010. // Written in 2010 by Fileability. // #import "NSArray+IGKAdditions.h" #import "smartcmp.h" NSComparisonResult IGKInverseComparisonResult(NSComparisonResult result) { if (result == NSOrderedAscending) return NSOrderedDescending; if (result == NSOrderedDescending) return NSOrderedAscending; return NSOrderedSame; } @implementation NSArray (IGKAdditions) - (NSArray *)igk_map:(id (^)(id obj))rule { rule = [rule copy]; NSMutableArray *filteredArray = [[NSMutableArray alloc] initWithCapacity:[self count] + 1]; for (id obj in self) { id image = rule(obj); if (image) [filteredArray addObject:image]; } return filteredArray; } - (NSArray *)igk_filter:(BOOL (^)(id obj))predicate { predicate = [predicate copy]; NSMutableArray *mappedArray = [[NSMutableArray alloc] initWithCapacity:[self count] + 1]; for (id obj in self) { if (obj && predicate(obj)) [mappedArray addObject:obj]; } return mappedArray; } - (id)igk_firstObject { return [self igk_objectAtSoftIndex:0]; } - (id)igk_objectAtSoftIndex:(NSInteger)index { if (index < 0) return [self igk_objectAtSoftIndex:[self count] + index]; if (index >= [self count]) return nil; return [self objectAtIndex:index]; } - (NSArray *)cdr { if ([self count] < 2) return nil; return [self subarrayWithRange:NSMakeRange(1, [self count] - 1)]; } - (NSArray *)smartSort:(NSString *)query { //Note some commonly used information about the query NSString *lowercaseQuery = [query lowercaseString]; NSUInteger queryLength = [query length]; unichar *queryCharacters = malloc(queryLength * sizeof(unichar)); [query getCharacters:queryCharacters range:NSMakeRange(0, queryLength)]; //Find the length of the longest name NSUInteger maximumLength = 1.0; for (id obj in self) { NSString *result = [obj valueForKey:@"name"]; if ([result length] > maximumLength) maximumLength = [result length]; } //Iterate the array and score each item NSMutableArray *scores = [[NSMutableArray alloc] initWithCapacity:[self count] + 1]; for (id obj in self) { NSString *result = [obj valueForKey:@"name"]; NSString *lowercaseResult = [result lowercaseString]; NSUInteger resultLength = [result length]; unichar *resultCharacters = malloc(resultLength * sizeof(unichar)); [result getCharacters:resultCharacters range:NSMakeRange(0, resultLength)]; SmartCmpScore score = smartcmpScore(query, lowercaseQuery, queryCharacters, queryLength, result, lowercaseResult, resultCharacters, resultLength, obj, maximumLength); [scores addObject:[NSArray arrayWithObjects:[NSNumber numberWithDouble:score], obj, nil]]; free(resultCharacters); } //Sort the scores NSArray *sortedScores = [scores sortedArrayUsingComparator:^ NSComparisonResult (id a, id b) { NSComparisonResult comparisonResult = IGKInverseComparisonResult([[a objectAtIndex:0] compare:[b objectAtIndex:0]]); if (comparisonResult == NSOrderedSame) { //If we're really desperate we can compare the lengths of the contents if ([[a objectAtIndex:1] respondsToSelector:@selector(lengthOfContent)]) { return IGKInverseComparisonResult([[[a objectAtIndex:1] lengthOfContent] compare:[[b objectAtIndex:1] lengthOfContent]]); } return [[[a objectAtIndex:1] valueForKey:@"name"] compare:[[b objectAtIndex:1] valueForKey:@"name"]]; } return comparisonResult; }]; //Clean up free(queryCharacters); //Return the sorted objects NSMutableArray *sortedObjects = [[NSMutableArray alloc] initWithCapacity:[self count] + 1]; for (id obj in sortedScores) { [sortedObjects addObject:[obj objectAtIndex:1]]; } return sortedObjects; } @end | __label__pos | 0.99897 |
Ya está disponible el framework MVC para WordPress! Puedes echarle un ojo aquí!
Acordeón con jQuery
jQuery
En este tutorial vamos a ver cómo puedes crear un efecto tipo acordeón con jQuery. En caso de que no sepas lo que es jQuery o si no sabes utilizarlo, consulta primero el tutorial de introducción a jQuery.
Se denomina efecto acordeón al efecto que incluye una serie de cabeceras que abren y cierran una serie de paneles con contenido. Cada cabecera de nuestro acordeón abrirá o colapsará su respectivo panel. Existen dos modalidades, una en la que cuando haces clic en una cabecera simplemente se abre su respectivo panel y otra en la que también se cierran todos los demás. En este ejemplo veremos cómo crear la primera modalidad.
Antes de comenzar, asegúrate de incluir el script jQuery en tu proyecto.
Versión simplificada
Vamos a empezar agregando el siguiente código HTML, en el que agregamos un elemento con la clase .acordeon que incluye varios pares de cabeceras .acordeon-cabecera y paneles de contenido .acordeon-contenido:
<h1>Acordeón</h1>
<div class="acordeon">
<div class="acordeon-cabecera">Cabecera 1</div>
<div class="acordeon-contenido">Lorem ipsum dolor sit amet consectetur adipiscing elit, id nibh nulla enim dis tempor. Eu ultrices interdum vivamus.</div>
<div class="acordeon-cabecera">Cabecera 2</div>
<div class="acordeon-contenido">Ultrices enim potenti hac proin egestas imperdiet placerat luctus sem sapien et sed, ante conubia malesuada.</div>
<div class="acordeon-cabecera">Cabecera 3</div>
<div class="acordeon-contenido">Dis tempor blandit convallis morbi dictumst tempus non fermentum, ligula suscipit curabitur tellus at dignissim orci.</div>
</div>
Seguidamente, vamos a agregar el código JavaScript que hará que el acordeón funcione. Lo único que hacemos es ejecutar una función cuando se haga clic en alguna cebecera. En dicha función agregamos o eliminamos la clase .active de la cabecera mediante el método toggleClass("active"). de esta forma podemos aplicar ciertos estilos a las cebeceras que se encuentren activas.
Luego seleccionamos el siguiente elemento, que será el contenido de cada panel, mediante el método next() y mostramos y ocultamos el panel mediante el método slideToggle():
$(".acordeon").on("click", ".acordeon-cabecera", function() {
$(this).toggleClass("active").next().slideToggle();
});
Vamos a agregar también algunos estilos CSS muy básicos:
.acordeon-cabecera {
cursor: pointer;
}
.acordeon-contenido {
display: none;
}
.acordeon {
font-weight: 800;
}
Y con esto ya estaría listo. Puedes ver el resultado en funcionamiento aquí.
Versión avanzada
Vamos a mejorar algo el aspecto de nuestro acordeón. Para ello bastará con que agreguemos algunos estilos CSS:
html {
min-height: 100%;
font-family: 'Nunito', sans-serif;
}
body {
background: #7db4fc;
line-height: 1.5;
}
h1 {
font-weight: 200;
font-size: 3rem;
color: white;
text-align: center;
}
.acordeon {
max-width: 400px;
background: white;
margin: 0 auto;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}
.acordeon-cabecera {
border-bottom: 1px solid #DDE0E7;
color: #222222;
cursor: pointer;
font-weight: 600;
padding: 1.5rem;
background:#f6f7f9;
}
.acordeon-cabecera:hover {
background: #fdf8d7;
}
.acordeon-cabecera.active {
background-color: #fdf8d7;
}
.acordeon-contenido {
display: none;
border-bottom: 1px solid #DDE0E7;
background: #fff;
padding: 1.4rem;
color: #4a5666;
}
Y con esto ya estaría listo. Puedes ver el resultado en funcionamiento aquí.
Avatar de Edu Lazaro
Edu Lázaro: Ingeniero técnico en informática, actualmente trabajo como desarrollador web y programador de videojuegos.
👋 Hola! Soy Edu, me encanta crear cosas y he redactado esta guía. Si te ha resultado útil, el mayor favor que me podrías hacer es el de compatirla en Twitter 😊
Si quieres conocer mis proyectos, sígueme en Twitter.
1 comentario en “Acordeón con jQuery
1. Hola! Tengo una duda. ¿Se pueden crear dos paneles de acordeones en una misma página web solo realizando uno, duplicarlo y cambiarle la información? ¿O hay que cambiar algunos datos para que funcione? He hecho esto, y el segundo panel de acordeones funciona, pero el primero no. Espero su respuesta. Muchas gracias.
Deja una respuesta
Tu dirección de correo electrónico no será publicada. | __label__pos | 0.681606 |
HomeSearch
C# Seek File Examples: ReadBytes
This C# article demonstrates the Seek method on streams. It requires System.IO.
Seek
locates a position in a file. It allows data to be read from a binary file at a certain part. For example, we can read 20,000 bytes from any part of a file. This is useful for certain file formats—particularly binary ones.
Example.
To begin our tutorial, we use the Seek method. From databases, you know that Seek is the term for when the data can be instantly retrieved, with an index. Therefore, Seek should be fast.
Here: This example gets the 50000th byte to the 51999th byte and iterates through them.
Note: The BinaryReader class is used. The program opens the binary file with BinaryReader here. It uses the "perls.bin" file.
File.Open
C# program that seeks in Main method using System; using System.IO; class Program { static void Main() { // 1. // Open as binary file. using (BinaryReader b = new BinaryReader(File.Open("perls.bin", FileMode.Open))) { // 2. // Important variables: int length = (int)b.BaseStream.Length; int pos = 50000; int required = 2000; int count = 0; // 3. // Seek the required index. b.BaseStream.Seek(pos, SeekOrigin.Begin); // 4. // Slow loop through the bytes. while (pos < length && count < required) { byte y = b.ReadByte(); // 5. // Increment the variables. pos++; count++; } } } }
Variables used in program.
Length is the entire length of the file we are reading from. Pos is the index we want to start reading from. Required is the number of bytes we want to read. Count is the number of bytes we have read.
Seek: We call Seek on the BaseStream and move the position to 50000 bytes. It looks through each byte.
The above code
can slow down IO. It apparently requires each byte to be read separately off the disk. By using arrays, we can improve performance by several times. Next, we look at the version that uses arrays.
Example 2.
We next use the Seek method with arrays of bytes. There are two useful methods you can call to read in an array of bytes. They are Read and ReadBytes. We see ReadBytes, but if you need to reuse your buffer, use Read.
C# program that uses Seek and ReadBytes using System; using System.IO; class Program { static void Main() { // 1. // Open file with a BinaryReader. using (BinaryReader b = new BinaryReader(File.Open("perls.bin", FileMode.Open))) { // 2. // Variables for our position. int pos = 50000; int required = 2000; // 3. // Seek to our required position. b.BaseStream.Seek(pos, SeekOrigin.Begin); // 4. // Read the next 2000 bytes. byte[] by = b.ReadBytes(required); } } }
The example
opens the same binary file. We start at the same index in the file as the previous example (the 50000th byte). BinaryReader itself doesn't provide Seek, but you can use BaseStream with no damage.
And: It calls ReadBytes. This reads in the 2000 required bytes. These are stored in the byte array.
Note: If there aren't enough bytes left, the ReadBytes method does not throw exceptions.
Reusing buffers.
The above code could be changed so you can provide your own buffer. This could cut down on memory usage and memory pressure in some situations. In a performance-sensitive application, this makes sense.
Discussion.
Here we look at two Read methods available on the BinaryReader class. They both will store the result in an array but with the Read method you can provide your own buffer, which can reduce memory usage in some scenarios.
BinaryReader.ReadBytes: Reads count bytes from the current stream into a byte array and advances the current position by count bytes.
ReadBytes: Microsoft Docs
BinaryReader.Read: Reads count bytes from the stream with index as the starting point in the byte array.
Read: Microsoft Docs
Benchmarks.
Here we compare the performance benchmarks of the first example shown in this article (which uses single byte reads) and the second example in this article (which uses arrays). The array example is much faster.
Note: This may occur because Windows doesn't buffer the single byte reads well. Also, there are different layers of code here.
Benchmark notes for Seek Bytes read: 20000 File size: 2.94 MB Start position: Inclusive random number Compilation: Release Iterations: 10000 Seek benchmark results Read one byte: 2574 ms Read array: 671 ms
Summary.
We used the Seek method on the BinaryReader and FileStream classes. The article showed the performance of using seeking with BinaryReader and FileStream. Using the array read method is far faster than using single bytes.
Finally: In my test with a three megabyte file, the amount of time executing the Seek wasn't significant.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, [email protected]. | __label__pos | 0.849599 |
desnav.com
Antivirus vs. Antimalware: What’s the Ideal for Cyber Attack Protection?
The Internet used to be a place where people can safely accomplish different tasks without fearing anything. This completely changed when some people started to put their noses in other people’s business. With this, viruses and malware attacks are prevalent.
You should know that cybercriminals are skilled and organized not to mention persistent. They use new tactics to exploit the flaws of PCs. More than ever you need security software programs to keep your devices and your information secure. When looking for security software programs, you will come across two things – antivirus and antimalware. These things can be confusing.
You must know the differences so you can identify what is ideal for cyber-attack protection. To help you get started, here’s what you should know about antivirus and antimalware:
What is antivirus software and how does it work?
Before anything, you should understand the nature of the virus. A computer virus is a software that can replicate. It is designed to harm computers as well as information systems. You should understand that it can spread through the Internet either from malicious downloads or infected files and email attachments.
As the name suggests, antivirus software is designed to protect against viruses. With the proliferation of malware, antivirus software started to protect against classic malware like Trojans, keyloggers, backdoors, rootkits, botnets and many more.
Some of the features to look for in antivirus software programs include the following:
• The virus scanning should be done in the background.
• Blocking malicious script files then preventing them from running.
• Heuristic analysis that can identify new variants of viruses and previously known computer viruses.
• Malware removal can get rid of classic malware.
desnav.comWhat is antimalware software and how does it work?
Malware, on the other hand, comes with malicious intent. It can be in the form of adware, Trojans, worms, ransomware, virus, and many more. Experts are saying that a virus is considered malware but malware is not a virus.
Antimalware covers greater protection from anti-spyware to anti-spam or phishing. Some of the features to look for in antimalware software programs include the following:
• Removal of known malware like adware, spyware, Trojans, and advanced malware.
• It offers second malware protection.
• Software updates that can identify new threats.
• Traffic filtering that can secure your device by blocking access to infected servers.
• It provides online banking security.
• It features anti-phishing protection that can detect and block scam.
• It provides a malware distribution.
• It protects against sites that are involved in the distribution of malware.
Final words
While antivirus can keep cybercriminals out of your PC and other devices, it just provides limited protection from advanced malware attacks. With this, you should also consider antimalware software programs.
There are many resources like desnav.com to help you choose the right suite but keep in mind that antimalware can give your antivirus a boost thereby enhancing the protection of your devices. At the end of the day, you should consider both security software programs to maximize your security. | __label__pos | 0.666779 |
ASP.NET MVC: LessThan and GreaterThan Validation Attributes
ASP.NET MVC ships with a handy Compare attribute that allows you to compare two inputs and display a validation message if they do not match. This is great for sign up pages where a password needs to be entered twice and we need to ensure that they are equal but aside from that, I haven’t found any other use for the Compare attribute. What I have found that I have needed more are LessThan and GreaterThan attributes that allow you to compare two inputs and ensure that one is less than or greater than the other. The ASP.NET MVC Framework doesn’t not come loaded with such attributes so using the Compare attribute as a template, I have created them.
You can download a project here that has the complete source code and test pages for these attributes.
We will start first with the validation attribute:
public class NumericLessThanAttribute : ValidationAttribute, IClientValidatable
{
private const string lessThanErrorMessage = "{0} must be less than {1}.";
private const string lessThanOrEqualToErrorMessage = "{0} must be less than or equal to {1}.";
public string OtherProperty { get; private set; }
private bool allowEquality;
public bool AllowEquality
{
get { return this.allowEquality; }
set
{
this.allowEquality = value;
// Set the error message based on whether or not
// equality is allowed
this.ErrorMessage = (value ? lessThanOrEqualToErrorMessage : lessThanErrorMessage);
}
}
public NumericLessThanAttribute(string otherProperty)
: base(lessThanErrorMessage)
{
if (otherProperty == null) { throw new ArgumentNullException("otherProperty"); }
this.OtherProperty = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, this.OtherProperty);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult(String.Format(CultureInfo.CurrentCulture, "Could not find a property named {0}.", OtherProperty));
}
object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
decimal decValue;
decimal decOtherPropertyValue;
// Check to ensure the validating property is numeric
if (!decimal.TryParse(value.ToString(), out decValue))
{
return new ValidationResult(String.Format(CultureInfo.CurrentCulture, "{0} is not a numeric value.", validationContext.DisplayName));
}
// Check to ensure the other property is numeric
if (!decimal.TryParse(otherPropertyValue.ToString(), out decOtherPropertyValue))
{
return new ValidationResult(String.Format(CultureInfo.CurrentCulture, "{0} is not a numeric value.", OtherProperty));
}
// Check for equality
if (AllowEquality && decValue == decOtherPropertyValue)
{
return null;
}
// Check to see if the value is greater than the other property value
else if (decValue > decOtherPropertyValue)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
public static string FormatPropertyForClientValidation(string property)
{
if (property == null)
{
throw new ArgumentException("Value cannot be null or empty.", "property");
}
return "*." + property;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationNumericLessThanRule(FormatErrorMessage(metadata.DisplayName), FormatPropertyForClientValidation(this.OtherProperty), this.AllowEquality);
}
}
Like the compare attribute, this attribute will compare against another value on the form. The other property name is passed into the attributes constructor. There is also another named parameter, AllowEquality, which allows you to specify whether or not the value being validated can be equal to the ‘other’ property. The IsValid method is pretty straightforward and compares the two values to see if they are valid.
The last method, GetClientValidationRules creates a ModelClientValidationNumericLessThanRule class defined below:
public class ModelClientValidationNumericLessThanRule : ModelClientValidationRule
{
public ModelClientValidationNumericLessThanRule(string errorMessage, object other, bool allowEquality)
{
ErrorMessage = errorMessage;
ValidationType = "numericlessthan";
ValidationParameters["other"] = other;
ValidationParameters["allowequality"] = allowEquality;
}
}
This class specifies the client validation type and parameters that will be loaded into the data attributes of the input on the html page. Here we have specified that the jQuery client validation type has a name of ‘numericlessthan’ and that it will accept to parameters values named ‘other’ and ‘allowEquality’.
Now that we have created these two classes, we can now generate a model to test the validation:
public class NumericLessThanViewModel
{
public decimal MaxValue { get; set; }
[NumericLessThan("MaxValue", AllowEquality = true)]
[Display(Name="Value")]
public decimal Value { get; set; }
}
For this to work we need at least two properties on the model; one that specifies the maximum value and another that will be used for the user input. On the user input property, add the NumericLessThan attribute and specify the name of the ‘other’ property to which it will be compared and whether or not equality is allowed. The ‘other’ value will usually be loaded as a hidden field in the form.
At this point just the server side validation has been setup. We need to add a javascript file as well to enable client side validation.
jQuery.validator.addMethod('numericlessthan', function (value, element, params) {
var otherValue = $(params.element).val();
return isNaN(value) && isNaN(otherValue) || (params.allowequality === 'True' ? parseFloat(value) <= parseFloat(otherValue) : parseFloat(value) < parseFloat(otherValue));
}, '');
jQuery.validator.unobtrusive.adapters.add('numericlessthan', ['other', 'allowequality'], function (options) {
var prefix = options.element.name.substr(0, options.element.name.lastIndexOf('.') + 1),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(':input[name=' + fullOtherName + ']')[0];
options.rules['numericlessthan'] = { allowequality: options.params.allowequality, element: element };
if (options.message) {
options.messages['numericlessthan'] = options.message;
}
});
function appendModelPrefix(value, prefix) {
if (value.indexOf('*.') === 0) {
value = value.replace('*.', prefix);
}
return value;
}
The first method in the code above adds the actual method that is called when validating the input. In it we check to see if both values are numbers and depending on whether or not we specified to allow equality, we check to ensure that the user input is less than or equal to the other value.
The second method adds the rule to the set of jQuery validation adapters and supplies the wiring up of the parameters that will be supplied to the validation method.
And that is it. The ASP.NET MVC framework and the jQuery validation libraries will take care of the rest.
In the downloadable project above I have included a NumericGreaterThan attribute as well but as you can image, the code is almost identical to the LessThan attribute so I will not be going over it here.
ASP.NET MVC: Displaying Client and Server Side Validation Using Error Icons
In a previous post I showed how you could display both client and server side validation using qTip tooltips. In this post I will show how you can display an error icon next to the field that is invalid and then when the user hovers over the icon, display the error message (demonstrated below).
As done previously I will be using the same example project from this post where we created a dialog form which was submitted via Ajax.
You can download the complete solution for this example here.
First, the error icon. I utilized the ui-icon-alert class that comes with jQuery UI to display the error icon. But, to get the icon to display correctly without having to create a containing div element around the icon, we need to add a new class to the jquery.ui.theme.css file. Open up the default jquery.ui.theme.css file or if you have added a custom theme, the jquery-ui-[version number].custom.css file and find the states and images sub section under the Icons section. Add the following css class to the list of classes there.
.ui-state-error-icon { display:inline-block; width: 16px; height: 16px; background-image: url(images/ui-icons_cd0a0a_256x240.png); }
This class will allow a 16 x 16px icon from the error images png to be displayed in an empty element.
Next we need to change the onError function in the jquery.validate.unobtrusive.js javascript file. Open that file and replace the onError function with that shown below.
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
// Do not display the error message
//container.empty();
//error.removeClass("input-validation-error").appendTo(container);
// If the error message is an empty string, remove the classes
// from the container that displays the error icon. Otherwise
// Add the classes necessary to display the error icon and
// wire up the qTip tooltip for the container
if ($(error).text() == "") {
container.removeClass("ui-state-error-icon").removeClass("ui-icon-alert");
}
else {
container.addClass("ui-state-error-icon").addClass("ui-icon-alert");
$(container).qtip({
overwrite: true,
content: $(error).text(),
style: {
classes: 'ui-tooltip-red'
}
});
}
}
else {
error.hide();
}
}
Here instead of displaying the error message in associated container, we are displaying the alert icon and wiring up a qTip tooltip to display the error text. (Make sure in your Layout or MasterPage that you reference the jquery.validate.unobtrusive.js javascript file not the jquery.validate.unobtrusive.min.js file.)
If you run the application now all client side errors will be displayed using little error icons as pictured above and if the user hovers over the icon, the error message will be displayed in the tooltip.
To make server side validation messages appear in the same way we need to add another javascript function to each page. Create a new javascript file named jquer.qtip.validation.js and paste the following code into it.
$(function () {
// Run this function for all validation error messages
$('.field-validation-error').each(function () {
// Get the error text to be displayed
var errorText = $(this).text();
// Remove the text from the error message span
// element and add the classes to display the icon
$(this).empty();
$(this).addClass("ui-state-error-icon").addClass("ui-icon-alert");
// Wire up the tooltip to display the error message
$(this).qtip({
overwrite: true,
content: errorText,
style: {
classes: 'ui-tooltip-red'
}
});
});
});
Here we are doing the same thing we did for client side validation except we are iterating over all elements with the field-validation-error class and removing its text, displaying the icon, and placing the error message in the tooltip. Make sure that on every form where you have server side validation displayed that you reference the jquery.qtip.validation.js javascript file.
There you have it. Client and server side validation displayed using error icons and tooltips.
ASP.NET MVC: Internal Server Error (500) on Action Method Returning Json Result
The ASP.NET MVC framework allows you to easily return Json from an action method. This makes jQuery Ajax calls very easy to implement, as shown below.
The JavaScript
$(.button).getJSON('/Home/GetJsonData',
{ id = 34 },
function(data) {
// Do something with it
}
);
The Action Method
public ActionResult GetJsonData(int id)
{
Person person = this.personService.GetPerson(id);
return Json(person);
}
There is only one problem with the above action method. If you attempt to run it, the call to the ActionMethod will result in a Internal Server Error (Error 500). The reason is that by default data can only be retrieved using a POST operation if your action method returns a Json result. To make this work with a GET request, all you need to use is the overloaded Json() method shown below.
public ActionResult GetJsonData(int id)
{
Person person = this.personService.GetPerson(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
ASP.NET MVC: Displaying Client and Server Side Validation Using qTip Tooltips
The ASP.NET MVC framework makes it very easy to do both client and server side validation out of the box. Using DataAnnotations on your model properties the framework can display errors to the user client side using jQuery validation or for more complex situations, model errors can be returned using server side validation. Here is an example of a model and corresponding error messages that are displayed to the user on offending fields.
With the [Required] DataAnnotation on the NickName property we get the error message “The Nick name field is required” if the user leaves it blank. Also, the framework realizes that the Age property is an integer and thus if the user enters a value other than a numeric value, it will display and error message.
The functionality is great but the way in which the error messages are displayed is not very aesthetically pleasing. Also, when fields are validated on the client side, if you haven’t built in spaces for the validation text, your form will jump all over the place to make room for the messages. In an effort to make things a little more pleasing to the eye and to avoid unnecessary form re-sizing I’m going to show how you can display both client and server side validation in tooltips using the jQuery plugin qTip. Our goal is to transfer the form displayed above into the following:
You can download the complete solution for this example here.
I will be building off of the example from my last post that showed how to use jQuery UI to build Ajax forms.
The first thing you need to do is download the qTip library, add them to your project, and add references to the jquery.qtip.min.js script and jquery.qtip.css style sheet in your _Layout.cshtml or MasterPage.aspx.
The displaying of client side validation errors is handled in the jquery.validate.unobtrusive.js onError method. We need to alter that method to display the tooltip with the validation message instead of showing the default label. I cannot take credit for figuring out this code. I actually am using the technique presented here with a minor tweak. Open up the jquery.validate.unobtrusive.js script and replace the onError method with the following:
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + inputElement[0].name + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
// Remove the following line so the default validation messages are not displayed
// container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
/**** Added code to display the error message in a qTip tooltip ****/
// Set positioning based on the elements position in the form
var elem = $(inputElement),
corners = ['left center', 'right center'],
flipIt = elem.parents('span.right').length > 0;
// Check we have a valid error message
if (!error.is(':empty')) {
// Apply the tooltip only if it isn't valid
elem.filter(':not(.valid)').qtip({
overwrite: false,
content: error,
position: {
my: corners[flipIt ? 0 : 1],
at: corners[flipIt ? 1 : 0],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-red' // Make it red... the classic error colour!
}
})
// If we have a tooltip on this element already, just update its content
.qtip('option', 'content.text', error);
}
// If the error is empty, remove the qTip
else { elem.qtip('destroy'); }
}
Take a look at the qTip documentation for more information on what each of the options are doing here.
Your site is probably referencing the jquery.validate.unobtrusive.min.js file so make sure you replace that reference with the non-minified version you just updated.
Next, we need to update the DialogForm.js script file we created to do two things when the dialog window is closed; remove all the qTip tooltips and remove the form from the page after it is submitted. It turns out that when closing a jQuery UI dialog window, the constructed elements are not actually removed from the page but rather just hidden. After a successful ajax post and reload of the form, there will be issues rendering the server side validation messages if we don’t remove the submitted form. That is why the form has to be removed when the dialog is closed.
To make these changes, open the DialogForm.js file and add the close function to the dialog generation function.
$(function () {
// Wire up the click event of any dialog links
$('.dialogLink').live('click', function () {
var element = $(this);
// Retrieve values from the HTML5 data attributes of the link
var dialogTitle = element.attr('data-dialog-title');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url');
// Generate a unique id for the dialog div
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
// Load the form into the dialog div
$(dialogDiv).load(this.href, function () {
$(this).dialog({
modal: true,
resizable: false,
title: dialogTitle,
buttons: {
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function () {
$(this).dialog('close');
}
},
// **** START NEW CODE ****
close: function () {
// Remove all qTip tooltips
$('.qtip').remove();
// It turns out that closing a jQuery UI dialog
// does not actually remove the element from the
// page but just hides it. For the server side
// validation tooltips to show up you need to
// remove the original form the page
$('#' + dialogId).remove();
}
// **** END NEW CODE ****
});
// Enable client side validation
$.validator.unobtrusive.parse(this);
// Setup the ajax submit logic
wireUpForm(this, updateTargetId, updateUrl);
});
return false;
});
});
If we run the application at this point then the client side validation messages will be displayed in the qTip tooltips. Now, to display the server side validation messages in qTip tooltips as well.
To demonstrate how to do this I am going to create a custom validation attribute named AgeValidation and add it to our Profile model. This validation can actually be done client side but I want to show how to show the tooltips after a server side validation error, so humor me.
public class Profile
{
[Required]
public string Name { get; set; }
[Required]
[StringLength(10, MinimumLength=3)]
[Display(Name="Nick name")]
public string NickName { get; set; }
[Required]
public string Email { get; set; }
[Required]
[AgeValidation(ErrorMessage="You must be older than 12 to sign up")]
public int Age { get; set; }
}
// I know this can be accomplished using the Range validation
// attribute but I have implmented it as a custom validation
// attribute to show how server side validation error messages
// can be displayed using qTip tooltips
public class AgeValidation : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return false;
int intValue;
if (!int.TryParse(value.ToString(), out intValue))
return false;
return (intValue > 12);
}
}
Now if the user attempts to submit a Profile model with an age less than 12, a server side validation error message will be added. The trick to displaying the server side validation errors in qTip tooltips is to know how ASP.NET MVC renders the default label with the error message. It turns out that when a validation error message is displayed, ASP.NET MVC creates a span element with the class ‘field-validation-error’ and its contents contain the error message. So, in order to display that message in a tooltip, all we need to do is extract that error message from the span element and load it into a tootip. This can be accomplished by the following javascript function:
$(function () {
// Run this function for all validation error messages
$('.field-validation-error').each(function () {
// Get the name of the element the error message is intended for
// Note: ASP.NET MVC replaces the '[', ']', and '.' characters with an
// underscore but the data-valmsg-for value will have the original characters
var inputElem = '#' + $(this).attr('data-valmsg-for').replace('.', '_').replace('[', '_').replace(']', '_');
var corners = ['left center', 'right center'];
var flipIt = $(inputElem).parents('span.right').length > 0;
// Hide the default validation error
$(this).hide();
// Show the validation error using qTip
$(inputElem).filter(':not(.valid)').qtip({
content: { text: $(this).text() }, // Set the content to be the error message
position: {
my: corners[flipIt ? 0 : 1],
at: corners[flipIt ? 1 : 0],
viewport: $(window)
},
show: { ready: true },
hide: false,
style: { classes: 'ui-tooltip-red' }
});
});
});
And lastly, we need to add a reference to the above script on the page that will display the form fields for the Profile model.
@model DialogFormExample.Models.Profile
@using (Html.BeginForm()) {
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)<br />
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.NickName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.NickName) <br />
@Html.ValidationMessageFor(model => model.NickName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email) <br />
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age) <br />
@Html.ValidationMessageFor(model => model.Age)
</div>
}
<script src="@Url.Content("~/Scripts/jquery.qtip.validation.js")" type="text/javascript" />
And that’s it. Now you have a form that will display both server and client side validation in qTip tooltips!
ASP.NET MVC: Client Side Validation with an Ajax Loaded Form
In my last post I discussed how to perform some CRUD operations using Ajax and the jQuery UI dialog window. In that posted I included a little gem which I did not point out and probably should have.
The ASP.NET MVC framework provides client side validation using the jQuery validation library. It is a great tool for the user as they receive immediate notification when they have entered an invalid value but it is also great for the developer as you reduce unnecessary load on the server. The problem is all the client side validation logic is setup when the page is loaded so if you load a form using Ajax after the original page has been loaded, client side validation will not work for that form.
In order to remedy this all you need to do is make a manual call to the jQuery validation scripts passing in a selector that will include the form you load. Here is the line that needs to be included:
// Enable client side validation
$.validator.unobtrusive.parse('form');
Above I have indicated that I want the jQuery validation library to parse all form elements but if you form has been given an id, you can pass in the id of the form as well. Below is a more complete example from my last post that shows the form being loaded into the dialog window and then the call to the jQuery validation library.
// Load the form into the dialog div
$(dialogId).load(this.href, function () {
$(this).dialog({
modal: true,
resizable: false,
title: dialogTitle,
buttons: {
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function () { $(this).dialog('close'); }
}
});
// Enable client side validation
$.validator.unobtrusive.parse(this);
});
ASP.NET MVC: Ajax Dialog Form Using jQuery UI
In one of my recent projects I needed to display some information, allow the user to edit it utilizing a dialog window, post the updated information and reload it for the user using Ajax. I needed to perform the named operations for multiple models so I set out to create some generic code that could be reused over and over. Below is a picture of what I am trying to accomplish.
The project used for the post below can be downloaded here.
First, the model. For this example, we will use a simple model that contains some profile information for a user.
public class Profile
{
[Required]
public string Name { get; set; }
[Required]
[StringLength(10, MinimumLength=3)]
[Display(Name="Nick name")]
public string NickName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public int Age { get; set; }
}
Second, we need to create three action methods. One will be used to display the profile information, another to display the form for editing the profile, and lastly another that will be used to save the edited profile object. The first two should always return a PartialView as each of these action methods will be called using Ajax and their result will be loaded into div elements; the first into a div used to display the saved profile and the second into the edit dialog. The third action method will return a PartialView if the ModelState is invalid so that the errors can be displayed to the user and a Json result indicating the save was successful if all went well. (Note that in this example I am just storing the profile information in Session but obviously this would be stored in a database or some other data store.)
public ActionResult Profile()
{
Profile profile = new Profile();
// Retrieve the perviously saved Profile
if (Session["Profile"] != null)
profile = Session["Profile"] as Profile;
return PartialView(profile);
}
public ActionResult EditProfile()
{
Profile profile = new Profile();
// Retrieve the perviously saved Profile
if (Session["Profile"] != null)
profile = Session["Profile"] as Profile;
return PartialView(profile);
}
[HttpPost]
public ActionResult EditProfile(Profile profile)
{
// If the ModelState is invalid then return
// a PartialView passing in the Profile object
// with the ModelState errors
if (!ModelState.IsValid)
return PartialView("EditProfile", profile);
// Store the Profile object and return
// a Json result indicating the Profile
// has been saved
Session["Profile"] = profile;
return Json(new { success = true });
}
Next we need to create the two partial views that correspond to the first two action methods we created above. In this example, the partial view for the EditProfile action is pretty much just the stock view created by the MVC frameowork except I have removed the input element to submit the form as we will use the buttons on the jQuery UI dialog to submit it.
The second partial view, the one that displays the saved Profile object again in this example is the stock view with a few added elements.
@using DialogFormExample.MvcHelpers
@model DialogFormExample.Models.Profile
<fieldset>
<legend>Contact Info</legend>
<div class="display-field">
Name: @Html.DisplayFor(model => model.Name)
</div>
<div class="display-field">
Nick name: @Html.DisplayFor(model => model.NickName)
</div>
<div class="display-field">
Email: @Html.DisplayFor(model => model.Email)
</div>
<div class="display-field">
Age: @Html.DisplayFor(model => model.Age)
</div>
<div class="right">
@Html.DialogFormLink("Edit", Url.Action("EditProfile"), "Edit Profile", "ProfileContainer", Url.Action("Profile"))
</div>
</fieldset>
The first portion of the partial view just displays the form elements required for editing the model. This is just the stock Edit view modified only slightly. The new code starts at line 25. Here I created an extension method for HtmlHelper named DialogFormLink that will create an anchor tag loaded with all the needed information to make the dialog form work. Here is the code for the extension method. You can read the comments to get an understanding of the parameters it requires.
/// <summary>
/// Creates a link that will open a jQuery UI dialog form.
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="linkText">The inner text of the anchor element</param>
/// <param name="dialogContentUrl">The url that will return the content to be loaded into the dialog window</param>
/// <param name="dialogTitle">The title to be displayed in the dialog window</param>
/// <param name="updateTargetId">The id of the div that should be updated after the form submission</param>
/// <param name="updateUrl">The url that will return the content to be loaded into the traget div</param>
/// <returns></returns>
public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
string dialogId, string dialogTitle, string updateTargetId, string updateUrl)
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(linkText);
builder.Attributes.Add("href", dialogContentUrl);
builder.Attributes.Add("data-dialog-title", dialogTitle);
builder.Attributes.Add("data-update-target-id", updateTargetId);
builder.Attributes.Add("data-update-url", updateUrl);
// Add a css class named dialogLink that will be
// used to identify the anchor tag and to wire up
// the jQuery functions
builder.AddCssClass("dialogLink");
return new MvcHtmlString(builder.ToString());
}
The above extension method that builds our anchor tag utilizes the HTML5 data attributes to store information such as the title of the dialog window, the url that will return the content of the dialog window, the id of the div to update after the form is submitted, and the url that will update the target div.
Now we need to add the container div to hold the Profile information in the Index view.
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<div id="ProfileContainer">
@{ Html.RenderAction("Profile"); }
</div>
Lastly, I have listed the scripts and css files that need to be linked below in the _Layout page for everything to work correctly.
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/DialogForm.js")" type="text/javascript"></script>
</head>
The last script reference above is to a script I wrote called DialogForm.js. This script (shown below) will make everything work.
$(function () {
// Don't allow browser caching of forms
$.ajaxSetup({ cache: false });
// Wire up the click event of any current or future dialog links
$('.dialogLink').live('click', function () {
var element = $(this);
// Retrieve values from the HTML5 data attributes of the link
var dialogTitle = element.attr('data-dialog-title');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url');
// Generate a unique id for the dialog div
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
// Load the form into the dialog div
$(dialogDiv).load(this.href, function () {
$(this).dialog({
modal: true,
resizable: false,
title: dialogTitle,
buttons: {
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function () { $(this).dialog('close'); }
}
});
// Enable client side validation
$.validator.unobtrusive.parse(this);
// Setup the ajax submit logic
wireUpForm(this, updateTargetId, updateUrl);
});
return false;
});
});
function wireUpForm(dialog, updateTargetId, updateUrl) {
$('form', dialog).submit(function () {
// Do not submit if the form
// does not pass client side validation
if (!$(this).valid())
return false;
// Client side validation passed, submit the form
// using the jQuery.ajax form
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
// Check whether the post was successful
if (result.success) {
// Close the dialog
$(dialog).dialog('close');
// Reload the updated data in the target div
$(updateTargetId).load(updateUrl);
} else {
// Reload the dialog to show model errors
$(dialog).html(result);
// Enable client side validation
$.validator.unobtrusive.parse(dialog);
// Setup the ajax submit logic
wireUpForm(dialog, updateTargetId, updateUrl);
}
}
});
return false;
});
}
Conclusion
I know that was a lot to take in but after you do the setup once, all you need to do is make one call to Html.DialogFormLink and everything will be taken care of for you. Hope this helps!
ASP.NET MVC: Unauthenticated User Always Redirected to ~/Account/LogOn Despite Custom Sign In Url
By default new ASP.NET MVC projects redirect any unauthenticated users who request resources that require authentication to the /Account/LogOn action. The log on page is defined in the web.config authentication section.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
It is my preference for users to “Sign in” instead of “Log on” so I changed the web.config to the following and changed the action method name from LogOn to SignIn.
<authentication mode="Forms">
<forms loginUrl="~/Account/SignIn" timeout="2880" />
</authentication>
After the change I tried accessing a page that required the user to be authorized with and unauthorized user and to my surprise, the site redirected me to /Account/LogOn and I got a 404 error saying the the resource could not be found. It turns out this is a known issue with the ASP.NET MVC when the WebMatrix.Data.dll and WebMatrix.DataWeb.dll are added to the deployable assemblies collection. This issue can be fixed by adding the following key to the appSettings section of the web.config.
<appSettings>
...
<add key="loginUrl" value="~/Account/SignIn" />
</appSettings>
I presume this will be fixed in the next release of ASP.NET MVC as a bug has been logged on Microsoft Connect here.
Follow
Get every new post delivered to your Inbox.
Join 82 other followers | __label__pos | 0.922014 |
Community
cancel
Showing results for
Search instead for
Did you mean:
JKuba2
Beginner
224 Views
BUG REPORT: VHDL 2008 target aggregate assignment leads to missing driver Warning
Hello,
I'm using target aggregates in VHDL 2008 and I found out, that Quartus (specifically "Quartus Prime Version 19.4.0 Build 64 12/04/2019 SC Pro Edition") fails to assign drivers to some of the target signals when they are std_logic_vector with the width of 1.
Here is an example code I tested it on:
library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity EXAMPLE is generic( WIDTH : natural := 8 ); port( IN_A : in std_logic_vector(WIDTH-1 downto 0); IN_B : in std_logic_vector(WIDTH-1 downto 0); OUT_A : out std_logic_vector(WIDTH-1 downto 0); OUT_B : out std_logic; OUT_C : out std_logic_vector(WIDTH-1 downto 0); OUT_D : out std_logic_vector(1-1 downto 0); OUT_E : out std_logic_vector(WIDTH/3-1 downto 0); OUT_F : out std_logic_vector(1-1 downto 0); OUT_G : out std_logic_vector(2-1 downto 0); OUT_H : out std_logic_vector(0-1 downto 0); OUT_I : out std_logic_vector((WIDTH+1)-(WIDTH/3+1+2+0)-1 downto 0) ); end entity; architecture FULL of EXAMPLE is signal result : unsigned(WIDTH+1-1 downto 0); begin my_process : process (all) begin result <= ("0" & unsigned(IN_A)) + ("0" & unsigned(IN_B)); (OUT_A, OUT_B) <= std_logic_vector(result); (OUT_C, OUT_D) <= std_logic_vector(result); (OUT_E, OUT_F, OUT_G, OUT_H, OUT_I) <= std_logic_vector(result); end process; end architecture;
Synthesizing this code leads to a warning:
Warning (13024): Output pins are stuck at VCC or GND Warning (13410): Pin "OUT_D[0]" is stuck at GND File: example.vhd Line: 17 Warning (13410): Pin "OUT_F[0]" is stuck at GND File: example.vhd Line: 20
meaning Quartus was unable to assign value to those parts of the aggregate, where the signal had a 1-bit width. You can see, that the bug does not occur, when the signal is a simple std_logic, but I have multiple cases where the width of the signal is determined by generics and it is possible for it to result as 1.
Thanks
0 Kudos
8 Replies
121 Views
Hi,
For 1-bit signal, you have to use std_logic instead of std_logic_vector.
Thanks.
Best regards,
KhaiY
JKuba2
Beginner
121 Views
Are you saying it's done on purpose and you don't plan on fixing it?
Because it would be a much lesser complication even if it was the other way around and the expression didn't work for std_logic instead. Than I can imagine turning all std_logic signals that are used in aggregates into 1-bit vectors; but this way it cannot be done so easily, since a vector with generic width can sometimes by 1 bit wide and sometimes wider. So the only way to solve this would be creating a std_logic version of each std_logic_vector and switch between them in separated IF branches based on the vector width. And since there are N signals in the aggregate, it would mean up to 2**N different branches of code to solve this. That really makes the whole point of target aggregates being used for code simplification useless.
Sincerely,
JKuba2
JCaba5
Beginner
121 Views
Hi,
I have the same problem as JKuba2. This bug is really annoying.
Sincerely,
Jakub
121 Views
Hi,
I received the reply from our developer. You may refer to the workaround in the test_19_4_0_64_workaround.QAR attached.
Thanks.
Best regards,
KhaiY
JKuba2
Beginner
121 Views
Hello
Well, this workaround fixes the non-working short aggregate assignment by not using the short aggregate assignment. I know how to do that, too. The point was to be able to assign multiple signals from one signal without having to explicitly write the width of each and every one of them and thus shorten the code and make it more clear and readable. I know I can make it work the same way without the aggregates. But it bugs me that it doesn't work in this specific case, even though it should.
I'm glad to see that someone was actually assigned to look into this, but this is not the result I was looking for, sadly. What I'm looking for is at least a hint suggesting that someone will try to fix the bug in the synthesis tool, even if it is in a version a year from now.
Thanks.
Best regards,
JKuba2
121 Views
Hi,
Yes. I have reported this to the developer and this is scheduled to be fix in the future release.
Thanks.
Best regards,
KhaiY
JKuba2
Beginner
121 Views
Thank you very much.
JKuba2
SSilu
Beginner
117 Views
I also confirm this annoying bug. It's shame quartus is lacking such basic support of VHDL 2008 features. I took me a few days to find out why my design was not working. Today I also realized that conditional assignment in process VHDL 2008 feature is not working. Quartus simply synthesize logic away.
rx_pkt_len_proc : process(clk_avmm) is
begin
if rising_edge(clk_avmm) then
ready <= '1';
ready <= '0' when ready = '1';
end if;
end process; | __label__pos | 0.71334 |
fbpx
In the early days of Microsoft Azure the Portal was the primary tool to go in and configure your cloud components. After some time the Azure Service Manager API’s were introduced as a set of both PowerShell and Command-Line tools (X-Plat CLI). These tools allowed for Azure Automation to be scripted, however they were still a bit cumbersome as they were procedural based. More recently Microsoft overhauled the entire Azure Portal that exists today as well as a brand new set of Azure Resource Manager API’s. The purpose of Azure Resource Manager is more than just replacing Azure Service Manager. It’s real purpose is a story about automation and DevOps.
Being a JSON file, ARM Templates provide a declarative method for defining Azure deployments. Defining deployments declaratively in this manner is known as Infrastructure as Code (IaC).
Azure Resource Manager
The most easily visible change to Microsoft Azure that came with the migration to Azure Resource Manager is the concept of Resource Groups. Resource Groups allow for various cloud components / entities (now referred to as Resources) deployed into Azure to be placed into logical groupings. The Resource Groups allow for a vastly improved experience for managing Azure Resources.
All the various Azure Resources (Web App, SQL Database, Storage, VM’s, etc) that make up a single Application or System can be grouped together as a logical unit. This allows for all the Resource Groups to be listed and navigated within the Azure Portal in a fashion that brings a high level of clarity as to what resources go together to form a complete application or system.
In the early days of Microsoft Azure it wasn’t difficult to manage all the Azure Resources since most companies didn’t really have that much deployed into a single Azure Subscription. As companies started adopting Azure more and migrating systems over to the cloud there became an increasing need to be able to more easily organize and manage the huge number of Azure Resources making up a dozen or even hundreds of applications. This lead to the natural evolution of Azure to implementing Azure Resource Groups.
While the “Groups” feature of Azure Resource Groups is the most visible there are a number of additional features and benefits to Azure Resource Groups. Here’s a list of a few of these:
• Organize all Azure Resources of a single application into a single logical Azure Resource Group
• Manage, Deploy and Monitor Azure Resources within a group together to treat them as building blocks of an application, rather than as stand-along components
• Ability to use declarative ARM Templates to define deployments
• Role Based Access Control (RBAC) for securing and controlling access to all resources within a group
• Ability to add Tags to each resource within a Resource Group so that additional metadata can be associated with Azure Resources
• More transparent billing by allowing for the costs of an entire Resource Group or resources with a specific Tag to be viewed
The migration of Azure Management to using Azure Resource Manager is a progression towards a more easily managed and organized Microsoft Azure Cloud.
Azure Automation
Using the Azure PowerShell and Azure CLI (Cross-Platform Command-Line Interface) Tools allow for scriptable management and deployment of Azure resources in a procedural manner. This is the method for Azure Automation that’s been supported since the introduction of Azure Service Management. The shift to Azure Resource Management still supports Azure PowerShell and Xplat-CLI with an additional set of commands for each tool that support Azure Resource Management.
The procedural method of using scripts to automate Azure Resource management and deployment is still fully supported by using the Azure PowerShell and Azure CLI tools in addition to the older Azure Service Management. Procedural automation allows for building scripts that are run line by line, from start to finish. This is a perfectly fine method of implementing automation and has pretty much been an industry standard for a really long time. This can also be an extremely quick method of implementing automation.
In addition to Automation, the Azure PowerShell and Azure CLI allow for quick command-line interface for interacting, managing and deploying Azure Resources that provides administrators an alternative to using the Azure Portal within a web browser.
ARM Template Deployment
One of the brand new features introduced by Azure Resource Management is ARM Templates (Azure Resource Management Templates). These Templates are built as a JSON file that declaratively defines the deployment and configuration of all the Azure Resources within a single Azure Resource Group. This allow for the definition of the Azure Resources for an application to be more simply defined while allowing Azure to manage the order in which everything needs to be deployed based on the necessary dependencies.
Being a JSON file, ARM Templates provide a declarative method for defining Azure deployments. Defining deployments declaratively in this manner is known as Infrastructure as Code (IaC). Infrastructure as Code not only provides a nice way to be able to upload an ARM Template to the Azure Portal for deployment, but also allows for more easily using it in Automated Build and Deployment scenarios. The ARM Template for an application can be checked into a Source Code Repository (TFS, Git, Github, etc) along-side the application code itself, or the ARM Template code can be maintained within a repository by itself for purely Infrastructure deployments.
Storing ARM Templates within a Source Code Repository allows for versioning and change tracking to more easily be managed and rollbacked when necessary without requiring additional documentation that can be easily neglected over time.
Want to see what an ARM Template’s JSON looks like? Here’s an ARM Template from the Azure QuickStart Templates repository full of community contributed ARM Templates that deploys an Azure Resource Group with a Web App and SQL Database:
{
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"skuName": {
"type": "string",
"defaultValue": "F1",
"allowedValues": [
"F1",
"D1",
"B1",
"B2",
"B3",
"S1",
"S2",
"S3",
"P1",
"P2",
"P3",
"P4"
],
"metadata": {
"description": "Describes plan's pricing tier and instance size. Check details at https://azure.microsoft.com/en-us/pricing/details/app-service/"
}
},
"skuCapacity": {
"type": "int",
"defaultValue": 1,
"minValue": 1,
"metadata": {
"description": "Describes plan's instance count"
}
},
"administratorLogin": {
"type": "string",
"metadata": {
"description": "The admin user of the SQL Server"
}
},
"administratorLoginPassword": {
"type": "securestring",
"metadata": {
"description": "The password of the admin user of the SQL Server"
}
},
"databaseName": {
"type": "string",
"defaultValue": "sampledb",
"metadata": {
"description": "The name of the new database to create."
}
},
"collation": {
"type": "string",
"defaultValue": "SQL_Latin1_General_CP1_CI_AS",
"metadata": {
"description": "The database collation for governing the proper use of characters."
}
},
"edition": {
"type": "string",
"defaultValue": "Basic",
"allowedValues": [
"Basic",
"Standard",
"Premium"
],
"metadata": {
"description": "The type of database to create."
}
},
"maxSizeBytes": {
"type": "string",
"defaultValue": "1073741824",
"metadata": {
"description": "The maximum size, in bytes, for the database"
}
},
"requestedServiceObjectiveName": {
"type": "string",
"defaultValue": "Basic",
"allowedValues": [
"Basic",
"S0",
"S1",
"S2",
"P1",
"P2",
"P3"
],
"metadata": {
"description": "Describes the performance level for Edition"
}
}
},
"variables": {
"hostingPlanName": "[concat('hostingplan', uniqueString(resourceGroup().id))]",
"webSiteName": "[concat('webSite', uniqueString(resourceGroup().id))]",
"sqlserverName": "[concat('sqlserver', uniqueString(resourceGroup().id))]"
},
"resources": [
{
"name": "[variables('sqlserverName')]",
"type": "Microsoft.Sql/servers",
"location": "[resourceGroup().location]",
"tags": {
"displayName": "SqlServer"
},
"apiVersion": "2014-04-01-preview",
"properties": {
"administratorLogin": "[parameters('administratorLogin')]",
"administratorLoginPassword": "[parameters('administratorLoginPassword')]"
},
"resources": [
{
"name": "[parameters('databaseName')]",
"type": "databases",
"location": "[resourceGroup().location]",
"tags": {
"displayName": "Database"
},
"apiVersion": "2014-04-01-preview",
"dependsOn": [
"[variables('sqlserverName')]"
],
"properties": {
"edition": "[parameters('edition')]",
"collation": "[parameters('collation')]",
"maxSizeBytes": "[parameters('maxSizeBytes')]",
"requestedServiceObjectiveName": "[parameters('requestedServiceObjectiveName')]"
}
},
{
"type": "firewallrules",
"apiVersion": "2014-04-01-preview",
"dependsOn": [
"[variables('sqlserverName')]"
],
"location": "[resourceGroup().location]",
"name": "AllowAllWindowsAzureIps",
"properties": {
"endIpAddress": "0.0.0.0",
"startIpAddress": "0.0.0.0"
}
}
]
},
{
"apiVersion": "2015-08-01",
"name": "[variables('hostingPlanName')]",
"type": "Microsoft.Web/serverfarms",
"location": "[resourceGroup().location]",
"tags": {
"displayName": "HostingPlan"
},
"sku": {
"name": "[parameters('skuName')]",
"capacity": "[parameters('skuCapacity')]"
},
"properties": {
"name": "[variables('hostingPlanName')]"
}
},
{
"apiVersion": "2015-08-01",
"name": "[variables('webSiteName')]",
"type": "Microsoft.Web/sites",
"location": "[resourceGroup().location]",
"dependsOn": [
"[variables('hostingPlanName')]"
],
"tags": {
"[concat('hidden-related:', resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName')))]": "empty",
"displayName": "Website"
},
"properties": {
"name": "[variables('webSiteName')]",
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
},
"resources": [
{
"apiVersion": "2015-08-01",
"type": "config",
"name": "connectionstrings",
"dependsOn": [
"[variables('webSiteName')]"
],
"properties": {
"DefaultConnection": {
"value": "[concat('Data Source=tcp:', reference(concat('Microsoft.Sql/servers/', variables('sqlserverName'))).fullyQualifiedDomainName, ',1433;Initial Catalog=', parameters('databaseName'), ';User Id=', parameters('administratorLogin'), '@', variables('sqlserverName'), ';Password=', parameters('administratorLoginPassword'), ';')]",
"type": "SQLServer"
}
}
}
]
},
{
"apiVersion": "2014-04-01",
"name": "[concat(variables('hostingPlanName'), '-', resourceGroup().name)]",
"type": "Microsoft.Insights/autoscalesettings",
"location": "[resourceGroup().location]",
"tags": {
"[concat('hidden-link:', resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName')))]": "Resource",
"displayName": "AutoScaleSettings"
},
"dependsOn": [
"[variables('hostingPlanName')]"
],
"properties": {
"profiles": [
{
"name": "Default",
"capacity": {
"minimum": 1,
"maximum": 2,
"default": 1
},
"rules": [
{
"metricTrigger": {
"metricName": "CpuPercentage",
"metricResourceUri": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
"timeGrain": "PT1M",
"statistic": "Average",
"timeWindow": "PT10M",
"timeAggregation": "Average",
"operator": "GreaterThan",
"threshold": 80.0
},
"scaleAction": {
"direction": "Increase",
"type": "ChangeCount",
"value": 1,
"cooldown": "PT10M"
}
},
{
"metricTrigger": {
"metricName": "CpuPercentage",
"metricResourceUri": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
"timeGrain": "PT1M",
"statistic": "Average",
"timeWindow": "PT1H",
"timeAggregation": "Average",
"operator": "LessThan",
"threshold": 60.0
},
"scaleAction": {
"direction": "Decrease",
"type": "ChangeCount",
"value": 1,
"cooldown": "PT1H"
}
}
]
}
],
"enabled": false,
"name": "[concat(variables('hostingPlanName'), '-', resourceGroup().name)]",
"targetResourceUri": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
}
},
{
"apiVersion": "2014-04-01",
"name": "[concat('ServerErrors ', variables('webSiteName'))]",
"type": "Microsoft.Insights/alertrules",
"location": "[resourceGroup().location]",
"dependsOn": [
"[variables('webSiteName')]"
],
"tags": {
"[concat('hidden-link:', resourceId('Microsoft.Web/sites', variables('webSiteName')))]": "Resource",
"displayName": "ServerErrorsAlertRule"
},
"properties": {
"name": "[concat('ServerErrors ', variables('webSiteName'))]",
"description": "[concat(variables('webSiteName'), ' has some server errors, status code 5xx.')]",
"isEnabled": false,
"condition": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
"dataSource": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
"resourceUri": "[resourceId('Microsoft.Web/sites', variables('webSiteName'))]",
"metricName": "Http5xx"
},
"operator": "GreaterThan",
"threshold": 0.0,
"windowSize": "PT5M"
},
"action": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
"sendToServiceOwners": true,
"customEmails": [ ]
}
}
},
{
"apiVersion": "2014-04-01",
"name": "[concat('ForbiddenRequests ', variables('webSiteName'))]",
"type": "Microsoft.Insights/alertrules",
"location": "[resourceGroup().location]",
"dependsOn": [
"[variables('webSiteName')]"
],
"tags": {
"[concat('hidden-link:', resourceId('Microsoft.Web/sites', variables('webSiteName')))]": "Resource",
"displayName": "ForbiddenRequestsAlertRule"
},
"properties": {
"name": "[concat('ForbiddenRequests ', variables('webSiteName'))]",
"description": "[concat(variables('webSiteName'), ' has some requests that are forbidden, status code 403.')]",
"isEnabled": false,
"condition": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
"dataSource": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
"resourceUri": "[resourceId('Microsoft.Web/sites', variables('webSiteName'))]",
"metricName": "Http403"
},
"operator": "GreaterThan",
"threshold": 0,
"windowSize": "PT5M"
},
"action": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
"sendToServiceOwners": true,
"customEmails": [ ]
}
}
},
{
"apiVersion": "2014-04-01",
"name": "[concat('CPUHigh ', variables('hostingPlanName'))]",
"type": "Microsoft.Insights/alertrules",
"location": "[resourceGroup().location]",
"dependsOn": [
"[variables('hostingPlanName')]"
],
"tags": {
"[concat('hidden-link:', resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName')))]": "Resource",
"displayName": "CPUHighAlertRule"
},
"properties": {
"name": "[concat('CPUHigh ', variables('hostingPlanName'))]",
"description": "[concat('The average CPU is high across all the instances of ', variables('hostingPlanName'))]",
"isEnabled": false,
"condition": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
"dataSource": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
"resourceUri": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
"metricName": "CpuPercentage"
},
"operator": "GreaterThan",
"threshold": 90,
"windowSize": "PT15M"
},
"action": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
"sendToServiceOwners": true,
"customEmails": [ ]
}
}
},
{
"apiVersion": "2014-04-01",
"name": "[concat('LongHttpQueue ', variables('hostingPlanName'))]",
"type": "Microsoft.Insights/alertrules",
"location": "[resourceGroup().location]",
"dependsOn": [
"[variables('hostingPlanName')]"
],
"tags": {
"[concat('hidden-link:', resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName')))]": "Resource",
"displayName": "AutoScaleSettings"
},
"properties": {
"name": "[concat('LongHttpQueue ', variables('hostingPlanName'))]",
"description": "[concat('The HTTP queue for the instances of ', variables('hostingPlanName'), ' has a large number of pending requests.')]",
"isEnabled": false,
"condition": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
"dataSource": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
"resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', variables('hostingPlanName'))]",
"metricName": "HttpQueueLength"
},
"operator": "GreaterThan",
"threshold": 100.0,
"windowSize": "PT5M"
},
"action": {
"odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
"sendToServiceOwners": true,
"customEmails": [ ]
}
}
},
{
"apiVersion": "2014-04-01",
"name": "[concat('AppInsights', variables('webSiteName'))]",
"type": "Microsoft.Insights/components",
"location": "Central US",
"dependsOn": [
"[variables('webSiteName')]"
],
"tags": {
"[concat('hidden-link:', resourceId('Microsoft.Web/sites', variables('webSiteName')))]": "Resource",
"displayName": "AppInsightsComponent"
},
"properties": {
"ApplicationId": "[variables('webSiteName')]"
}
}
],
"outputs": {
"siteUri": {
"type": "string",
"value": "[reference(concat('Microsoft.Web/sites/', variables('webSiteName')), '2015-08-01').hostnames[0]]"
},
"sqlSvrFqdn": {
"type": "string",
"value": "[reference(concat('Microsoft.Sql/servers/', variables('sqlserverName'))).fullyQualifiedDomainName]"
}
}
}
As is visible by the above example ARM Template, the file uses the JSON syntax which has become an industry standard for defining both data and configurations on every development platform. One of the reasons for this is that JSON provides more clarity and brevity that make things both easier to read by a person, as well as making the files smaller and quicker to transmit over the Internet. Using JSON for ARM Templates was a good choice by the Microsoft Azure Team rather than using XML or some other proprietary file format instead.
One of the concerns many Developers and IT Pros have with ARM Templates is that it’s not easy to know what to enter where within a template file to configure specific resources. To help with this Microsoft has a few different tooling support options available. The Azure SDK gives Visual Studio 2015 a new Azure Resource Group Project type that includes some GUI for editing ARM Templates. Also, in addition to the Azure QuickStart Templates repository, the Azure Portal and Azure PowerShell have been given support to Export a Resource Group to an ARM Template.
Azure + DevOps
Lastly in this article, but perhaps the most important point to note about Azure Resource Manager is the improved DevOps integration possibilities enabled by all the above mentioned features of ARM. The root of DevOps is Communication, and there is no better way to communicate the setup and deployment of a hosting environment than Automation.
The migration Azure management to Azure Resource Manager, combined with ARM Templates, allows for a HUGE improvement in the overall DevOps story of Azure. Microsoft Azure has always offered tremendous benefits that lend themselves naturally to DevOps, but Azure Resource Manager really completes the Azure + DevOps story in a comprehensive way!
If managing Azure Resources has been an issue for you in the past then you should get a breathe of fresh air when you adopt Azure Resource Manager, Resource Groups, and ARM Templates. The Microsoft Azure platform is becoming even more awesome!
Microsoft MVP
Chris Pietschmann is a Microsoft MVP, HashiCorp Ambassador, and Microsoft Certified Trainer (MCT) with 20+ years of experience designing and building Cloud & Enterprise systems. He has worked with companies of all sizes from startups to large enterprises. He has a passion for technology and sharing what he learns with others to help enable them to learn faster and be more productive.
HashiCorp Ambassador Microsoft Certified Trainer (MCT) Microsoft Certified: Azure Solutions Architect | __label__pos | 0.982798 |
PageRenderTime 21ms CodeModel.GetById 17ms app.highlight 1ms RepoModel.GetById 1ms app.codeStats 0ms
/examples/shapedcontrols/unit1.pas
http://github.com/graemeg/lazarus
Pascal | 73 lines | 53 code | 15 blank | 5 comment | 0 complexity | c637130e3cabd678096b68886805f0d2 MD5 | raw file
1unit Unit1;
2
3{$mode objfpc}{$H+}
4
5interface
6
7uses
8 Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,
9 ExtCtrls;
10
11type
12
13 { TForm1 }
14
15 TForm1 = class(TForm)
16 Button1: TButton;
17 procedure Button1Click(Sender: TObject);
18 procedure FormCreate(Sender: TObject);
19 private
20 { private declarations }
21 public
22 procedure ShapeControl(AControl: TWinControl);
23 end;
24
25var
26 Form1: TForm1;
27
28implementation
29
30{$R unit1.lfm}
31
32{ TForm1 }
33
34procedure TForm1.Button1Click(Sender: TObject);
35begin
36 ShapeControl(Self);
37end;
38
39procedure TForm1.FormCreate(Sender: TObject);
40begin
41 Button1.Handle;
42 ShapeControl(Button1);
43end;
44
45procedure TForm1.ShapeControl(AControl: TWinControl);
46var
47 ABitmap: TBitmap;
48 Points: array of TPoint;
49begin
50 ABitmap := TBitmap.Create;
51 ABitmap.Monochrome := True;
52 ABitmap.Width := AControl.Width;
53 ABitmap.Height := AControl.Height;
54 SetLength(Points, 6);
55 Points[0] := Point(0, ABitmap.Height div 2);
56 Points[1] := Point(10, 0);
57 Points[2] := Point(ABitmap.Width - 10, 0);
58 Points[3] := Point(ABitmap.Width, ABitmap.Height div 2);
59 Points[4] := Point(ABitmap.Width - 10, ABitmap.Height);
60 Points[5] := Point(10, ABitmap.Height);
61 with ABitmap.Canvas do
62 begin
63 Brush.Color := clBlack; // transparent color
64 FillRect(0, 0, ABitmap.Width, ABitmap.Height);
65 Brush.Color := clWhite; // mask color
66 Polygon(Points);
67 end;
68 AControl.SetShape(ABitmap);
69 ABitmap.Free;
70end;
71
72end.
73 | __label__pos | 0.939839 |
Skip to content
Instantly share code, notes, and snippets.
Embed
What would you like to do?
Delete the newest of files with the same name except for different extensions.
import os, time
import os.path
for path, dirs, files in os.walk('./'):
dups = {}
for x in files:
name, ext = os.path.splitext(x)
fullpath = path+'/'+x
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(fullpath)
if not name in dups:
dups[name] = [(name, ext, time.ctime(mtime))]
else:
dups[name].append([name, ext, time.ctime(mtime)])
dups[name] = sorted(dups[name], key=lambda x: x[2])
delname, delext, deldate = dups[name][0]
delpath = path+'/'+delname+delext
os.remove(delpath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time. | __label__pos | 0.845787 |
#include "q_rand.hpp" #include "artifact_type.hpp" #include "cave.hpp" #include "cave_type.hpp" #include "dungeon_flag.hpp" #include "dungeon_info_type.hpp" #include "game.hpp" #include "generate.hpp" #include "hook_build_room1_in.hpp" #include "hook_chardump_in.hpp" #include "hook_monster_death_in.hpp" #include "hooks.hpp" #include "init1.hpp" #include "lua_bind.hpp" #include "messages.hpp" #include "monster2.hpp" #include "monster3.hpp" #include "monster_race.hpp" #include "monster_race_flag.hpp" #include "monster_spell_flag.hpp" #include "monster_type.hpp" #include "object1.hpp" #include "object2.hpp" #include "object_flag.hpp" #include "object_kind.hpp" #include "object_type.hpp" #include "player_type.hpp" #include "skills.hpp" #include "tables.hpp" #include "util.hpp" #include "variable.hpp" #include "z-rand.hpp" #include #include static int randquest_hero[] = { 20, 13, 15, 16, 9, 17, 18, 8, -1 }; /* Possible number(and layout) or random quests */ #define MAX_RANDOM_QUESTS_TYPES ((8 * 3) + (8 * 1)) static int random_quests_types[MAX_RANDOM_QUESTS_TYPES] = { 1, 5, 6, 7, 10, 11, 12, 14, /* Princess type */ 1, 5, 6, 7, 10, 11, 12, 14, /* Princess type */ 1, 5, 6, 7, 10, 11, 12, 14, /* Princess type */ 20, 13, 15, 16, 9, 17, 18, 8, /* Hero Sword Quest */ }; /* Enforce OoD monsters until this level */ #define RQ_LEVEL_CAP 49 // Generate lookup function GENERATE_MONSTER_LOOKUP_FN(get_adventurer, "Adventurer") void initialize_random_quests(int n) { auto const &d_info = game->edit_data.d_info; int step, lvl, i, k; int old_type = dungeon_type; /* Zero out everything first */ for (i = 0; i < MAX_RANDOM_QUEST; i++) random_quests[i].type = 0; if (n == 0) return; /* Factor dlev value by 1000 to keep precision */ step = (98 * 1000) / n; lvl = step / 2; quest[QUEST_RANDOM].status = QUEST_STATUS_TAKEN; for (i = 0; i < n; i++) { monster_race *r_ptr = nullptr; int rl = (lvl / 1000) + 1; int min_level; int tries = 5000; random_quest *q_ptr = &random_quests[rl]; /* Find the appropriate dungeon */ for (std::size_t j = 0; j < d_info.size(); j++) { auto d_ptr = &d_info[j]; if (!(d_ptr->flags & DF_PRINCIPAL)) continue; if ((d_ptr->mindepth <= rl) && (rl <= d_ptr->maxdepth)) { dungeon_type = j; break; } } q_ptr->type = random_quests_types[rand_int(MAX_RANDOM_QUESTS_TYPES)]; /* XXX XXX XXX Try until valid choice is found */ while (tries) { bool_ ok; tries--; /* Random monster 5 - 10 levels out of depth */ q_ptr->r_idx = get_mon_num(rl + 4 + randint(6)); if (!q_ptr->r_idx) continue; r_ptr = &r_info[q_ptr->r_idx]; /* Accept only monsters that can be generated */ if (r_ptr->flags & RF_SPECIAL_GENE) continue; if (r_ptr->flags & RF_NEVER_GENE) continue; /* Accept only monsters that are not breeders */ if (r_ptr->spells & SF_MULTIPLY) continue; /* Forbid joke monsters */ if (r_ptr->flags & RF_JOKEANGBAND) continue; /* Accept only monsters that are not friends */ if (r_ptr->flags & RF_PET) continue; /* Refuse nazguls */ if (r_ptr->flags & RF_NAZGUL) continue; /* Accept only monsters that are not good */ if (r_ptr->flags & RF_GOOD) continue; /* If module says a monster race is friendly, then skip */ if (modules[game_module_idx].race_status != NULL) { s16b *status = (*modules[game_module_idx].race_status)(q_ptr->r_idx); if ((status != NULL) && (*status >= 0)) { continue; } } /* Assume no explosion attacks */ ok = TRUE; /* Reject monsters with exploding attacks */ for (k = 0; k < 4; k++) { if (r_ptr->blow[k].method == RBM_EXPLODE) ok = FALSE; } if (!ok) continue; /* No mutliple uniques */ if ((r_ptr->flags & RF_UNIQUE) && ((q_ptr->type != 1) || (r_ptr->max_num == -1))) continue; /* No single non uniques */ if ((!(r_ptr->flags & RF_UNIQUE)) && (q_ptr->type == 1)) continue; /* Level restriction */ min_level = (rl > RQ_LEVEL_CAP) ? RQ_LEVEL_CAP : rl; /* Accept monsters matching the level restriction */ if (r_ptr->level > min_level) break; } /* Arg could not find anything ??? */ if (!tries) { if (wizard) { message_add(format("Could not find quest monster on lvl %d", rl), TERM_RED); } q_ptr->type = 0; } else { if (r_ptr->flags & RF_UNIQUE) { r_ptr->max_num = -1; } q_ptr->done = false; if (wizard) { message_add(format("Quest for %d on lvl %d", q_ptr->r_idx, rl), TERM_RED); } } lvl += step; } dungeon_type = old_type; } bool_ is_randhero(int level) { int i; bool_ result = FALSE; for (i = 0; randquest_hero[i] != -1; i++) { if (random_quests[level].type == randquest_hero[i]) { result = TRUE; break; } } return result; } static void do_get_new_obj(int y, int x) { object_type *q_ptr[3], forge[3]; int res, i; /* Create objects */ std::vector items; for (i = 0; i < 3; i++) { /* Get local object */ q_ptr[i] = &forge[i]; /* Wipe the object */ object_wipe(q_ptr[i]); /* Make a great object */ make_object(q_ptr[i], TRUE, TRUE, obj_theme::no_theme()); q_ptr[i]->found = OBJ_FOUND_REWARD; char buf[100]; object_desc(buf, q_ptr[i], 0, 0); items.push_back(buf); } while (TRUE) { res = ask_menu("Choose a reward to get(a-c to choose, ESC to cancel)?", items); /* Ok ? lets learn ! */ if (res > -1) { /* Drop it in the dungeon */ drop_near(q_ptr[res], -1, y + 1, x); cmsg_print(TERM_YELLOW, "There, Noble Hero. I put it there. Thanks again!"); break; } } for (i = 0; i < 3; i++) { object_type *o_ptr = q_ptr[i]; /* Check if there is any not chosen artifact */ if (i != res && artifact_p(o_ptr)) { /* Mega-Hack -- Preserve the artifact */ if (o_ptr->tval == TV_RANDART) { random_artifacts[o_ptr->sval].generated = FALSE; } else if (k_info[o_ptr->k_idx].flags & TR_NORM_ART) { k_info[o_ptr->k_idx].artifact = FALSE; } else if (o_ptr->name1) { a_info[o_ptr->name1].cur_num = 0; } } } } static void princess_death(s32b m_idx, s32b r_idx) { int r; cmsg_print(TERM_YELLOW, "O Great And Noble Hero, you saved me!"); cmsg_print(TERM_YELLOW, "I am heading home now. I cannot reward you as I should, but please take this."); /* Look for the princess */ for (r = m_max - 1; r >= 1; r--) { /* Access the monster */ monster_type *m_ptr = &m_list[r]; /* Ignore "dead" monsters */ if (!m_ptr->r_idx) continue; /* Is it the princess? */ if (m_ptr->r_idx == 969) { int x = m_ptr->fx; int y = m_ptr->fy; int i, j; delete_monster_idx(r); /* Wipe the glass walls and create a stair */ for (i = x - 1; i <= x + 1; i++) for (j = y - 1; j <= y + 1; j++) { if (in_bounds(j, i)) cave_set_feat(j, i, FEAT_FLOOR); } cave_set_feat(y, x, FEAT_MORE); do_get_new_obj(y, x); random_quests[dun_level].done = true; break; } } } static void hero_death(s32b m_idx, s32b r_idx) { random_quests[dun_level].done = true; cmsg_print(TERM_YELLOW, "The adventurer steps out of the shadows and picks up his sword:"); cmsg_print(TERM_YELLOW, "'Ah! My sword! My trusty sword! Thanks."); if (!can_create_companion()) { cmsg_print(TERM_YELLOW, "I must go on my own way now."); cmsg_print(TERM_YELLOW, "But before I go, I can help your skills.'"); cmsg_print(TERM_YELLOW, "He touches your forehead."); do_get_new_skill(); return; } cmsg_print(TERM_YELLOW, "If you wish, I can help you in your adventures.'"); /* Flush input */ flush(); if (get_check("Do you want him to join you? ")) { int x, y, i; /* Look for a location */ for (i = 0; i < 20; ++i) { /* Pick a distance */ int d = (i / 15) + 1; /* Pick a location */ scatter(&y, &x, p_ptr->py, p_ptr->px, d); /* Require "empty" floor grid */ if (!cave_empty_bold(y, x)) continue; /* Hack -- no summon on glyph of warding */ if (cave[y][x].feat == FEAT_GLYPH) continue; if (cave[y][x].feat == FEAT_MINOR_GLYPH) continue; /* Nor on the between */ if (cave[y][x].feat == FEAT_BETWEEN) continue; /* ... nor on the Pattern */ if ((cave[y][x].feat >= FEAT_PATTERN_START) && (cave[y][x].feat <= FEAT_PATTERN_XTRA2)) continue; /* Okay */ break; } if (i < 20) { int r_idx = get_adventurer(); m_allow_special[r_idx] = TRUE; int m_idx = place_monster_one(y, x, r_idx, 0, FALSE, MSTATUS_COMPANION); m_allow_special[r_idx] = FALSE; if (m_idx) { m_list[m_idx].exp = monster_exp(1 + (dun_level * 3 / 2)); m_list[m_idx].status = MSTATUS_COMPANION; monster_check_experience(m_idx, TRUE); } } else msg_print("The adventurer suddenly seems afraid and flees..."); } else { cmsg_print(TERM_YELLOW, "'As you wish, but I want to do something for you.'"); cmsg_print(TERM_YELLOW, "He touches your forehead."); do_get_new_skill(); } } static bool_ quest_random_death_hook(void *, void *in_, void *) { struct hook_monster_death_in *in = static_cast(in_); s32b m_idx = in->m_idx; int r_idx = m_list[m_idx].r_idx; if (!(dungeon_flags & DF_PRINCIPAL)) return (FALSE); if ((dun_level < 1) || (dun_level >= MAX_RANDOM_QUEST)) return (FALSE); if (!random_quests[dun_level].type) return (FALSE); if (random_quests[dun_level].done) return (FALSE); if (p_ptr->inside_quest) return (FALSE); if (random_quests[dun_level].r_idx != r_idx) return (FALSE); if (!(m_list[m_idx].mflag & MFLAG_QUEST)) return (FALSE); /* Killed enough ?*/ quest[QUEST_RANDOM].data[0]++; if (quest[QUEST_RANDOM].data[0] == random_quests[dun_level].type) { if (is_randhero(dun_level)) hero_death(m_idx, r_idx); else princess_death(m_idx, r_idx); } return (FALSE); } static bool_ quest_random_turn_hook(void *, void *, void *) { quest[QUEST_RANDOM].data[0] = 0; quest[QUEST_RANDOM].data[1] = 0; return (FALSE); } static bool_ quest_random_feeling_hook(void *, void *, void *) { if (!(dungeon_flags & DF_PRINCIPAL)) return (FALSE); if ((dun_level < 1) || (dun_level >= MAX_RANDOM_QUEST)) return (FALSE); if (!random_quests[dun_level].type) return (FALSE); if (random_quests[dun_level].done) return (FALSE); if (p_ptr->inside_quest) return (FALSE); if (!dun_level) return (FALSE); if (is_randhero(dun_level)) { cmsg_format(TERM_YELLOW, "A strange man wrapped in a dark cloak steps out of the shadows:"); cmsg_format(TERM_YELLOW, "'Oh, please help me! A horrible %s stole my sword! I'm nothing without it.'", r_info[random_quests[dun_level].r_idx].name); } else cmsg_format(TERM_YELLOW, "You hear someone shouting: 'Leave me alone, stupid %s'", r_info[random_quests[dun_level].r_idx].name); return (FALSE); } static bool_ quest_random_gen_hero_hook(void *, void *, void *) { int i; if (!(dungeon_flags & DF_PRINCIPAL)) return (FALSE); if ((dun_level < 1) || (dun_level >= MAX_RANDOM_QUEST)) return (FALSE); if (!random_quests[dun_level].type) return (FALSE); if (random_quests[dun_level].done) return (FALSE); if (p_ptr->inside_quest) return (FALSE); if (!is_randhero(dun_level)) return (FALSE); i = random_quests[dun_level].type; m_allow_special[random_quests[dun_level].r_idx] = TRUE; while (i) { int m_idx, y = rand_range(1, cur_hgt - 2), x = rand_range(1, cur_wid - 2); m_idx = place_monster_one(y, x, random_quests[dun_level].r_idx, 0, FALSE, MSTATUS_ENEMY); if (m_idx) { monster_type *m_ptr = &m_list[m_idx]; m_ptr->mflag |= MFLAG_QUEST; i--; } } m_allow_special[random_quests[dun_level].r_idx] = FALSE; return (FALSE); } static bool_ quest_random_gen_hook(void *, void *in_, void *) { struct hook_build_room1_in *in = static_cast(in_); s32b bx0 = in->x; s32b by0 = in->y; s32b x, y; int xstart; int ystart; int y2, x2, yval, xval; int y1, x1, xsize, ysize; if (!(dungeon_flags & DF_PRINCIPAL)) return (FALSE); if ((dun_level < 1) || (dun_level >= MAX_RANDOM_QUEST)) return (FALSE); if (!random_quests[dun_level].type) return (FALSE); if (random_quests[dun_level].done) return (FALSE); if (p_ptr->inside_quest) return (FALSE); if (quest[QUEST_RANDOM].data[1]) return (FALSE); if (is_randhero(dun_level)) return (FALSE); /* Pick a room size */ get_map_size(format("qrand%d.map", random_quests[dun_level].type), &ysize, &xsize); /* Try to allocate space for room. If fails, exit */ if (!room_alloc(xsize + 2, ysize + 2, FALSE, by0, bx0, &xval, &yval)) return FALSE; /* Get corner values */ y1 = yval - ysize / 2; x1 = xval - xsize / 2; y2 = y1 + ysize - 1; x2 = x1 + xsize - 1; /* Place a full floor under the room */ for (y = y1; y <= y2; y++) { for (x = x1; x <= x2; x++) { cave_set_feat(y, x, floor_type[rand_int(100)]); cave[y][x].info |= (CAVE_ROOM|CAVE_GLOW); } } build_rectangle(y1 - 1, x1 - 1, y2 + 1, x2 + 1, feat_wall_outer, CAVE_ROOM | CAVE_GLOW); /* Set the correct monster hook */ set_mon_num_hook(); /* Prepare allocation table */ get_mon_num_prep(); xstart = x1; ystart = y1; init_flags = INIT_CREATE_DUNGEON; process_dungeon_file(format("qrand%d.map", random_quests[dun_level].type), &ystart, &xstart, cur_hgt, cur_wid, TRUE, TRUE); for (x = x1; x < xstart; x++) for (y = y1; y < ystart; y++) { cave[y][x].info |= CAVE_ICKY | CAVE_ROOM; if (cave[y][x].feat == FEAT_MARKER) { monster_type *m_ptr; int i; m_allow_special[random_quests[dun_level].r_idx] = TRUE; i = place_monster_one(y, x, random_quests[dun_level].r_idx, 0, FALSE, MSTATUS_ENEMY); m_allow_special[random_quests[dun_level].r_idx] = FALSE; if (i) { m_ptr = &m_list[i]; m_ptr->mflag |= MFLAG_QUEST; } } } /* Dont try another one for this generation */ quest[QUEST_RANDOM].data[1] = 1; /* Boost level feeling a bit - a la pits */ rating += 10; return (TRUE); } static bool_ quest_random_dump_hook(void *, void *in_, void *) { static const char *number[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" }; struct hook_chardump_in *in = static_cast(in_); FILE *f = in->file; int i, valid = 0, lscnt = 0, pcnt = 0; for (i = 0; i < MAX_RANDOM_QUEST; i++) { if (random_quests[i].type) { valid++; if (random_quests[i].done) { if (is_randhero(i)) lscnt++; else pcnt++; } } } if (valid) { if (pcnt > 10) fprintf(f, "\n You have completed %d princess quests.", pcnt); else if (pcnt > 1) fprintf(f, "\n You have completed %s princess quests.", number[pcnt-2]); else if (pcnt == 1) fprintf(f, "\n You have completed one princess quest."); else fprintf(f, "\n You haven't completed a single princess quest."); if (lscnt > 10) fprintf(f, "\n You have completed %d lost sword quests.", lscnt); else if (lscnt > 1) fprintf(f, "\n You have completed %s lost sword quests.", number[lscnt-2]); else if (lscnt == 1) fprintf(f, "\n You have completed one lost sword quest."); else fprintf(f, "\n You haven't completed a single lost sword quest."); } return (FALSE); } std::string quest_random_describe() { // Only emit description if we're actually on a // random quest level. if (!(dungeon_flags & DF_PRINCIPAL)) return ""; if ((dun_level < 1) || (dun_level >= MAX_RANDOM_QUEST)) return ""; if (!random_quests[dun_level].type) return ""; if (random_quests[dun_level].done) return ""; if (p_ptr->inside_quest) return ""; if (!dun_level) return ""; fmt::MemoryWriter w; if (!is_randhero(dun_level)) { w.write("#####yCaptured princess!\n"); w.write("A princess is being held prisoner and tortured here!\n"); w.write("Save her from the horrible {}.\n", r_info[random_quests[dun_level].r_idx].name); } else { w.write("#####yLost sword!\n"); w.write("An adventurer lost his sword to a bunch of {}!\n", r_info[random_quests[dun_level].r_idx].name); w.write("Kill them all to get it back.\n"); } w.write("Number: {}, Killed: {}.", random_quests[dun_level].type, quest[QUEST_RANDOM].data[0]); return w.str(); } bool_ quest_random_init_hook() { add_hook_new(HOOK_MONSTER_DEATH, quest_random_death_hook, "rand_death", NULL); add_hook_new(HOOK_NEW_LEVEL, quest_random_turn_hook, "rand_new_lvl", NULL); add_hook_new(HOOK_LEVEL_REGEN, quest_random_turn_hook, "rand_regen_lvl", NULL); add_hook_new(HOOK_LEVEL_END_GEN, quest_random_gen_hero_hook, "rand_gen_hero", NULL); add_hook_new(HOOK_BUILD_ROOM1, quest_random_gen_hook, "rand_gen", NULL); add_hook_new(HOOK_FEELING, quest_random_feeling_hook, "rand_feel", NULL); add_hook_new(HOOK_CHAR_DUMP, quest_random_dump_hook, "rand_dump", NULL); return (FALSE); } | __label__pos | 0.993472 |
computehost Vps Hosting
computehost Dedicate Hosting
Domain Name System
DNS or Domain Name System is defined as the way which domain names on the internet are situated and translated in the IP - Internet Protocol addresses. It maps name used by people to locate a site on IP address which a PC uses in order to locate a site. For instance, if a person types ComputeHost.com in the web browser, server behind will map the name to IP address like 206.19.19.180.
Most of the internet activities, including web browsing relies on Domain Name System in order to instantly provide vital information to connect audience to the remote hosts. The mapping of DNS is distributed on the internet in authority hierarchy. Businesses, access providers, universities and governments, typically have assigned domain name and IP addresses, and run on the DNS servers to handle those names mapping to the addresses. Even, many URLs are even built on domain name.
How DNS work?
The Domain Name System server answer the questions from inside/outside of the domains. The moment server receives request from domain outside regarding name and address of inside domain, it offers authoritative answer. And when server receives request from domain inside, then it passes that request to other server which is managed by its net service provider. In case, server don't know the authoritative source of answer, then it will connect to DNS servers of top-notch domain, for instance - .edu or .com.
How it increases web performance?
In order to promote proficiency, DNS servers can cache answers received by them for a particular time. It permits them to respond instantly next time when a request comes in. For instance, if every employee in a workplace requires an access to a particular training video on the site same day, the DNS server will just have to primarily resolve name, only then it can cater to other requests of cache. The time duration, record time and live time is configurable. Long values minimize load on DNS servers, while short values makes sure most correct responses.
• Computehost
• Computehost
• Computehost | __label__pos | 0.988884 |
Accordion Like Content Tabs Plugin with jQuery - Easy Responsive Tabs
Accordion Like Content Tabs Plugin with jQuery - Easy Responsive Tabs
File Size: 73.5 KB
Views Total: 20730
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
Easy Responsive Tabs is a simple jQuery plugin for quickly creating content Tabs which allow you organize larger groups of content into a tab interface. It will automatically turn the content Tabs into a content accordion for mobile devices. You can change the media query break point through CSS to set the accordion, when screen resolution changed.
Features:
• Supports all major browsers (IE7+, Chorme, Firefox, etc)
• Responsive and mobile-friendly
• Vertical or horizontal tabs supported
How to use it:
1. Include jQuery library and Easy Responsive Tabs plugin on your web page
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/easyResponsiveTabs.js" type="text/javascript"></script>
2. Create the html for the vertical content tabs
<div id="horizontalTab">
<ul class="resp-tabs-list">
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div class="resp-tabs-container">
<div>
<p>...</p>
</div>
<div>
<p>...</p>
</div>
<div>
<p>...</p>
</div>
</div>
</div>
3. Include
body {
margin: 0px;
padding: 0px;
background: #f5f5f5;
font-family: 'Segoe UI';
}
ul.resp-tabs-list, p {
margin: 0px;
padding: 0px;
}
.resp-tabs-list li {
font-weight: 600;
font-size: 13px;
display: inline-block;
padding: 13px 15px;
margin: 0;
list-style: none;
cursor: pointer;
float: left;
}
.resp-tabs-container {
padding: 0px;
background-color: #fff;
clear: left;
}
h2.resp-accordion {
cursor: pointer;
padding: 5px;
display: none;
}
.resp-tab-content {
display: none;
padding: 15px;
}
.resp-tab-active {
border: 1px solid #c1c1c1;
border-bottom: none;
margin-bottom: -1px !important;
padding: 12px 14px 14px 14px !important;
}
.resp-tab-active {
border-bottom: none;
background-color: #fff;
}
.resp-content-active, .resp-accordion-active {
display: block;
}
.resp-tab-content {
border: 1px solid #c1c1c1;
}
h2.resp-accordion {
font-size: 13px;
border: 1px solid #c1c1c1;
border-top: 0px solid #c1c1c1;
margin: 0px;
padding: 10px 15px;
}
h2.resp-tab-active {
border-bottom: 0px solid #c1c1c1 !important;
margin-bottom: 0px !important;
padding: 10px 15px !important;
}
h2.resp-tab-title:last-child {
border-bottom: 12px solid #c1c1c1 !important;
background: blue;
}
.resp-arrow {
width: 0;
height: 0;
float: right;
margin-top: 3px;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 12px solid #c1c1c1;
}
h2.resp-tab-active span.resp-arrow {
border: none;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 12px solid #9B9797;
}
/*-----------Accordion styles-----------*/
h2.resp-tab-active {
background: #DBDBDB !important;
}
.resp-easy-accordion h2.resp-accordion {
display: block;
}
.resp-easy-accordion .resp-tab-content {
border: 1px solid #c1c1c1;
}
.resp-easy-accordion .resp-tab-content:last-child {
border-bottom: 1px solid #c1c1c1 !important;
}
.resp-jfit {
width: 100%;
margin: 0px;
}
.resp-tab-content-active {
display: block;
}
h2.resp-accordion:first-child {
border-top: 1px solid #c1c1c1 !important;
}
/*Here your can change the breakpoint to set the accordion, when screen resolution changed*/
@media only screen and (max-width: 768px) {
ul.resp-tabs-list {
display: none;
}
h2.resp-accordion {
display: block;
}
.resp-vtabs .resp-tab-content {
border: 1px solid #C1C1C1;
}
.resp-vtabs .resp-tabs-container {
border: none;
float: none;
width: 100%;
min-height: initial;
clear: none;
}
.resp-accordion-closed {
display: none !important;
}
.resp-vtabs .resp-tab-content:last-child {
border-bottom: 1px solid #c1c1c1 !important;
}
}
4. Call the plugin with options
$(document).ready(function () {
$('#horizontalTab').easyResponsiveTabs({
// Types: default, vertical, accordion
type: 'default',
//auto or any width like 600px
width: 'auto',
// 100% fit in a container
fit: true,
// Close the panels on start,
// the options 'accordion' and 'tabs' keep them closed in there respective view types
closed: false,
// The tab groups identifier
tabidentify: '',
// background color for active tabs in this group
activetab_bg: 'white',
// background color for inactive tabs in this group
inactive_bg: '#F5F5F5',
// border color for active tabs heads in this group
active_border_color: '#c1c1c1',
// border color for active tabs contect in this group
// so that it matches the tab head border
active_content_border_color: '#c1c1c1',
activate: function () {}
});
});
Change log:
2014-12-24
This awesome jQuery plugin is developed by samsono. For more Advanced Usages, please check the demo page or visit the official website. | __label__pos | 0.980799 |
How Removable Storage Works
Prev Next
Tech | Memory
Solid-State Storage
A very popular type of removable storage for small devices, such as digital cameras and PDAs, is Flash memory. Flash memory is a type of solid-state technology, which basically means that there are no moving parts. Inside the chip is a grid of columns and rows, with a two-transistor cell at each intersecting point on the grid. The two transistors are separated by a thin oxide layer. One of the transistors is known as the floating gate, and the other one is the control gate. The floating gate's only link to the row, or wordline, is through the control gate. As long as this link is in place, the cell has a value of "1."
To change the cell value to a "0" requires a curious process called Fowler-Nordheim tunneling. Tunneling is used to alter the placement of electrons in the floating gate. An electrical charge, usually between 10 and 13 volts, is applied to the floating gate. The charge comes from the column, or bitline, enters the floating gate and drains to a ground.
This charge causes the floating-gate transistor to act like an electron gun. The excited, negatively charged electrons are pushed through and trapped on the other side of the oxide layer, which acquires a negative charge. The electrons act as a barrier between the control gate and the floating gate. A device called a cell sensor monitors the level of the charge passing through the floating gate. If the flow through the gate is greater than fifty percent of the charge, it has a value of "1." If the charge passing through drops below the fifty-percent threshold, the value changes to "0."
This content is not compatible on this device.
Flash memory uses Fowler-Nordheim tunneling
to alter the placement of electrons.
The electrons in the cells of a Flash-memory chip can be returned to normal ("1") by the application of an electric field, a higher-voltage charge. Flash memory uses in-circuit wiring to apply this electric field either to the entire chip or to predetermined sections known as blocks. This erases the targeted area of the chip, which can then be rewritten. Flash memory works much faster than traditional electrically erasable programmable read-only memory (EEPROM) chips because instead of erasing one byte at a time, it erases a block or the entire chip. | __label__pos | 0.97009 |
free后向合并unlink利用
利用条件
1. 存在两个相邻堆块
• 能控制前一堆块数据部分
• 能控制后一堆块header部分
2. 有可写指针指向前一堆块数据段地址,能获取该指针地址
利用原理
堆块 free 时,如果相邻前一堆块处于空闲状态,会尝试进行后向合并的操作,将两堆块合并成一个堆块。其中由于空闲堆块原本在双向链表中管理,因此会触发 unlink 对其进行脱链,即从双向链表中取出。
关于 unlink 的详细介绍,可以参考CTF Wiki上的Unlink文章,本文只介绍free时后向合并的unlink利用。
以下是 _int_free 函数后向合并的部分源码:
/* consolidate backward */
if (!prev_inuse(p)) { // 需要当前释放堆块的prev_inuse段为0,也就是指示前一堆块为空闲状态
prevsize = prev_size (p);
size += prevsize;
p = chunk_at_offset(p, -((long) prevsize));
if (__glibc_unlikely (chunksize(p) != prevsize))
malloc_printerr ("corrupted size vs. prev_size while consolidating");
unlink_chunk (av, p);
}
可以看出,free当前堆块时,如果堆块的prev_inuse为0,表明前一堆块处于空闲状态,就会尝试进行后向合并操作。
然后会触发 unlink 操作将前一堆块从链表中取出,以下时 unlink_chunk 函数的源码:
/* Take a chunk off a bin list. */
static void
unlink_chunk (mstate av, mchunkptr p)
{
// size检测
// 空闲堆块的大小(size段)等于后一堆块记录的大小(prev_size段)
if (chunksize (p) != prev_size (next_chunk (p)))
malloc_printerr ("corrupted size vs. prev_size");
mchunkptr fd = p->fd;
mchunkptr bk = p->bk;
// 双向链表完整性检测
// 链表中前一堆块的后一堆块和后一堆块的前一堆块等于当前堆块
if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
malloc_printerr ("corrupted double-linked list");
fd->bk = bk;
bk->fd = fd;
// 如果大小不属于smallbin的范围并且fd_nextsize段不为NULL,需要进行largebin的检测
if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
{
// largebin的nextsize双向链表完整性检测
// 一般只需要把fd_nextsize段置0就不需要过这个检测
if (p->fd_nextsize->bk_nextsize != p
|| p->bk_nextsize->fd_nextsize != p)
malloc_printerr ("corrupted double-linked list (not small)");
if (fd->fd_nextsize == NULL)
{
if (p->fd_nextsize == p)
fd->fd_nextsize = fd->bk_nextsize = fd;
else
{
fd->fd_nextsize = p->fd_nextsize;
fd->bk_nextsize = p->bk_nextsize;
p->fd_nextsize->bk_nextsize = fd;
p->bk_nextsize->fd_nextsize = fd;
}
}
else
{
p->fd_nextsize->bk_nextsize = p->bk_nextsize;
p->bk_nextsize->fd_nextsize = p->fd_nextsize;
}
}
}
总结一下,要触发 unlink ,需要满足以下检测的条件:
1. size检测:chunksize (p) == prev_size (next_chunk (p))
2. 双向链表完整性检测: fd->bk == p && bk->fd == p
3. largebin检测:in_smallbin_range (chunksize_nomask (p)) || p->fd_nextsize == NULL
然后就能完成脱链操作,也是实现任意地址写的关键:
fd->bk = bk;
bk->fd = fd;
假设存在两个相邻堆块 chunk0 和 chunk1;chunk0_ptr 是指向 chunk0_data 部分的一个可写指针,其地址已知。我们可以控制chunk0 的 data 和 chunk1 的 header 部分。根据以上原理,我们进行如下构造:
unlink
此处以64位为例说明,与32位区别在于各段偏移大小
对于 chunk0_ptr ,有:
chunk0_ptr = p // p为chunk0_data的地址,也就是伪造的fake_chunk0地址
// chunk0_ptr的地址为0x0602280
// 即&chunk_ptr = 0x0602280
在该堆块内伪造一个堆块,使得:
fake_chunk0->prev_size = 0
fake_chunk0->size = chunk0_malloc_size // chunk0 申请的大小
// 双向链表完整性检测
fake_chunk0->fd = &chunk0_ptr - 0x18 // = 0x0602280 - 0x18 = 0x0602268
fake_chunk0->bk = &chunk0_ptr - 0x10 // = 0x0602268 - 0x10 = 0x0602270
// fd = p->fd = fake_chunk0->fd = 0x0602268
// bk = p->bk = fake_chunk0->bk = 0x0602270
// fd->bk = *(0x0602268 + 0x18) = *(0x0602280) = chunk0_ptr = p
// bk->fd = *(0x0602270 + 0x10) = *(0x0602280) = chunk0_ptr = p
对于 largebin 大小的堆块,还需要:
fake_chunk0->fd_nextsize = 0 // p->fd_nextsize = NULL
然后覆盖下一个堆块的 header 部分,使得:
chunk1->prev_size = fake_chunk->size // size检测
chunk1->size &= ~1 // prev_inuse置0
实现unlink:
fd->bk = bk // fd->bk => *(0x0602268 + 0x18) => *(0x0602280) => chunk_ptr = 0x0602280 - 0x10
bk->fd = fd // bk->fd => *(0x0602270 + 0x10) => *(0x0602280) => chunk_ptr = 0x0602280 - 0x18
最终实现效果:
chunk_ptr = &chunk_ptr - 0x18
将可写指针指向本身低0x18字节位置,于是可以控制可写指针写入任意地址。
实例
how2heap unsafe_unlink
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
uint64_t *chunk0_ptr;
int main()
{
setbuf(stdout, NULL);
printf("Welcome to unsafe unlink 2.0!\n");
printf("Tested in Ubuntu 20.04 64bit.\n");
printf("This technique can be used when you have a pointer at a known location to a region you can call unlink on.\n");
printf("The most common scenario is a vulnerable buffer that can be overflown and has a global pointer.\n");
int malloc_size = 0x420; //we want to be big enough not to use tcache or fastbin
int header_size = 2;
printf("The point of this exercise is to use free to corrupt the global chunk0_ptr to achieve arbitrary memory write.\n\n");
chunk0_ptr = (uint64_t*) malloc(malloc_size); //chunk0
uint64_t *chunk1_ptr = (uint64_t*) malloc(malloc_size); //chunk1
printf("The global chunk0_ptr is at %p, pointing to %p\n", &chunk0_ptr, chunk0_ptr);
printf("The victim chunk we are going to corrupt is at %p\n\n", chunk1_ptr);
printf("We create a fake chunk inside chunk0.\n");
printf("We setup the size of our fake chunk so that we can bypass the check introduced in https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=d6db68e66dff25d12c3bc5641b60cbd7fb6ab44f\n");
chunk0_ptr[1] = chunk0_ptr[-1] - 0x10;
printf("We setup the 'next_free_chunk' (fd) of our fake chunk to point near to &chunk0_ptr so that P->fd->bk = P.\n");
chunk0_ptr[2] = (uint64_t) &chunk0_ptr-(sizeof(uint64_t)*3);
printf("We setup the 'previous_free_chunk' (bk) of our fake chunk to point near to &chunk0_ptr so that P->bk->fd = P.\n");
printf("With this setup we can pass this check: (P->fd->bk != P || P->bk->fd != P) == False\n");
chunk0_ptr[3] = (uint64_t) &chunk0_ptr-(sizeof(uint64_t)*2);
printf("Fake chunk fd: %p\n",(void*) chunk0_ptr[2]);
printf("Fake chunk bk: %p\n\n",(void*) chunk0_ptr[3]);
printf("We assume that we have an overflow in chunk0 so that we can freely change chunk1 metadata.\n");
uint64_t *chunk1_hdr = chunk1_ptr - header_size;
printf("We shrink the size of chunk0 (saved as 'previous_size' in chunk1) so that free will think that chunk0 starts where we placed our fake chunk.\n");
printf("It's important that our fake chunk begins exactly where the known pointer points and that we shrink the chunk accordingly\n");
chunk1_hdr[0] = malloc_size;
printf("If we had 'normally' freed chunk0, chunk1.previous_size would have been 0x430, however this is its new value: %p\n",(void*)chunk1_hdr[0]);
printf("We mark our fake chunk as free by setting 'previous_in_use' of chunk1 as False.\n\n");
chunk1_hdr[1] &= ~1;
printf("Now we free chunk1 so that consolidate backward will unlink our fake chunk, overwriting chunk0_ptr.\n");
printf("You can find the source of the unlink macro at https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=ef04360b918bceca424482c6db03cc5ec90c3e00;hb=07c18a008c2ed8f5660adba2b778671db159a141#l1344\n\n");
free(chunk1_ptr);
printf("At this point we can use chunk0_ptr to overwrite itself to point to an arbitrary location.\n");
char victim_string[8];
strcpy(victim_string,"Hello!~");
chunk0_ptr[3] = (uint64_t) victim_string;
printf("chunk0_ptr is now pointing where we want, we use it to overwrite our victim string.\n");
printf("Original value: %s\n",victim_string);
chunk0_ptr[0] = 0x4141414142424242LL;
printf("New Value: %s\n",victim_string);
// sanity check
assert(*(long *)victim_string == 0x4141414142424242L);
}
相关练习
• 2014 HITCON stkof
参考
[1] Unlink - CTF Wiki, https://ctf-wiki.org/pwn/linux/user-mode/heap/ptmalloc2/unlink/
[2] unlink - 星盟安全Pwn公开课, https://www.bilibili.com/video/BV1Uv411j7fr?p=20&spm_id_from=pageDriver&vd_source=cd6c2579222a1d3d359211fb8bf436d3
[3] HITCON 2014 pwn - stkof 做题笔记, https://blog.csdn.net/qq_33976344/article/details/119929139
暂无评论
发送评论 编辑评论
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇 | __label__pos | 0.794081 |
You are here: Home » Video Asset Management » Using Streaming Media With Digital Asset Management Systems
Using Streaming Media With Digital Asset Management Systems
by Naresh Sarwan on September 14, 2009
In the first of a series of three media streaming articles, Naresh Sarwan describes how streamed media works and looks at two main methods: progressive download and true streaming. The other two articles in the series are Streaming Video Formats For Digital Asset Management and What Streaming Media Player Should Be Used With Digital Asset Management Systems?
What Is Streaming Video?
It is clear from discussing requirements with clients that there is widespread confusion about what streaming is, how it works and what the implications are. This is not entirely surprising, most of the available literature is highly technical and difficult to understand. In this article, I, attempt to present a simple overview of some of the basic concepts behind media streaming and why it is important.
Why Stream Media?
The main benefit of streaming is quite straightforward to understand. With streamed media, rather than needing to wait for an entire file to download, users can start viewing or listening to a clip as soon as enough data arrives for a player to begin displaying it. For live events, it is essential, there is no other feasible method of delivery. For archived media, the choice is less clear, but for the majority of Digital Asset Management scenarios, providing a streamed edition (at least for preview) is now simple to achieve using cheap widely available technology and a vendor (or development team) who has the necessary skills.
What Option Are Available For Streaming Digital Assets?
Once past the basic concepts of streaming, things get more complicated. There are essentially two further choices which begin to take the discussion into a more technical realm:
• The streaming method
• The streaming format
If chosen incorrectly, these can have some negative consequences in terms of performance and compatibility. Streaming itself divides into two broad techniques (there are others, but these are outside the scope of this article):
• Progressive Download
• True Streaming
Progressive Download
Progressive Download or ‘Pseudo Streaming’ as it is sometimes called is probably the most popular type currently in use on most websites because it is very easy to implement. Although the user can begin playing back media as soon as it downloads, they cannot skip forward to a part of the media that has not downloaded yet. The advantage is that media can be delivered on the same web server as used to deliver a Digital Asset Management system (or website) and the streamed media merely needs to be placed with other files – like web pages, PDFs, images etc. The media player takes responsibility for managing the download and partially assumes the role that a true streaming server would have provided – this is what simplifies the process and makes it far cheaper than true streaming.
The disadvantage is that for longer footage like movies or TV programmes is that users cannot access any of the media that has not yet downloaded. If their connection is slow and the playback rate exceeds the amount downloaded, they must wait while the player buffers some more of the footage to allow playback to start again – this can happen repeatedly and interrupt the playback experience. If your Digital Asset Management system uses any kind of timeline metadata features (e.g. Edit Decision Lists, DVD style chapters, linking assets based on time codes etc.) then the Progressive Streaming approach might restrict the facilities you can reliably offer.
True Streaming
True Streaming uses a dedicated streaming server. This is not necessarily a hardware device, but special software that delivers the client player the section of the footage that the user is requesting – whether at the start, middle or end. Rather than needing to wait for the section of the media that the user wants to play, they can be given the exact entry point they require and the stream commences from there. True Streaming is the best approach for longer footage and is the method of choice for established broadcast media owners (the BBC iPlayer, is an example of true streaming). For advanced video operations involving manipulation of timeline metadata, like video editing applications, True Streaming is usually essential.
The main disadvantage of True Streaming is that it requires a special dedicated server and is therefore harder to setup and may involve some systems administration work to enable successful playback in more secure corporate IT environments where Digital Asset Management systems are likely to be used.
Conclusion
Despite these drawbacks, the process of setting up most modern streaming server is not especially complex for most systems administrator or engineers and the task is far simpler now than it was a few years ago. In addition, competitive vendors such as Wowza Media and and open source solutions like Red5 have reduced the entry costs considerably even when taking into account the set-up and configuration. For most Video Digital Asset Management or Media Asset Management systems for significant groups of users, I recommend clients use a streaming server implement all Video DAM systems to easily scale to accommodate one from the outset.
Read the follow up article: Streaming Video Formats For Digital Asset Management.
What Is Streaming Video?
It is clear from discussing requirements with clients that there is widespread confusion about what streaming is, how it works and what the implications are. This is not entirely surprising, most of the available literature is highly technical and difficult to understand. In this article, I, attempt to present a simple overview of some of the basic concepts behind media streaming and why it is important.
Why Stream Media?
The main benefit of streaming is quite straightforward to understand. With streamed media, rather than needing to wait for an entire file to download, users can start viewing or listening to a clip as soon as enough data arrives for a player to begin displaying it. For live events, it is essential, there is no other feasible method of delivery. For archived media, the choice is less clear, but for the majority of Digital Asset Management scenarios, providing a streamed edition (at least for preview) is now simple to achieve using cheap widely available technology and a vendor (or development team) who has the necessary skills.
Related posts:
Leave a Comment
Previous post:
Next post: | __label__pos | 0.742002 |
no add friend button on facebook
Did you know that there are instances where you might not see the “Add Friend” button on Facebook profiles? It’s true! Despite its prominence as a social networking platform, there are situations where the option to add someone as a friend is not available.
This phenomenon can be puzzling and frustrating, especially when you’re eager to connect with someone. However, there are several reasons why the “Add Friend” button may not show up on Facebook profiles.
Key Takeaways:
• There are various reasons why the “Add Friend” button may not appear on Facebook profiles, such as privacy settings, denied or marked as spam friend requests, reaching the friend limit, or being blocked from sending friend requests.
• Adjusting your privacy settings, unfriending inactive accounts, sending a message to inquire about the friend request, or waiting for a response are potential solutions to the issue.
• Understanding these factors and implementing the suggested solutions can help overcome the challenge of not being able to send friend requests on Facebook.
Privacy settings restricting friend requests
Privacy settings on Facebook can restrict the visibility of the “Add Friend” button. Users have the ability to control who can send them friend requests by adjusting their profile settings. By setting their profile to private or restricted, users can ensure that only certain people can send them friend requests.
Additionally, some users choose to limit friend requests to only friends of friends. This means that if you are not connected to them through mutual friends, you won’t see the “Add Friend” button on their profile. This restriction helps users maintain a tighter-knit network on Facebook.
It’s important to note that if someone has blocked you, you won’t be able to see the “Add Friend” button on their profile. Blocking someone on Facebook prevents them from interacting with you in various ways, including sending friend requests.
Adjusting privacy settings is an effective way for users to manage who can send them friend requests and maintain control over their online connections.
Why adjust privacy settings?
Privacy settings on Facebook allow users to have greater control over their online presence. By restricting friend requests, users can choose who they want to connect with on the platform. This helps to ensure that users only receive friend requests from people they know or have mutual connections with.
“I prefer to keep my Facebook profile private so that I can control who can send me friend requests. It helps me maintain a secure and personal network of friends.” – Jane Doe
Friend request setting set to “Friends of friends” instead of “Everyone”
One of the reasons why the “Add Friend” button may not be visible on Facebook profiles is because of the friend request settings. These settings have an impact on who can send and receive friend requests. If a user has set their friend request setting to “Friends of friends,” it means that only people who are friends with their existing friends can send them a friend request.
This setting can limit the number of new connections made on the platform, especially if there are no mutual friends between you and the person you want to add. If you find that you’re having trouble sending or receiving friend requests, it’s worth checking your friend request settings to make sure they are not set to “Friends of friends.”
See also Learn Quickly: How to See Your Facebook Password
To adjust your friend request settings on Facebook:
1. Go to your Facebook profile.
2. Click on the “Friends” tab on your profile page.
3. Click on the three dots (ellipsis) next to the “Find Friends” button.
4. Select “Edit Privacy.”
5. Under the “Who can send you friend requests?” section, choose the desired option. If you want to receive friend requests from everyone, select “Everyone.”
6. Save the changes.
By modifying your friend request settings to allow friend requests from everyone, you can expand your network and make new connections on Facebook.
It’s important to note that while adjusting your friend request settings can increase the chances of receiving friend requests, it’s always best to send requests to people you know or have genuine connections with. Building meaningful relationships on Facebook is key to a positive social experience.
Friend request denied or marked as spam
Sometimes, the “Add Friend” button may not be visible on Facebook profiles because your friend request has been denied or marked as spam.
When a friend request is denied, it means that the recipient has chosen not to accept your request. This could happen for various reasons, such as the person not recognizing you or not wanting to expand their friend list at the moment.
“I received a friend request from someone I didn’t know, so I decided to deny it. I prefer to connect with people I actually know in real life.”
– Sarah Thompson
On the other hand, if your friend request is marked as spam, it indicates that the recipient or the Facebook system has flagged your request as suspicious or violating community guidelines. This may occur if you have been sending too many friend requests in a short period of time, or if your account has been reported for suspicious activity.
• Sending multiple friend requests to people you don’t know: If you send friend requests to a large number of people whom you have no real connection with, Facebook’s spam detection algorithms may flag your account.
• Being reported for suspicious activity: If multiple people report your account as suspicious or if your account engages in behavior that violates Facebook’s terms of service, your friend requests may be marked as spam.
To avoid having your friend requests marked as spam, it’s important to send requests only to people you know and with whom you have a genuine connection.
If you believe that your friend requests have been wrongly categorized as spam, you can contact Facebook Support to review your account and address the issue.
friend request denied on Facebook
User has reached friend limit of 5,000 or is blocked from sending requests
The “Add Friend” button may not show up if the user has reached the friend limit of 5,000 or if they have been blocked from sending friend requests. If a user has already reached the maximum number of friends allowed on Facebook, they will need to delete existing friends before being able to add new ones. Additionally, if a user has violated Facebook’s terms of service or sent too many requests that were marked as spam, they may be temporarily blocked from sending or accepting friend requests.
If you find that you are unable to see the “Add Friend” button on someone’s profile, it could be because they have reached the maximum number of friends allowed on Facebook. In order to add them as a friend, they would need to remove some of their existing friends to make room for new connections.
Another reason why you may not be able to send friend requests is if you have violated Facebook’s terms of service or sent too many requests that were marked as spam. In such cases, Facebook may temporarily block you from sending or accepting friend requests as a way to prevent misuse of the platform.
It’s important to be mindful of the friend limit and to respect Facebook’s guidelines when it comes to sending friend requests. If you find yourself unable to add new friends, consider managing your friend list and removing inactive or unnecessary connections to make room for new ones.
See also Facebook Marketing Tactics for B2B Companies
friend limit on Facebook and blocked from sending friend requests
Common reasons for being blocked from sending friend requests:
• Sending too many friend requests in a short period of time
• Adding people you don’t personally know
• Having a high number of friend requests marked as spam
• Violating Facebook’s terms of service
It’s important to use the friend request feature on Facebook responsibly and to only send requests to people you have a genuine connection with. This helps maintain the integrity of the platform and ensures a positive experience for all users.
Solutions to the issue
If you’re facing difficulty finding the “Add Friend” button on Facebook, don’t worry! There are several solutions you can try to overcome this problem.
Adjust Your Privacy Settings
One effective solution is to adjust your privacy settings on Facebook. By doing so, you can ensure that the “Add Friend” button is visible and accessible to others. To adjust your settings:
1. Go to your Facebook profile.
2. Click on the “Privacy” tab.
3. Review your privacy settings and ensure that friend requests are allowed from everyone.
Unfriend Inactive Accounts
If you have a large number of inactive accounts on your friends list, it may be preventing you from adding new friends. Consider unfriending these inactive accounts to make room for new friend requests. To unfriend an account:
• Navigate to the account’s profile page.
• Click on the “Friends” button.
• Select “Unfriend” from the dropdown menu.
Send a Message to Inquire
If you’re unable to locate the “Add Friend” button on someone’s profile, try sending them a message to inquire about the friend request. By reaching out directly, you can clarify any confusion and express your interest in connecting with them.
“Hey [Name], I tried sending you a friend request but couldn’t find the ‘Add Friend’ button on your profile. Could you please let me know if you’d like to connect? Thanks!”
Waiting for a response
Finally, if you’ve sent a friend request and don’t receive an immediate acceptance or decline, it might be best to simply wait for a response. Sometimes, people may take time to consider friend requests or may not use Facebook regularly. Patience can often lead to successful connections!
Conclusion
In conclusion, the absence of the “Add Friend” button on Facebook profiles can be attributed to various reasons. These include privacy settings, denied or marked as spam friend requests, reaching the friend limit, or being blocked from sending friend requests. Understanding these factors is crucial in resolving the issue of being unable to send friend requests on Facebook.
To overcome this problem, there are several solutions that users can explore. One solution is to adjust their privacy settings to allow friend requests from everyone. Another option is to unfriend inactive accounts to create space for new friend requests. Additionally, users can send a message to inquire about the friend request or simply wait for a response.
By implementing these suggested solutions and considering the potential reasons behind the absence of the “Add Friend” button, users can successfully navigate the challenges of not being able to send friend requests on Facebook. With a better understanding of privacy settings and utilization of available options, connecting and expanding social circles on the platform becomes more efficient and effective.
FAQ
Why is There No Add Friend Button on Facebook Profiles?
The “Add Friend” button may not show up on Facebook profiles due to various reasons.
What are some privacy settings that can restrict friend requests on Facebook?
Users can set their profile to private or restricted, limiting who can send them friend requests. Some users only allow friends of friends to add them.
Why can’t I add a friend on Facebook even if we have mutual friends?
If a user has set their friend request setting to “Friends of friends,” only people who are friends with their existing friends can send them a friend request.
Why did my friend request on Facebook get denied or marked as spam?
Various reasons can lead to friend requests being denied or marked as spam, such as the recipient not recognizing you, sending too many requests in a short time, or being flagged for suspicious activity.
Why can’t I add more friends on Facebook?
The “Add Friend” button may not be visible if the user has reached the friend limit of 5,000 or if they have been blocked from sending friend requests.
How can I solve the issue of not being able to add a friend on Facebook?
Solutions include adjusting privacy settings to allow friend requests from everyone, unfriending inactive accounts to make room for new requests, sending a message to inquire about the request, or waiting for a response. | __label__pos | 0.787073 |
node.js – 使用express来焊接?
我是node.js的新手,尝试使用焊接在服务器端渲染模板,并使用express作为路由器。
然而,node.js的例子并没有显示为内容提供服务,并且模糊了如何使用express:
var fs = require('fs'), jsdom = require('jsdom'); jsdom.env( './test.html', ['./jquery.js', './weld.js'], function(errors, window) { var data = [{ name: 'hij1nx', title : 'code slayer' }, { name: 'tmpvar', title : 'code pimp' }]; window.weld(window.$('.contact')[0], data); } );
帮助或例子,将不胜感激。
网上收集的解决方案 "node.js – 使用express来焊接?"
我认为这样的事情会起作用。 还没有testing过。
var fs = require('fs'), jsdom = require('jsdom'), app = require('express').createServer(); app.get('/', function(req, res) { jsdom.env('./test.html', ['./jquery.js', './weld.js'], function(errors, window) { var data = [{ name : 'hij1nx', title : 'code slayer' }, { name : 'tmpvar', title : 'code pimp' }]; window.weld(window.$('.contact')[0], data); res.send(window.document.innerHTML); //after the welding part we just send the innerHTML window.close(); // to prevent memory leaks of JSDOM }); }); app.listen(3001); | __label__pos | 0.993222 |
Sender not authorized to use method
when dfx deploy canister into gw.dfinity.network error show follows:
The Replica returned an error: code 3, message: “Sender not authorized to use method.”
Wallet canisters on tungsten may only be created by an administrator.
Which version of dfx are you using?
dfx --version
Can you share the canister code or dfx.json that you’re trying to deploy?
0.6.26 if set --network ic show errors:
The Replica returned an error: code 1, message: “Canister 5demk-laaaa-aaaab-abbna-cai with memory allocation 10MiB cannot be installed because the Subnet’s remaining memory capacity is 0MiB”
Wallet canisters on ic may only be created by an administrator.
Please submit your Principal (“dfx identity get-principal”) in the intake form to have one created for you.
the other error :slightly_smiling_face:
The replica returned an HTTP Error: Http Error: status 413 Payload Too Large, content type “text/plain; charset=UTF-8”, content: Request 0x8feed6ad5cdcd7f7a50cee13c453931dfbe14518624be37b24ae31dcf0feccf4 is too large.
more bug , linkedup_assets dependencies canister A ,A dependencies B ,dfx build --all is ok,but single exec dfx build linkedup_assets case error alias B not found
If you’re running dfx build on individual canisters that have dependencies, you’ll need to declare the dependency canisters in your dfx.json, similar to this: Development workflow: quickly test code modifications - #9 by Ori
Please try using 0.7.0-beta.3:
DFX_VERSION=0.7.0-beta.3 sh -ci "$(curl -fsSL https://sdk.dfinity.org/install.sh )"
1 Like
when import Deque into HashMap
var hashMap = HashMap.HashMap<UserId, Deque>(1, isEq, Principal.hash);
Stderr:
/Users/libaozhong/dfinitly/my_rust_program/linkedup/src/linkedup/database.mo:93.47-93.52: type error [M0029], unbound type Deque
It seems to indicate that the Deque data structure cannot be found in your code.
try:
import Deque "mo:base/Deque";
var hashMap = HashMap.HashMap<UserId, Deque.Deque<T>>(1, isEq, Principal.hash);
when after upgrade dfx version to 0.7.0-beta.3 , import linkedup_assets from “ic:canisters/linkedup_assets” in .js file exec trigger undefine exception,
DFX_VERSION=0.7.0-beta.3 sh
libaozhongdeMacBook-Pro:linkedup libaozhong$ dfx ping ic
The replica returned an HTTP Error: Http Error: status 404 Not Found, content type “”, content: Not Found
Have anyone had a same problem?
all canisters are deployed locally
But server refuses connection, DFX is running
Have you tried using “localhost” instead of the loopback IP address to access the page in your browser?
How are you trying to access your front-end canister?
Like this: http://127.0.0.1:8000/?canisterId=ryjl3-tyaaa-aaaaa-aaaba-cai ?
Also check the 8000 port is not in use.
Yes buy the recommended method from Frontend tutorial docs.
Port is not in used. This happens with 0.7.3 beta version. As 0.6.26 has issue with canister memory allocation I can’t rebuild frontend there :confused:
пн, 26 апр. 2021 г., 13:19 Gabriel via Internet Computer Developer Forum <[email protected]>:
both, same error, don’t know why.
here is the clearly says it’s running
a new error now
TransportError
1 Like | __label__pos | 0.812813 |
Learning In Statistics in Rosaryville, Maryland, Prince George’s
1. Know the Importance of Statistics
Statistics is an integral allocation of our daily life. every the industries are using statistics to be active their routine work. For example, in our day to hours of daylight life, we outlook statistics likewise bearing in mind we go for the surgery the doctor tell us what would be the help or side effects of the particular surgery.
On the new hand, we daily watch the stats greater than the internet as competently as extra channels nearly the employment rate, GDP, crime rate and appropriately on. There are profusion of examples which we have seen our day to daylight life.
Read Also :
See as a consequence easy Formula Steps on How to Calculate Common Stock
From this point, you may be adept to understand why statistics is crucial for us. And why you obsession to examination statistics. The number of students always have a doubt that why to learn statistics. This dwindling will back them to make certain nearly why statistics is important.
Work upon getting hold of knowledge of statistics: After getting know what is statistics. This is the become old to play upon getting hold of the knowledge of statistics.
There are plenty of resources comprehensible higher than the internet and offline that will encourage you to get a deep knowledge of statistics. You can along with gain statistics knowledge in imitation of the back up of a statistics book.
There are a number of books that will help you to learn statistics from basic to the avant-garde level.
2. Learn the terms most often used in statistical analysis.
Mode
It is the set of data values that appear most often in a answer dataset. Suppose that if in a data set the x is a discrete random variable, then the mode of x will be the probability addition statute that is having the maximum value.
Median
It is the simplest take action of central tendency. We arrange the observation from the smallest to the largest value to locate the medium of the unlimited data set. In raid of the unusual number of clarification in a total data set later the center value automatically become the median. In war of even number of observations, the sum of two middle values become the median.
See furthermore {} What Are The 4 proceedings Of Variability | A unmovable Guide
Standard Deviation
Standard anomaly is all just about the proceed that is used to quantify the amount of variation of a set of data values.
Distribution
Distribution of statistical data sets (or populations) is a list of act out that represents all practicable values (or intervals) of data and how often it occurs. in the manner of the distribution of hierarchical data is conducted, you see the number or percentage of individuals in each group.
Bell-shaped curve
An asymmetrical bell-shaped curve that represents the distribution of values, frequencies, or possibilities of a set of data. Gaussian or general distribution is the usually mathematically well-defined vine curve in statistics and in science.
Probability
The probability distribution is a table or an equation that connects each upshot of a statistical experiment to the probability of an event. believe to be a simple experiment in which we flip a coin twice. Suppose random adaptable X is defined as the result of two coins.
Outliers
For example, the farthest lessening in the above figure is external. A convenient definition of an uncovered is a point that is 1.5 get older later than the interquartile range above or below the first quartile. There can plus be out growth in imitation of comparing contact between two sets of data.
3. begin applying them to unmemorable life
The best artifice to learn whatever is from applying it in real life. You can furthermore learn statistics by applying it in your day to daylight life. You can apply various statistics in your daily moving picture to create hermetically sealed decisions. In fact, statistics will urge on you to spend your child maintenance more effectively. You can plus get various statistics from newspapers, media, politics and sports.
See as well as {} The Definitive lead on Margin of mistake in Statistics
4. Learn not quite statistics from what people telling you and asking them questions
Statistics is one of the toughest subjects for anyone. Whether you are an intelligent student or an average one. with you acquire into statistics class. later you can learn statistics more effectively by asking the question from your mentor.
You should as well as focus on what your mentor is teaching to you. It is the best and most committed quirk to learn statistics. Your little attention can help you to have a bigger command higher than statistics.
5. locate some software that will back up you verbal abuse a unchangeable set of values
Statistics software are plus playing crucial in learning statistics. This software helps you to shout abuse data more easily later you do manually.
There are great quantity of commands assigned in that software to measure some predefined statistics function. If you have some basic knowledge virtually statistics next it would back up you can play in these statistics tools easily and even learn more roughly statistics following these tools.
Tips to find Out The Best Statistics Assignment Helper
See next {} How realize You insinuation Your Statistics Assignment in APA
1. say you will the assist of the internet
Internet is full of resources; there are great quantity of websites that pay for you the best statistics assignment help. hence how can your internet urge on you to choose the right statistics assignment encourage services?
You should see for those sites which are having good reviews. These sites usually manage to pay for the best statistics assignment help. try to avoid the low-quality sites that find the money for the incorrect answers for your statistics questions. A fine character assignment help sites back up you to acquire excellent grades from your teacher.
Learning In Statistics in Rosaryville, Maryland, Prince George’s
2. Analyzing the featured examples in the site
This is one of the most excellent ways to pick the right one. You should have a see at the featured examples that have mentioned on the site. These examples urge on you to analyze the action of the sites.
These examples let you know the reply that has been achieved by solving the puzzling difficulty of statistics question. From that, you can have the idea of how effectively the particular assignment helpers can solve the perplexing problems.
3. get The help From Statistics Experts Sites
Sometimes the students solve the profound statistics questions. They try their best but dont get the desired answer. If they get the answer to the problem, but the answer may not be cleared in their mind. In this way, they can email the statistics experts to solve their problem.
See as a consequence {} How to locate the Best Online Statistics Homework Help
These experts usually mastered the topic and can lead you to solve the obscure problems speedily and distinct all your doubts on the solutions. occupy keep in mind that dont just concede your ask to them and get an reply from them. otherwise of this, entertain attempt to learn each step that is used to find the respond to your statistics assignment questions.
4. take The support From The Apps
Some sites have taken their assignment support services to the neighboring level. They are the apps beyond the internet that help the students to acquire the best statistics assignment back without visiting the website. In some cases, the apps are a lot better than the site.
The students can easily concede their assignment and create payments securely bearing in mind the help of this excellent app. In some apps, the assignment assist provider gives the capability of the sites calculator.
This calculator helps you to acquire the fast results of your statistics question. once the help of this feature, you can get an idea that a particular app is right for you or not.
5. get The help Form alive Mentors
In some of the site, you can find the mentor live for you to solve all your statistics assignment questions. Here you need to pay some charges to have the session with the mentor.
See then {} top 8 reasons why one should learn statistics for robot learning
But I would in the same way as to suggest that you should have a procedures of their sessions. Some of the sites present 5 minutes procedures session. In these measures session, the students to ensure that the experts teaching them are credited passable to teach them.
If the students acquire satisfied, they can avail their services and solve all their statistics assignment united queries in the
SPSS Vs Excel. Which is the best Tools
SPSS vs Excel is always a big issue amongst statistics students mind. Today I am going to allocation in the manner of you the best ever comparison along with SPSS vs Excel.
SPSS
SPSS Stands for statistical packages for Social Science. It is the make public leader in terms of statistical packaging tools. There are several uses of SPSS that are considered as the derivative for data molest and storage. It is having two methods for batch processing, i.e., interactive batches and noninteractive batches.
SPSS inc developed it, but future on, it was acquired by IBM in 2009. The earlier reveal of SPSS was under the umbrella. But after acquiring by IBM, SPSS was renamed as IBM SPSS in 2015.
SPSS as well as comes past an open-source savings account that is known as PSPP. This relation has used the process of statistics and the formulation of data foul language techniques in imitation of totally few exceptions. These statistics and formulation are used for the professional call names of large data chunks.The open-source checking account of SPSS is quite decent, and it wont expire in the future.
Anyone can use the similar SPSS software for the lifetime. SPSS is one of the best diagnostic software that provides high-quality graphics for more investigative features.
The best portion of this software is gone you create adequate graphics in this software. after that you can output the graphics as HTML5 files. It means that you can entrance these files through your browser too.
Excel
Excel is one of the most powerful and easy to use statistics software. It allows you to amassing the data in tabular format, i.e., in rows and column format. It moreover allows you to interact afterward your data in various ways.
You can sort and filter the data using some of the most potent formulas. The pivot tables one is the best feature of Excel. You can use pivot tables to create a new insight by manipulating the data.
See furthermore {} Tableau vs Spotfire | Which One is greater than before For You And Why?
Excel has various features that can support you later than statistics. There are multiple ways to importing and exporting the data. You can as well as mingle the data into the workflow.
Like no extra statistics software, Excel allows you to make the custom acquit yourself using its programming abilities.
The primary objective of Excel is to make archives of data and to treat badly the data as per the users demands. As mentioned earlier, Excel allows you to use the outdoor database to analyze, make reports, and consequently on.
Now a day, Excel is offering the best graphical user interface along in the same way as the use of graphics tools and visualization techniques.
Statistics vs Machine Learning: Which is More Powerful
Statistic
Statistics is all approximately the examination of collection, analysis, interpretation, presentation, and government of data. Whenever we use statistics in scientific, and industrial problem, we begin the process by deciding a statistical model process.
Statistics plays a crucial role in human activity. It means that similar to the incite of statistics, we can track human activities. It helps us in deciding the per capita income of the country, the employment rate, and much more. In supplementary words, statistics support us to conclude from the data we have collected.
Learning In Statistics
Machine learning
Machine learning is the well ahead technology. It is developing at a brusque pace. During the last few years, machine learning has reached the neighboring level. It is used in various fields with fraud detection, web search results, real-time ads on web pages and mobile devices, image recognition, robotics, and many additional areas.
Machine learning is a part of computer science. It has been evolved from the testing of computational learning and theory in exaggerated intelligence. machine Learning feat taking into account AI. In further words, machine learning gives the ability to the computers to learn further things subsequent to the support of some programs.
Machine learning is along with cooperative to create predictions upon data. It constructs some algorithms that are operated by a model creation, and it is used to create data-driven predictions. robot learning has played a crucial role in the functionality of human society.
Difference amongst Statistics vs machine Learning
Nowadays, data is the key to capability for the business. But data is forever shifting and evolving at a rushed pace. hence the concern needs some techniques to convert the raw data into essential one. For this they agree to help of robot learning and statistics.
See along with {} What is Bias in Statistics? Its Definition and Types
Data is collected in the management from mysterious operations. The companies always need to convert the data into valuable data; otherwise, the data is no more than the garbage.
Industries using statistics
Almost all industry use the statistics. Because without statistics, we cant get the conclusion from the data. Nowadays, statistics is crucial for various fields later eCommerce, trade, psychology, chemistry, and much more.
Business
Statistics is one of the significant aspects of companies. It is playing a crucial role in the industry. Nowadays, the world is becoming more competitive than ever before.
It is becoming more hard for the issue to stay in the competition. They craving to meet the customers desires and expectations. It can forlorn happen if the company takes quick and improved decisions.
So how can they pull off so? Statistics function a crucial role in understanding the desires and expectations of the customers. It is, therefore, important that brands agree to quick decisions in view of that that they can make better decisions. Statistics meet the expense of useful insights to make smarter decisions.
Economics
Statistics is the base of Economics. It is playing a crucial role in economics. National income savings account is critical indicators for economists. There are various statistics methods appear in on the data to analyze it.
Statistics is then long-suffering in defining the link surrounded by demand and supply. It is after that required in as regards all aspect of economics.
Mathematics
Statistics is furthermore an integrated allocation of mathematics. Statistics encourage in describing measurements in a truthful manner.
Mathematicians frequently use statistical methods afterward probability averages, dispersions, estimation. all these are moreover an integral ration of mathematics.
Banking
Statistics plays an necessary ration in the banking sector. Banks require statistics for the number of stand-in reasons. The banks play upon conclusive phenomena. Someone deposits their grant in the bank.
Then the banker estimates that the depositor will not sit on the fence their maintenance during a period. They in addition to use statistics to invest the maintenance of the depositor into the funds. It helps the banks to make their profit. {}
State Management
Statistics is an critical aspect of the enhancement of the country. Statistical data is widely used to believe administrative level decisions. Statistics is crucial for the government to achievement its duties efficiently.
Industries using robot learning
The increase of computer and technologies has produced robot learning. machine learning has untouched the pretentiousness we flesh and blood our lives. There are lots of industries which are using machine learning.
Google is using machine learning in their self-driven cars. Netflix is one of the most excellent examples of machine learning technologies. Netflix is using robot learning to personalize the content for its customers.
It analyzes human actions and subsequently provides the best-matched content to the customer. machine learning is afterward helpful in fraud detection, and it helps the brands to be safe in almost every platform.
Machine learning is getting more well-liked because the data is along with growing at a unexpected pace. It allows us to analyze the deafening amount of data in less become old and low cost behind the back up of powerful data analysis methods. It helps us to speedily build models that can analyze the colossal amount of data and focus on faster solutions, even upon a large scale.
See moreover {} Excel VS Numbers: Which One Makes You Smart
Business
Brands are using robot learning to create various models to inspect their performance. machine learning allows the brands to create thousands of model in a week.
It is making the brands more operating and better for the long term. machine learning also offers various data techniques that are quite helpful for the concern to meet the needs of brands in on all sector.
It is making the brands more functional and enlarged for the long term. machine learning furthermore offers various data techniques that are quite compliant for the matter to meet the needs of brands in approximately every sector.
Decision Making
Machine learning is along with helpful in decision making. It helps to reproduce the known patterns and knowledge.
These patterns automatically applied to the data we have collected from various sources. for that reason it helps the concerned people to assume improved decision and actions.
Neural Networks
Neural networks were used for data mining applications. But after the spread of robot learning, it is viable to make complex neural networks that are having many layers. {} {}
Statistics vs robot Learning
They belong to stand-in schools
Machine Learning
Machine learning is a subset of computer science and artificial intelligence. It harmony with building a system that can learn from the data on the other hand of learning from the pre-programmed instructions.
Statistical Modelling
Statistics is a subset of mathematics. It deals following finding the connection between variables to predict the outcome. {}
They came going on in alternating eras
Statistics is quite older than robot learning. upon the supplementary hand, robot learning got into existence a few years ago. robot learning comes into existence in the 1990s, but it was not getting that much popular.
But after the computing becomes cheaper, subsequently the data scientist moves into the enhance of robot learning. The number of growing data and mysteriousness of big data has increased the infatuation for robot learning. {} {}
See with {} Learn more or less Excel & Topics of Excel Assignment For Students
The extent of assumptions involved
Statistics modeling is used to con on several assumptions. Here are the few examples of linear regression assumes.
The linear tally amongst the independent and dependent variable
Homoscedasticity
For all dependent value point toward of mistake at zero.
Observations of independence.
normally distribution of error for each value of the dependent variable
On the new machine Learning algorithms get consent a few of these things. But in general, are spared from most of these assumptions.
We plus infatuation not specify the distribution of the dependent or independent modifiable in a robot learning algorithm.
Head-to-Head Comparison of Python vs Matlab
What is Python?
Python is a general-purpose programming language. You can control Python on any platform. It means Python is platform-independent. It is offering the most handy syntax, which means you can code easily within this programming language.
Apart from that, if someone extra than works on your Python code, after that they can easily gate and improve the code. It is the most significant language of the subsequent to decade, and you compulsion to write a few lines of code as compared later than Java and C++ to affect any task. ( Python Coding help )
Python is written in portable ANSI C. for that reason that you compile and govern the code upon any practicing system, including Mac OS, Windows, Linux, and many more. It works similarly upon all the platforms. Python allows you the adaptableness to code in a infected environment. {}
Python is a high-level programming language, and it is unconditionally same to MATLAB. It provides functioning typing and automatic memory management; as I mentioned earlier, Python offers the most comprehensible syntax. It means that you can easily convert your ideas into a coding language.
If you have Pythons clear license, you will get the libraries, lists, and dictionaries. It helps you to achieve resolution goals in a well-organized way. It also works in the same way as a variety of modules that support you to begin speedily once Python.
See afterward {} summit 3 Most Prominent Ways for Python String Compare
Advantages of Python:
Execution by end-to-end development.
Open-source packages( Pandas, Numpy, Scipy).
Packages of Trading(zipline, Pybacktest, Pyalgotrade).
Most prominent language for general programming and application development.
Can proceed subsequent to further languages to be next to R, C++, and others (Python).
Fastest general-purpose language, especially in iterative loops.Fastest general speed, especially in iterative loops.
Disadvantages of Python:
Immature trading packages.
All packages are not compatible once each other smaller communities as compared later than further languages.
Python is Slow at Runtime.
What is Matlab?
MATLAB is a high-level programming language. MATLAB stands for Matrix Laboratory. Thats why it is considered the powerful obscure language for mathematical programming.
It is offering the best mathematical and graphical packages along once various built-in tools for problem-solving. You can as well as manufacture the graphics illustrations using MATLAB. MATLAB is one of the oldest programming languages in the world. It was developed in the late 1970s by Cleve Moler.
Some experts with decide it as a successor of FORTON. In the further on days of MATLAB, it was an interfacing software for easy entry to Forton libraries for numerical computing without the assist of FORTON.
In the year 1983, the GUI bank account of MATLAB was introduced by John Little, Cleve Moler, and Steve Bangert. After rewriting the MATLAB code in C in the year 1984, to the formation of MathWorks. Nowadays, MATLAB has become the agreeable for data analysis, numerical analysis, and graphical visualization.
Advantages of Matlab:
Fastest computational and mathematical platform.
Primarily linear matrix algebra packages for every fields of mathematics and trading at the commercial level.
Integration of all packages with a concise script.
Most involved and startling visualisation of plots and interactive charts
As a billboard product, it is capably tested and supported providing multi-threaded hold and trash accretion effectively.
Disadvantages of Matlab:
Matlab is an interpreted language and therefore it takes more get older to execute.
Impossible to Can kill for execution, you must translate it into other language.
The suffering of integration is solved in imitation of other languages.
It is quite hard to detect biases in trading systems. For this, extensive investigation is required.
Iterative loops function worse in MATLAB.
Not adept of developing stand-alone applications.
Difference Between R and Python Language?
R vs Python is one of the most common but important questions asked by lots of data science students. We know that R and Python, both are open source programming languages. Both of these languages are having a large community. Apart from that, these languages are developing continuously.
Thats the explanation these languages build up supplementary libraries and tools to their catalog. The major take aim of using R is for statistical analysis, while Python provides a more general data science approach.
Both languages are state-of-the-art programming languages for data science. Python is one of the simplest programming languages in terms of its syntax.
Thats why any beginner in a programming language can learn Python without putting in the further effort. on the new hand, R is built by statisticians that are a tiny bit hard to master.
Check the under mentioned stats of user allegiance for Python and R.
Before distressing to the difference, lets see at some stats that back up you understand why both programming languages are popular or best to learn.
Now we have edit some basic differences in the company of R vs Python. But this is not the end of the difference along with these two languages. There is a lot more to learn about the comparison amid R vs Python. Here we go:-
What is R?
R is one of the oldest programming languages developed by academics and statisticians. R comes into existence in the year 1995. Now R is providing the richest ecosystem for data analysis.
The R programming language is full of libraries. There are a couple of repositories furthermore approachable in the same way as R. In fact, CRAN has re 12000 packages. The broad variety of libraries makes it the first unconventional for statistical analysis and logical work.
Consists of packages for regarding any statistical application one can think of. CRAN currently hosts more than 10k packages.
Equipped past excellent visualization libraries considering ggplot2.
Capable of standalone analyses.
What is Python?
On the further hand, Python can get the thesame tasks as the R programming language does. The major features of Python are data wrangling, engineering, web scraping, and appropriately on. Python next has the tools that encourage in implementing robot learning on a large scale.
Guido van Rossum developed Python in 1991. Python is the most well-liked programming language in the world. Python is one of the simplest languages to maintain, and it is more robust than R. Now a hours of daylight Python has the cutting edge API. This API is quite cooperative in machine learning and AI.
Most data scientists use deserted five Python libraries, i.e., Numpy, Pandas, Scipy, Scikit-learn, and Seaborn.
Object-oriented language
General Purpose
Has a lot of extensions and amazing community support
Simple and simple to understand and learn
Packages like pandas, NumPy, and sci-kit-learn, create Python an excellent unorthodox for machine learning activities.
R or Python Usage
Python has the most potent libraries for math, statistics, unnatural intelligence, and robot learning. But still, Python is not useful for econometrics and communication and with for thing analytics.
On the additional hand, R is developed by academics and scientists. It is specially intended for robot learning and data science. R has the most potent communication libraries that are quite compliant in data science. In addition, R is equipped in the manner of many packages that are used to play data mining and become old series analysis.
Lets get a brief detail about the archives of both programming languages!
ABC -> Python was Invented (1989 Guido van Rossum) -> Python 2 (2000) came into existence -> Python 3 (2008) modifies.
Fortran -> S (at siren Labs) -> R was Invented (1991 by Ross Ihaka and Robert Gentleman) -> R 1.0.0 (2000) came into existence -> R 3.0.2 (2013).
See plus {} The Best lead upon the Comparison in the company of SPSS vs SAS
Why should we not use both of these languages at the thesame time?
Heaps of people think that they can use both programming languages at the similar time. But we should prevent using them at the thesame time. The majority of people are using forlorn one of these programming languages. But they always want to have access to the capability of the language adversary.
For example, if you use both languages at the similar time, that may approach some of the problems. If you use R and you want to acquit yourself some object-oriented function, after that you cant use it on R.
On the supplementary hand, Python is not conventional for statistical distributions. so that they should not use both languages at the thesame times because there is a mismatch of their functions.
But there are some ways that will urge on you to use both of these languages past one another. We will talk roughly them in our adjacent blog. Lets have a look at the comparison amid R vs Python. | __label__pos | 0.705687 |
DACTL
A generalized computational model based on graph rewriting is presented along with Dactl, an associated compiler target (intermediate) language. An illustration of the capability of graph rewriting to model a variety of computational formalisms is presented by showing how some examples written originally in a number of languages can be described as graph rewriting transformations using Dactl notation. This is followed by a formal presentation of the Dactl model before giving a formal definition of the syntax and semantics of the language. Some implementation issues are also discussed.
References in zbMATH (referenced in 28 articles , 1 standard article )
Showing results 1 to 20 of 28.
Sorted by year (citations)
1 2 next
1. Danvy, Olivier; Zerny, Ian: Three syntactic theories for combinatory graph reduction (2011)
2. Echahed, Rachid: On term-graph rewrite strategies. (2008)
3. Crégut, Pierre: Strongly reducing variants of the Krivine abstract machine (2007)
4. Duval, Dominique; Echahed, Rachid; Prost, Frédéric: Modeling pointer redirection as cyclic term-graph rewriting. (2007)
5. Sinot, François-Régis; Mackie, Ian: Macros for interaction nets: A conservative extension of interaction nets. (2005)
6. Drewes, Frank; Hoffmann, Berthold; Plump, Detlef: Hierarchical graph transformation (2002)
7. Habel, Annegret; Plump, Detlef: Computational completeness of programming languages based on graph transformation (2001)
8. Panangaden, P.; Verbrugge, C.: Generating irregular partitionable data structures (2000)
9. Andries, Marc; Engels, Gregor; Habel, Annegret; Hoffmann, Berthold; Kreowski, Hans-Jörg; Kuske, Sabine; Plump, Detlef; Schürr, Andy; Taentzer, Gabriele: Graph transformation for specification and programming (1999)
10. Kreowski, Hans-Jörg; Kuske, Sabine: Graph transformation units with interleaving semantics (1999)
11. Banach, R.: MONSTR I -- Fundamental issues and the design of MONSTR (1998)
12. Banach, R.: MONSTR II -- suspending semantics and independence (1997)
13. Fu, James Jianghai: Directed graph pattern matching and topological embedding (1997)
14. Glauert, John: Object graph rewriting: An experimental parallel implementation (1997)
15. Ariola, Zena M.: Relating graph and term rewriting via Böhm models (1996)
16. Banach, R.: Transitive term graph rewriting (1996)
17. Ariola, Zena M.; Arvind: Properties of a first-order functional language with sharing (1995)
18. Shand, Duncan; Brock, Simon: Proofs as graphs. (1995)
19. Sleep, M.Ronan: SEMAGRAPH: The theory and practice of term graph rewriting. (1995)
20. Banach, R.: Term graph rewriting and garbage collection using opfibrations (1994)
1 2 next | __label__pos | 0.720201 |
HTML
HTML
HTML Forms – Defination and Usage
The HTML <form> element defines a form to take information from users. Forms are the important elements of a webpage or website. You usually see a contact form or a subscription form on every website. Contact form generally have three important inputs like Name,Email or Message and subscription form generally have only one or two field like Name and Email. So these all are inputs from the user of website.
HTML form is used to collect information from user. Lets take an example of most used social network Facebook. When we login into Facebook, we first enter username and password. These username and password elements are the part of HTML Form. They collect our information to authenticate and get our account information.
In this post we will explain how these forms are created or you can say how to use HTML <form> tag to take information from user.Its start tag is <form> and end tag is </form>. So lets create our first form and we will add input elements one by one.
Form <input> Element
The <input> element is the most important form element. The <input> element can be displayed in several ways, depending on the type attribute. We add <input> elements to our form with different type attribute.
<h2>HTML Form</h2>
<form>
<input type="text" name="a" placeholder="Text">
<input type="number" name="b" placeholder="Number">
</form>
We added a form to our page and three input elements with different type attributes. Now when we open the page in browser we will get this :
Explaination: We added three input elements. First input element has type attribute “text” , so we can type anything in this field Number,Alphabets and Symbols. And second input element has type attribute “number” , so we can type only number in this field.
In HTML5 ,we have a long list of these type attribute.
• color
• date
• datetime
• email
• month
• number
• range
• search
• tel
• time
• url
• week
So we can assign any of these attribute value for type as per our desired input. Try with these type attributes and make your first form.
Input Radio
This is something different from normal input elements. Here we provide some options for user to choose from them. Lets say when we want to ask about gender from user. We give the option to choose from Male or Female. So for these types of form element we use type attribute radio .To make a group of option we have to give same name attribute to all options input. Example :
<form>
Gender:
<input type='radio' name='gender' value='male'>Male
<input type='radio' name='gender' value='female'>Female
</form>
Output of above code:
Gender:
Male
Female
Note: We have already assigned value to input radio elements because we are not taking value from users .We are just showing options to users to choose from. Name attribute should be same for all options to select only one out of all.
Input Checkbox
In some cases, user may have option to choose more than one option. In that situation we will use checkbox instead of radio buttons. Here user can choose multiple options at same time. This type of element is called checkbox. As user can choose multiple options ,so there is no need to make group by assigning same name. Example :
<form>
Hobbies :
<input type='checkbox' name='checkbox1' value='Reading'>Reading Books
<input type='checkbox' name='checkbox2' value='music'>Listening To Music
<input type='checkbox' name='checkbox3' value='cricket'>Playing Cricket
</form>
Output of above code:
Hobbies :
Reading Books
Listening To Music
Playing CricketNote: On clicking checkbox ,it will be marked as checked. So values which are checked will be accepted as user’s choice.
Form <select> Element
Form <select> element functioning is same as of <input> element type radio but when the list of options is very long then <select> element is used not the radio button. Form <select> element create a drop-down list of options and user can select his option from the list. As usually choose country whenever you register on an social network site. List of countries is so long that we can’t give radio buttons to choose from them. So we use <select> element there. Here is the expample to create a <select> element :
<form>
Your Country
<select name='country'>
<option>India</option>
<option>US</option>
<option>Australia</option>
<option>Russia</option>
<option>Canada</option>
</select>
</form>
Output of above code is :
Your Country
Explaination: For <select> element ,we create list items or options with <option> tag. All the options are inclosed in <option> tag with starting tag as <option> and closing tag as </option>.
Form <textarea> Element
All the above explained elements take a small input as name,email ,mobile etc. But we need a long text input in our form for bigger inputs from users like any message, description or feedback. So we have one more element for long inputs that is called textarea. The <textarea> element is multi-line, it has attribute of ‘rows’ and ‘cols’. Rows set lines of input area and cols set the width of input area. Lets create a textarea :
<form >
Message
<textarea name='message' rows='5' cols='8' ></textarea>
</form>
Output:
Message
Form Reset Button
Mostly in form we have a reset button. This reset button don’t do anything special but just clear all filled values from input elements. Means if someone want to reset the form he don’t need to refresh page , just reset button do it easily. Reset button is added as :
<form>
<input type='text' name='name' value='' placeholder='name'>
<input type='reset' name='reset' value='reset'>
</form>
Output:
Explaination: I have created a from with one input for name and a reset button. Just enter something into input and press ‘Reset’ button. Filled value will be cleared.
Form Submit Button
Mostly in form we have a reset button. This reset button don’t do anything special but just clear all filled values from input elements. Means if someone want to reset the form he don’t need to refresh page , just reset button do it easily. Reset button is added as :
<form action='form-submit.php' method='post'>
<input type='text' name='name' value='' placeholder='name'>
<input type='submit' name='reset' value='Submit'>
</form>
Output:
Explaination: I have created a from with one input for name and a Submit button. When you press the submit button it will send all filled values to the page assigned in form ‘action’ attribute. Action attribute is important attribute of a form. This defines the page where all form data will be sent.
This is all about the HTML Form. We have described all of its elements , so we can create a form in html easily. This all was about designing. For functioning like how we get and use submitted data, we will create a new post in PHP. For any doubt and question comment below. Thank You. Keep coding.
Subscribe To Our Newsletter
Facebook By Weblizar Powered By Weblizar
View Comments
There are currently no comments.
15 − 11 = | __label__pos | 0.870159 |
Graphing Parallel and Perpendicular Lines (Day 2 of 2)
37 teachers like this lesson
Print Lesson
Objective
SWBAT write the equation of lines that are parallel and perpendicular.
Big Idea
Students will connect the main ideas from the previous four lessons to write the equations of parallel and perpendicular lines using given information.
Do-Now
10 minutes
Students will complete the Do Now in 5 minutes.
The aim of this Do-Now is to remind students of how the presence of a negative sign changes an equation. The Do-Now and today's lesson both allow students to practice MP6, as students will be solving equations and must pay special attention to accuracy.
We will review the answers to the Do-Now aloud. I will ask students to score their own paper.
Next, a student will read the objective: "SWBAT write the equation of lines that are parallel and perpendicular."
Guided Notes + Practice
40 minutes
We will open up class using this graphic organizer.
As a review from our last class, I will ask students to write the equations of the four colored lines on the top of their paper. Then, I will ask students to underline the slope of each line.
• Underneath the first graph students will write: Parallel lines have the same slope.
• Underneath the second graph students will write: Perpendicular lines have opposite reciprocal slopes.
Students will then practice finding the opposite reciprocal of a number.
Next, we will complete the first example. I will call on a student volunteer to read the prompt to the class. I found it helpful for students to create a list underneath of the example problem to help organize their thoughts and to help them comprehend what each question is asking.
• Find the equation of a line that is parallel to y = 2x + 5, and that passes through the point (-1, -1).
• Line One: y = 2x + 5
• Line Two: ???? ( We don't know know the equation of line two)
I will use the following prompts to guide students to creating their own equation:
• "Our goal is to find the equation of a new line, Line Two, that fits specific criteria."
• "What are the rules that Line Two must follow?"
• "Do we know any values for Line Two now?"
• "Why does Line Two have to have a slope of 2?"
• "Do we know anything else about Line Two?"
• "How can we figure out the equation of a line using what we have?"
Students will then solve for b and create the equation of a the line y = 2x + 1. Students will use the graph on their paper to check their answer.
Lastly, Students will use what they have learned to write the equations of parallel and perpendicular lines by completing this assignment. I will encourage students to check their responses by graphing the equations that they create on a separate piece of graph paper.
Partner Activity
20 minutes
The class will complete the Rectangle Investigation individually or with a partner. In this activity students will be asked to graph several equations using colored pencils. Students will then analyze the slope of each equation to answer questions relating to the rectangle that is formed by the intersecting lines.
Instructional Note: Students will need colored pencils to complete this activity
Closing
10 minutes
Two volunteers will give a short summary about what we learned in class today. I will then ask students to describe how they can use a coordinate plane to check their answers when graphing equations of a line that are parallel and perpendicular. Students will then complete an exit card. The exit cards should be graded directly after class, and the students should then be grouped by the percentage of correct questions for the review during our next class. | __label__pos | 0.998385 |
Working with System.Char in X++
There are situations where it is useful to workl with characters in X++. As you know, X++ does not have the concept of characters in the defined in the language: Only strings are defined. However, it is not impossible to work with characters in X++, if you use the managed System.Char type. It will not win any prizes for elegance, but it works…
Consider the following example:
static void CharArray(Args _args)
{
System.Char[] chars;
System.Char a, b;
a = System.Char::Parse(‘a’);
b = System.Char::Parse(‘b’);
chars = new System.Char[2]();
chars.SetValue(a, 0);
chars.SetValue(b, 1);
}
Here an array containing to chars is created, and assigned the values {‘a’, ‘b’}. Note the special trick used to create a character literal, using the System.Char::Parse method.
Comments (0)
Skip to main content | __label__pos | 0.924886 |
bt_gatt_read() multiply read #bluetooth #nrf52840
antonsolonovich@...
Hello,
I use nrf52840-dk as central_hr and nrf52833-dk as peripheral_hr, examples from NRF Connect SDK.
I want to read two or more values using bt_gatt_read().
Code:
dis->read_params.func = gatt_read_cb;
dis->read_params.handle_count = 2;
dis->read_params.handles = dis_handles;
err = bt_gatt_read(dis->conn, &(dis->read_params));
I read two values,
BT_UUID_DIS_MODEL_NUMBER, which is "Model"
and BT_UUID_DIS_SERIAL_NUMBER, with value "serial"
Here you can see part of my log,
gatt read cb // We are in callback
data length 11 //One length for two values?
data = Modelserial //Don't understand how to split it
gatt read cb //Extra callback with zero length? Does it mean that reading finished?
data length 0
empty data
The problem is that in multiply read I get one callback and one length for all values,
and I don't understand how to split it, and what value for what characteristic is.
Also I've asked it on DevZone
https://devzone.nordicsemi.com/f/nordic-q-a/77045/discovery-dis
but no success there
Thank you,
Anton | __label__pos | 0.773227 |
phpDocumentor updates
[squirrelmail.git] / src / help.php
1 <?php
2
3 /**
4 * help.php
5 *
6 * Displays help for the user
7 *
8 * @copyright © 1999-2005 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @version $Id$
11 * @package squirrelmail
12 */
13
14 /**
15 * Path for SquirrelMail required files.
16 * @ignore
17 */
18 define('SM_PATH','../');
19
20 /* SquirrelMail required files. */
21 require_once(SM_PATH . 'include/validate.php');
22 require_once(SM_PATH . 'functions/global.php');
23 require_once(SM_PATH . 'functions/display_messages.php');
24
25 displayPageHeader($color, 'None' );
26
27 $helpdir[0] = 'basic.hlp';
28 $helpdir[1] = 'main_folder.hlp';
29 $helpdir[2] = 'read_mail.hlp';
30 $helpdir[3] = 'compose.hlp';
31 $helpdir[4] = 'addresses.hlp';
32 $helpdir[5] = 'folders.hlp';
33 $helpdir[6] = 'options.hlp';
34 $helpdir[7] = 'search.hlp';
35 $helpdir[8] = 'FAQ.hlp';
36
37 /****************[ HELP FUNCTIONS ]********************/
38
39 /**
40 * parses through and gets the information from the different documents.
41 * this returns one section at a time. You must keep track of the position
42 * so that it knows where to start to look for the next section.
43 */
44
45 function get_info($doc, $pos) {
46 $ary = array(0,0,0);
47
48 $cntdoc = count($doc);
49
50 for ($n=$pos; $n < $cntdoc; $n++) {
51 if (trim(strtolower($doc[$n])) == '<chapter>'
52 || trim(strtolower($doc[$n])) == '<section>') {
53 for ($n++; $n < $cntdoc
54 && (trim(strtolower($doc[$n])) != '</section>')
55 && (trim(strtolower($doc[$n])) != '</chapter>'); $n++) {
56 if (trim(strtolower($doc[$n])) == '<title>') {
57 $n++;
58 $ary[0] = trim($doc[$n]);
59 }
60 if (trim(strtolower($doc[$n])) == '<description>') {
61 $ary[1] = '';
62 for ($n++;$n < $cntdoc
63 && (trim(strtolower($doc[$n])) != '</description>');
64 $n++) {
65 $ary[1] .= $doc[$n];
66 }
67 }
68 if (trim(strtolower($doc[$n])) == '<summary>') {
69 $ary[2] = '';
70 for ($n++; $n < $cntdoc
71 && (trim(strtolower($doc[$n])) != '</summary>');
72 $n++) {
73 $ary[2] .= $doc[$n];
74 }
75 }
76 }
77 if (isset($ary)) {
78 $ary[3] = $n;
79 } else {
80 $ary[0] = _("ERROR: Help files are not in the right format!");
81 $ary[1] = $ary[0];
82 $ary[2] = $ary[0];
83 }
84 return( $ary );
85 } else if (!trim(strtolower($doc[$n]))) {
86 $ary[0] = '';
87 $ary[1] = '';
88 $ary[2] = '';
89 $ary[3] = $n;
90 }
91 }
92 $ary[0] = _("ERROR: Help files are not in the right format!");
93 $ary[1] = $ary[0];
94 $ary[2] = $ary[0];
95 $ary[3] = $n;
96 return( $ary );
97 }
98
99 /**************[ END HELP FUNCTIONS ]******************/
100
101
102 echo html_tag( 'table',
103 html_tag( 'tr',
104 html_tag( 'td','<center><b>' . _("Help") .'</b></center>', 'center', $color[0] )
105 ) ,
106 'center', '', 'width="95%" cellpadding="1" cellspacing="2" border="0"' );
107
108 do_hook('help_top');
109
110 echo html_tag( 'table', '', 'center', '', 'width="90%" cellpadding="0" cellspacing="10" border="0"' ) .
111 html_tag( 'tr' ) .
112 html_tag( 'td' );
113
114 if (!isset($squirrelmail_language)) {
115 $squirrelmail_language = 'en_US';
116 }
117
118 if (file_exists("../help/$squirrelmail_language")) {
119 $user_language = $squirrelmail_language;
120 } else if (file_exists('../help/en_US')) {
121 echo "<center><font color=\"$color[2]\">"
122 ._("The help has not been translated to the selected language. It will be displayed in English instead.");
123 echo '</font></center><br />';
124 $user_language = 'en_US';
125 } else {
126 error_box( _("Some or all of the help documents are not present!"), $color );
127 exit;
128 }
129
130
131 /* take the chapternumber from the GET-vars,
132 * else see if we can get a relevant chapter from the referer */
133 $chapter = 0;
134
135 if ( sqgetGlobalVar('chapter', $temp, SQ_GET) ) {
136 $chapter = (int) $temp;
137 } elseif ( sqgetGlobalVar('HTTP_REFERER', $temp, SQ_SERVER) ) {
138 $ref = strtolower($temp);
139
140 $contexts = array ( 'src/compose' => 4, 'src/addr' => 5,
141 'src/folders' => 6, 'src/options' => 7, 'src/right_main' => 2,
142 'src/read_body' => 3, 'src/search' => 8 );
143
144 foreach($contexts as $path => $chap) {
145 if(strpos($ref, $path)) {
146 $chapter = $chap;
147 break;
148 }
149 }
150 }
151
152 if ( $chapter == 0 || !isset( $helpdir[$chapter-1] ) ) {
153 echo html_tag( 'table', '', 'center', '', 'cellpadding="0" cellspacing="0" border="0"' ) .
154 html_tag( 'tr' ) .
155 html_tag( 'td' ) .
156 '<center><b>' . _("Table of Contents") . '</b></center><br />';
157 echo html_tag( 'ol' );
158 for ($i=0, $cnt = count($helpdir); $i < $cnt; $i++) {
159 $doc = file("../help/$user_language/$helpdir[$i]");
160 $help_info = get_info($doc, 0);
161 echo '<li><a href="../src/help.php?chapter=' . ($i+1)
162 . '">' . $help_info[0] . '</a>' .
163 html_tag( 'ul', $help_info[2] );
164 }
165 do_hook('help_chapter');
166 echo '</ol></td></tr></table>';
167 } else {
168 $doc = file("../help/$user_language/" . $helpdir[$chapter-1]);
169 $help_info = get_info($doc, 0);
170 echo '<center><small>';
171 if ($chapter <= 1){
172 echo '<font color="' . $color[9] . '">' . _("Previous")
173 . '</font> | ';
174 } else {
175 echo '<a href="../src/help.php?chapter=' . ($chapter-1)
176 . '">' . _("Previous") . '</a> | ';
177 }
178 echo '<a href="../src/help.php">' . _("Table of Contents") . '</a>';
179 if ($chapter >= count($helpdir)){
180 echo ' | <font color="' . $color[9] . '">' . _("Next") . '</font>';
181 } else {
182 echo ' | <a href="../src/help.php?chapter=' . ($chapter+1)
183 . '">' . _("Next") . '</a>';
184 }
185 echo '</small></center><br />';
186
187 echo '<font size="5"><b>' . $chapter . ' - ' . $help_info[0]
188 . '</b></font><br /><br />';
189
190 if (isset($help_info[1]) && $help_info[1]) {
191 echo $help_info[1];
192 } else {
193 echo html_tag( 'p', $help_info[2], 'left' );
194 }
195
196 $section = 0;
197 for ($n = $help_info[3], $cnt = count($doc); $n < $cnt; $n++) {
198 $section++;
199 $help_info = get_info($doc, $n);
200 echo "<b>$chapter.$section - $help_info[0]</b>" .
201 html_tag( 'ul', $help_info[1] );
202 $n = $help_info[3];
203 }
204
205 echo '<br /><center><a href="#pagetop">' . _("Top") . '</a></center>';
206 }
207
208 do_hook('help_bottom');
209
210 echo html_tag( 'tr',
211 html_tag( 'td', ' ', 'left', $color[0] )
212 );
213
214 ?>
215 </table></body></html> | __label__pos | 0.984436 |
脚本二值化过QQ滑块验证【源码分享】
测试设备:雷电模拟器 540*960 dpi 240
基本原理:
把滑块验证图片转化成0和1的二值化图片,也就是黑白图
二值化过QQ滑块验证【源码分享】
原图
二值化过QQ滑块验证【源码分享】
二值化后的图片
然后找滑块序列,匹配成功,就找到滑块位置了
二值化过QQ滑块验证【源码分享】
代码分享:
Dim r,g,b,m,s,y,k,d,GetColor
dim p=0
Dim q=0
KeepCapture
For j= 195 To 479
For i = 21 To 518
GetColor = GetPixelColor(i,j)
ColorToRGB(GetColor,r,g,b)
y=r+g+b
If 384 – y > 50 Then
k =0
Else
k=1
End If
d=d&k
Next
s = InStr(260, d, “100000000000000000000000000000000000000000000000000000000000000001”)
m = InStr(260, d, “10000000000000000000000000000000000000000000000000000000000000001”)
If 0<s<420 Then
p = p + 1
If p = 6 Then
Exit For
End If
End If
If 0<m<420 Then
q = q + 1
If q = 6 Then
Exit For
End If
End If
d=””
Next
ReleaseCapture
TracePrint s,m
If s > m Then
For i = 0 To 5
TracePrint s+21
Next
else
For i = 0 To 5
TracePrint m+21
Next
End If
我在写这个代码的时候,发现每张图的滑块也有差别,一共找到两个滑块序列,所以后期我在代码优化上面做了两个序列值。
相较于我的实战第一课的过滑块方法,这种方法更加便捷,不用获取所有验证图的原图。
同时识别速度很快,不到1秒钟。
原文始发于微信公众号(3分钟学堂):
除特别注明外,本站文章均为原创,转载请注明出处和链接!
本文链接地址: https://pumpkinit.com/988.html
Pumpkin [https://pumpkinit.com] 感谢
发表评论
电子邮件地址不会被公开。 必填项已用*标注 | __label__pos | 0.51301 |
I've found some workaround for floating point problem in PHP:
php.ini setting precision = 14
342349.23 - 341765.07 = 584.15999999992 // floating point problem
php.ini setting, let's say precision = 8
342349.23 - 341765.07 = 584.16 // voila!
Demo: http://codepad.org/r7o086sS
How bad is that?
1. Can I rely on this solution if I need just precise 2 digits calculations (money)?
2. If not can you provide me a clear example when this solutions fails?
Edit: 3. Which php.ini.precision value suits best two digits, money calculations
• Please mind I can't use integer calculations (float*100 = cents), it's far too late for that.
• I am not going to work on numbers higher than 10^6
• I don't need to compare numbers
UPDATE
@Baba answer is good, but he used precision=20, precision=6 in his tests... So still i am not sure is it gonna work or not.
Please consider following:
Let's say precision = 8 and only thing I do is addition + and subtraction -
A + B = C
A - B = C
Question 1: Is precision workaround gonna fail for numbers between 0..999999.99, where A and B is a number with decimal places? If so please provide me an example.
Simple test would do the job:
// if it fails what if I use 9,10,11 ???
// **how to find when it fails??? **
ini_set('precision', 8);
for($a=0;$a<999999.99;$a+=0.01) {
for($b=0;$b<999999.99;$b+=0.01) {
// mind I don't need to test comparision (round($a-$b,2) == ($a-$b))
echo ($a + $b).','.($a - $b)." vs ";
echo round($a + $b, 2).','.round($a - $b, 2)."\n";
}
}
but obviously 99999999 * 2 is too big job so I can't run this test
Question 2: How to estimate/calculate when precision workaround fails? Without such crazy tests? Is there any mathematicial*, straight answer for it? How to calculate is gonna to fail or not?
*i don't need to know floating point calculations works, but when workaround fails if you know precision, and range of A and B
Please mind I really know cents and bcmath are best solution. But still I am not sure is workaround gonna fails or not for substraction and addition
• 7
If you're dealing with 2-digit precision (money), why not use integers instead and divide the final result by 100? – Wiseguy Jan 29 '13 at 16:19
• 1
@Wiseguy Edited my question – Peter Jan 29 '13 at 16:19
• 2
@PLAudet It could be set in an apache vhost with php_value for example... – Michael Berkowski Jan 29 '13 at 16:22
• 2
what about simply using round($value,2) or number_format($value,2) – Pitchinnate Jan 29 '13 at 16:27
• 4
Using integers doesn't help if your app does any division. (Like offering percentage-based price discounts or calculating cost per item for items purchased in bulk.) – Alex Howansky Jan 29 '13 at 17:00
up vote 41 down vote accepted
+750
Introduction
Floating-point arithmetic is considered an esoteric subject by many people. This is rather surprising because floating-point is ubiquitous in computer systems. Most fractional numbers don't have an exact representation as a binary fraction, so there is some rounding going on. A good start is What Every Computer Scientist Should Know About Floating-Point Arithmetic
Questions
Question 1
Can I rely on this solution if I need just precise 2 digits calculations (money)?
Answer 1
If you need need precise 2 digits then the answer is NO you can not use the php precision settings to ascertain a 2 digit decimal all the time even if you are not going to work on numbers higher than 10^6.
During calculations there is possibility that the precision length can be increased if the length is less than 8
Question 2
If not can you provide me a clear example when this solutions fails?
Answer 2
ini_set('precision', 8); // your precision
$a = 5.88 ; // cost of 1kg
$q = 2.49 ;// User buys 2.49 kg
$b = $a * 0.01 ; // 10% Discount only on first kg ;
echo ($a * $q) - $b;
Output
14.5824 <---- not precise 2 digits calculations even if precision is 8
Question 3
Which php.ini.precision value suits best two digits, money calculations?
Answer 3
Precision and Money calculation are 2 different things ... it's not a good idea to use PHP precision for as a base for your financial calculations or floating point length
Simple Test
Lest Run some example together using bcmath , number_format and simple minus
Base
$a = 342349.23;
$b = 341765.07;
Example A
ini_set('precision', 20); // set to 20
echo $a - $b, PHP_EOL;
echo floatval(round($a - $b, 2)), PHP_EOL;
echo number_format($a - $b, 2), PHP_EOL;
echo bcsub($a, $b, 2), PHP_EOL;
Output
584.15999999997438863
584.15999999999996817 <----- Round having a party
584.16
584.15 <-------- here is 15 because precision value is 20
Example B
ini_set('precision', 14); // change to 14
echo $a - $b, PHP_EOL;
echo floatval(round($a - $b, 2)), PHP_EOL;
echo number_format($a - $b, 2), PHP_EOL;
echo bcsub($a, $b, 2), PHP_EOL;
Output
584.15999999997
584.16
584.16
584.16 <-------- at 14 it changed to 16
Example C
ini_set('precision', 6); // change to 6
echo $a - $b, PHP_EOL;
echo floatval(round($a - $b, 2)), PHP_EOL;
echo number_format($a - $b, 2), PHP_EOL;
echo bcsub($a, $b, 2), PHP_EOL;
Output
584.16
584.16
584.16
584.00 <--- at 6 it changed to 00
Example D
ini_set('precision', 3); // change to 3
echo $a - $b, PHP_EOL;
echo floatval(round($a - $b, 2)), PHP_EOL;
echo number_format($a - $b, 2), PHP_EOL;
echo bcsub($a, $b, 2), PHP_EOL;
Output
584
584
584.16 <-------------------------------- They only consistent value
0.00 <--- at 3 .. everything is gone
Conclusion
Forget about floating point and just calculate in cents then later divided by 100 if that is too late just simply use number_format it looks consistent to me .
Update
Question 1: Is precision workaround gonna fail for numbers between 0..999999.99, where A and B is a number with decimal places? If so please provide me an example
Form 0 to 999999.99 at increment of of 0.01 is about 99,999,999 the combination possibility of your loop is 9,999,999,800,000,000 I really don't think anyone would want to run such test for you.
Since floating point are binary numbers with finite precision trying to set precision would have limited effect to ensure accuracy Here is a simple test :
ini_set('precision', 8);
$a = 0.19;
$b = 0.16;
$c = 0.01;
$d = 0.01;
$e = 0.01;
$f = 0.01;
$g = 0.01;
$h = $a + $b + $c + $d + $e + $f + $g;
echo "Total: " , $h , PHP_EOL;
$i = $h-$a;
$i = $i-$b;
$i = $i-$c;
$i = $i-$d;
$i = $i-$e;
$i = $i-$f;
$i = $i-$g;
echo $i , PHP_EOL;
Output
Total: 0.4
1.0408341E-17 <--- am sure you would expect 0.00 here ;
Try
echo round($i,2) , PHP_EOL;
echo number_format($i,2) , PHP_EOL;
Output
0
0.00 <------ still confirms number_format is most accurate to maintain 2 digit
Question 2: How to estimate/calculate when precision workaround fails? Without such crazy tests? Is there any mathematical*, straight answer for it? How to calculate is gonna to fail or not?
The fact sill remains Floating Point have Accuracy Problems but for mathematical solutions you can look at
i don't need to know floating point calculations works, but when workaround fails if you know precision, and range of A and B
enter image description here
Not sure what that statement means :)
• Nice one, thank you. But regarding Answer 2 - still there is no example when solution fails on 2 digits number add/substract calculations like 342349.23 - 341765.07 = 584.15999999992. And in Example C precision workaround is acctionaly.. doing the proper job :) – Peter Feb 3 '13 at 18:25
• And still it looks like precision=8 is good chocie for me – Peter Feb 3 '13 at 18:27
• My Belive is that you need exactly 2 digit 584.15999999992 does not look like it – Baba Feb 4 '13 at 7:48
• 1
This answer shows a lot of effort (my kudos to you for that). However, after reading it you get the impression that PHP's precision directive somehow affects mathematical calculations and that's misleading at its best, given that it's just a parameter for string conversion. If you have a number and you convert it to string before you do math with it (the only case where precision can act) you should probably start by tweaking your code's logic. – Álvaro González Feb 7 '13 at 17:23
• 1
Thank you so much. Really great answer. And I am more than happy to click +500 button, as this is exactly what I was looking for. Thanks to you now I have no single doubt that precise workaround is not an option in any possible scenario. Thanks again. – Peter Feb 12 '13 at 20:20
I just quote this interesting site to the problem. (No reputation expected :) but it should being mentioned:
What can I do to avoid this (floating point) problem?
That depends on what kind of calculations you’re doing.
• If you really need your results to add up exactly, especially when you work with money:use a special decimal datatype.
• If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it.
• If you have no decimal datatype available, an alternative is to work with integers, e.g. do money calculations entirely in cents. But this is more work and has some drawbacks.
The site contains also some basic tips for PHP
I would use integers or create a special Decimal type for it.
If you decide to use bcmath: Be careful if you pass that values to SQL queries or other external programs. It can lead to unwanted side effects if they are not aware of the precision. (What is likely)
According to the docs, the precision directive just changes the digits shown when casting numbers to strings:
precision integer
The number of significant digits displayed in floating point numbers.
So it's basically a very convoluted alternative to number_format() or money_format(), except that it has less formatting options and it can suffer from some other side effects you might not be aware:
<?php
$_POST['amount'] = '1234567.89';
$amount = floatval($_POST['amount']);
var_dump($amount);
ini_set('precision', 5);
$amount = floatval($_POST['amount']);
var_dump($amount);
...
float(1234567.89)
float(1.2346E+6)
Edit:
I insist: this setting does not alter the way PHP makes mathematical calculations with numbers. It's just a magical way to change format options when converting from floating point numbers (not even integers!) to strings. Example:
<?php
ini_set('precision', 2);
$amount = 1000;
$price = 98.76;
$total = $amount*$price;
var_dump($amount, $total);
ini_set('precision', 15);
var_dump($amount, $total);
... prints:
int(1000)
float(9.9E+4)
int(1000)
float(98760)
Which illustrates that:
1. Floating point calculations are unaffected, only the display changes
2. Integers are unaffected in all cases
• So 1234567.89 is quite good for "precision=5"? What if I use precision 10? (edited my question) Which php.ini.precision value suits best for two digits calculations? If precision just changes the digits shown when casting numbers why FP issue dissapeared? – Peter Jan 29 '13 at 16:49
• codepad.org/r7o086sS Looks it's ok for numbers up to 10^13? – Peter Jan 29 '13 at 17:02
• 1
@PeterSzymkowski - Not sure I understand all your questions. Precision takes into account all digits, not just decimals. And your FP issue "disappears" because the difference is tiny and it's gone with rounding. You are simply rounding in a very complicate way. – Álvaro González Jan 29 '13 at 17:08
• Let's says I am using precision=10. So any substraction between numbers 1..10^10-2 gonna give me good results without FP Problem? – Peter Jan 29 '13 at 17:16
• I suggest you forget about precision. You have many functions that provide full control and don't have size effects. – Álvaro González Jan 29 '13 at 17:56
I believe if you simply round your result you come up with, then that would take care of your floating point problem for you without having to make a server-wide change to your configuration.
round(342349.23 - 341765.07, 2) = 584.16
• please read my question carefully and comments as well – Peter Feb 7 '13 at 17:00
If you use precision=8, if you use an 8 digit number, you can't be certain of the 8th digit. This could be off by 1 from rounding the 9th digit.
Eg
12345678.1 -> 12345678
12345678.9 -> 12345679
This may not seem so bad, but consider
(11111111.2 + 11111111.2) + 11111111.4
-> (11111111) + 11111111.4
-> 22222222.4
-> 22222222
Whereas, if you were using precision=9, this would be 22222222.8 which would round to 22222223.
If you're just doing additions and subtractions, you should use at least 2 or so more digits of precision than you need to avoid rounding in these sorts of calculations. If you're doing multiplication or division, you may need more. Using the bare minimum necessary can lead to lost digits here and there.
So, to answer your question, you might get away with it if you're lucky and php uses high precision in calculations and only then stores the result in a lower precision (and you don't then use that number to go on and do other calculations), but in general, it is a very bad idea since (at least) the last digit in your calculation is completely unreliable.
• Yep. This is why i asked for numbers up to 10^6, and what about precision 8,9,10,11,12? – Peter Feb 9 '13 at 12:16
Your Answer
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.869861 |
Welcome, guest | Sign In | My Account | Store | Cart
This is a threadsafe version of recipe 576979. A publish-subscribe (observer) pattern is implemented as a descriptor. Assigning a value notifies the observers. Uses recipe 577105 as synchlock.py and recipe 576979 as Observer.py
Python, 100 lines
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
from Observer import _obwan, Observable
import threading
from synchlock import synchronous
class _tsobwan(_obwan):
"""Subclassed _obwan to provide thread synchronization"""
def __init__(self):
_obwan.__init__(self)
self._synchLock = threading.RLock()
setvalu = synchronous('_synchLock')(_obwan.setvalu)
subscribe = synchronous('_synchLock')(_obwan.subscribe)
_callbacks = synchronous('_synchLock')(_obwan._callbacks)
_cancel = synchronous('_synchLock')(_obwan._cancel)
class TSObservable(Observable):
"""Subclassed to provide thread synchronization"""
def __init__(self, nam ):
self.xname = "__"+nam
self.obwan = _tsobwan
# -------------------------------------------------------------------------
# example case
if __name__ == "__main__":
class MyClass(object):
""" A Class containing the observables chancellor and width"""
chancellor = TSObservable('chancellor')
width = TSObservable('width')
def __init__(self):
self.chancellor.setvalu(0)
self.width.setvalu(0)
class MyObserver(object):
"""Provides Observers for above"""
def __init__(self, name, observedObj):
self.name = name
self.subs1 = observedObj.chancellor.subscribe(self.print_c)
self.subs2 = observedObj.width.subscribe(self.print_w)
self.timesToReport = len(name)
def print_c(self, value):
print "%s observed change "%self.name, value
self.timesToReport -= 1
if self.timesToReport == 0:
print " cancelling my subscription"
self.subs1 = None
def print_w(self, value):
print "%s observed value "%self.name, value
def report2(value):
print "Report 2 observed value of ",value
import threading
import time
def onRun(observed, name):
obsver = MyObserver(name, observed)
isrunning = True
for j in range(400):
time.sleep(.10)
if isrunning and obsver.timesToReport==0:
isrunning = False
observed.chancellor = obsver.name
# ----------------------------------------------------
obnames = """Bob AllisonJane Karl Mujiburami Becky Geraldine
Johnny Barbarah Matthew""".split()
area = MyClass()
rptsbscrbr = area.width.subscribe(report2)
thrds = [ threading.Thread(target=onRun, name=n, args=(area,n))
for n in obnames]
for thrd in thrds:
thrd.start()
# lots of reports on changes to width
area.width = 4
area.width = "reddish"
# lots of reports on changes to chancellor
area.chancellor = 1.5
area.chancellor = 9
print " "
time.sleep(4.0)
# Resursing starts as thread cancel subscriptions
area.chancellor = "Amy"
# wait awhile...
time.sleep(4)
area.width =7.1
c = raw_input("ok?")
TSObservable implements threadsafe observer pattern. Since a TSObservable is a descriptor, it is added at the class level. To subscribe to changes, invoke instance.observable.subscribe( observer, [exception handler]), which returns a subscription object. The subscription remains as long as there is a reference to the subscription object. The object's __del__ method causes the subscription to be cancelled.
The observer function takes one argument, which will be the value that the observable was set to. Exceptions produced by observer can be handled by the optionally provided exception handler. The exception handler will be called with the exception as the argument if observer throws an exception. The handler should return false if the exception was not handled or the handler wants the exception to be reraised.
If observer, or a method called by it attempts to change the observed value, a RecursionError is raised.
This recipe provides thread safety to the Observable in recipe 576979 by using the synchronous decorator in recipe 577105.
2 comments
John K Luebs 11 years, 10 months ago # | flag
TSObservable isn't a descriptor. In python, a descriptor has a certain protocol involving a __get__ method at a minimum
Rodney Drenth (author) 11 years, 5 months ago # | flag
The __get__ and __set__ methods are implemented in the parent class of TSObservable.
| __label__pos | 0.603662 |
Tresdin Tresdin - 3 months ago 18
Javascript Question
How to resize then crop an image with canvas
I already know how to
-> resize an image:
var image = document.getElementById('myImage'),
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
ctx.drawImage(image,0,0,400,300);
-> or crop an image:
var image = document.getElementById('myImage'),
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
ctx.drawImage(image,50,50,image.width,image.height,0,0,50,50);
But I don't know how to resize then crop an image. How could I do this? Thank you.
Answer
From the documentation, these are the parameters for drawImage:
drawImage(image,
sx, sy, sw, sh,
dx, dy, dw, dh);
enter image description here
So, to crop the outer 10 pixels from the source image (Assuming it's 100 * 50), and then to scale that up to 160*60:
ctx.drawImage(image,
10, 10, // Start at 10 pixels from the left and the top of the image (crop),
80, 30, // "Get" a `80 * 30` (w * h) area from the source image (crop),
0, 0, // Place the result at 0, 0 in the canvas,
160, 60); // With as width / height: 160 * 60 (scale)
Example:
var image = new Image(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
image.src = 'https://www.google.nl/images/srpr/logo3w.png';
image.onload = function(){
ctx.drawImage(image,
70, 20, // Start at 70/20 pixels from the left and the top of the image (crop),
50, 50, // "Get" a `50 * 50` (w * h) area from the source image (crop),
0, 0, // Place the result at 0, 0 in the canvas,
100, 100); // With as width / height: 100 * 100 (scale)
}
Image: <br/>
<img src="https://www.google.nl/images/srpr/logo3w.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="275px" height="95px"></canvas> | __label__pos | 0.997516 |
PHP code to import from CSV file to MySQL
By: Nate
After playing a while, I'm confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead.
Arguments to pass in are exactly the same as for fputcsv, though I have added an additional $mysql_null boolean which allows one to turn php null's into mysql-insertable nulls (by default, this add-on is disabled, thus working identically to fputcsv [except this one works!]).
<?php
function fputcsv2 ($fh, array $fields, $delimiter = ',', $enclosure = '"', $mysql_null = false) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ($fields as $field) {
if ($field === null && $mysql_null) {
$output[] = 'NULL';
continue;
}
$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
$enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
) : $field;
}
fwrite($fh, join($delimiter, $output) . "\n");
}
// the _EXACT_ LOAD DATA INFILE command to use
// (if you pass in something different for $delimiter
// and/or $enclosure above, change them here too;
// but _LEAVE ESCAPED BY EMPTY!_).
/*
LOAD DATA INFILE
'/path/to/file.csv'
INTO TABLE
my_table
FIELDS TERMINATED BY
','
OPTIONALLY ENCLOSED BY
'"'
ESCAPED BY
''
LINES TERMINATED BY
'\n'
*/
?>
Most Viewed Articles (in PHP )
Latest Articles (in PHP)
Comment on this tutorial | __label__pos | 0.748735 |
PercentageCalculator .pro Discount Percentage Fraction to % Decimal to %
20 percent of 36?
Percentage Calculator
What is % of
Answer:
Percentage Calculator 2
is what percent of ?
Answer: %
Percentage Calculator 3
is % of what?
Answer:
Solution for 'What is 20% of 36?'
In all the following examples consider that:
Solution Steps
The following question is of the type "How much X percent of W", where W is the whole amount and X is the percentage figure or rate".
Let's say that you need to find 20 percent of 36. What are the steps?
Step 1: first determine the value of the whole amount. We assume that the whole amount is 36.
Step 2: determine the percentage, which is 20.
Step 3: Convert the percentage 20% to its decimal form by dividing 20 into 100 to get the decimal number 0.2:
20100 = 0.2
Notice that dividing into 100 is the same as moving the decimal point two places to the left.
20.0 → 2.00 → 0.20
Step 4: Finally, find the portion by multiplying the decimal form, found in the previous step, by the whole amount:
0.2 x 36 = 7.2 (answer).
The steps above are expressed by the formula:
P = W × X%100
This formula says that:
"To find the portion or the part from the whole amount, multiply the whole by the percentage, then divide the result by 100".
The symbol % means the percentage expressed in a fraction or multiple of one hundred.
Replacing these values in the formula, we get:
P = 36 × 20100 = 36 × 0.2 = 7.2 (answer)
Therefore, the answer is 7.2 is 20 percent of 36.
Solution for '20 is what percent of 36?'
The following question is of the type "P is what percent of W,” where W is the whole amount and P is the portion amount".
The following problem is of the type "calculating the percentage from a whole knowing the part".
Solution Steps
As in the previous example, here are the step-by-step solution:
Step 1: first determine the value of the whole amount. We assume that it is 36.
(notice that this corresponds to 100%).
Step 2: Remember that we are looking for the percentage 'percentage'.
To solve this question, use the following formula:
X% = 100 × PW
This formula says that:
"To find the percentage from the whole, knowing the part, divide the part by the whole then multiply the result by 100".
This formula is the same as the previous one shown in a different way in order to have percent (%) at left.
Step 3: replacing the values into the formula, we get:
X% = 100 × 2036
X% = 200036
X% = 55.56 (answer)
So, the answer is 20 is 55.56 percent of 36
Solution for '36 is 20 percent of what?'
The following problem is of the type "calculating the whole knowing the part and the percentage".
Solution Steps:
Step 1: first determine the value of the part. We assume that the part is 36.
Step 2: identify the percent, which is 20.
Step 3: use the formula below:
W = 100 × PX%
This formula says that:
"To find the whole, divide the part by the percentage then multiply the result by 100".
This formula is the same as the above rearranged to show the whole at left.
Step 4: plug the values into the formula to get:
W = 100 × 3620
W = 100 × 1.8
W = 180 (answer)
The answer, in plain words, is: 36 is 20% of 180.
Sample percentage problems | __label__pos | 0.999319 |
FANDOM
--ALRIGHT LET'S DO THIS
--Initial writeup started by User:Falterfire on 7/1/2017
--Borrowing functions written by somebody else over on Module:VoidByReward
--For reference:
-- in DropData["Drops"]
local typeCol = 1 -- [1] = type (IE Survival, Capture)
local catCol = 2 -- [2] = category (IE Hard, Derelict)
local rotCol = 3 -- [3] = rotation (IE A, B)
local numCol = 4 -- [4] = quantity (IE 1, 50)
local itemCol = 5 -- [5] = item (IE Hornet Strike, Endo)
local itemCatCol = 6 -- [6] = category (IE Mod, Resource)
local rarityCol = 7 -- [7] = rarity (IE common, uncommon)
local chanceCol = 8 -- [8] = drop chance (IE 15.03, 21.2)
-- in DropData["Enemies"]
local eNameCol = 1 -- [1] = Name (IE Lancer)
local eChance1Col = 2 -- [2] = Chance for that category (IE Mod % or Blueprint %)
local eCountCol = 3 -- [3] = Number dropped. -1 means unknown
local eItemCol = 4 -- [4] = Item (IE Hornet Strike, Dread Blueprint)
local eItemCatCol = 5 -- [5] = Item Category (IE Mod, Blueprint)
local eRarityCol = 6 -- [6] = Item Rarity (IE Common, Legendary)
local eChance2Col = 7 -- [7] = The chance for this item to drop
local eIgnoreCol = 8 -- [8] = if not nil and true, ignore this enemy
local p = {}
local DropData = mw.loadData( 'Module:DropTables/data' )
local Icon = require( "Module:Icon" )
local Shared = require( "Module:Shared" )
local Void = require( "Module:Void" )
local Mission = require( "Module:Missions" )
local Relics = require( "Module:VoidByReward")
local function linkEnemy(EName)
--Cut off enemy names before parentheses while linking
local paren, trash = string.find(EName, "%(")
local Result = ""
if(paren ~= nil) then
Result = "[["..string.sub(EName, 1, paren - 2).."|"..EName.."]]"
elseif (EName == "Fissure Corrupted Enemy") then
Result = "[[Void Fissure|"..EName.."]]"
else
Result = "[["..EName.."]]"
end
return Result
end
--Sorts theTable based on the listed column
local function tableSort(theTable, sortCol, ascend)
local new function sorter(r1, r2)
if(ascend) then
return r1[sortCol] < r2[sortCol]
else
return r1[sortCol] > r2[sortCol]
end
end
table.sort(theTable, sorter)
end
--Returns the real drop chance of a specific enemy drop
--This involves combining chance to drop mod/blueprint with chance of that specific item dropping
--So 3% Mod Chance + 37.94% Pressure Point chance = 1.1382% real chance
local function getRealDropChance(EnemyDrop)
local odds1 = EnemyDrop[eChance1Col]
local odds2 = EnemyDrop[eChance2Col]
local result = ((odds1 * odds2) / 100)
return result
end
--Gets one of each mission type and returns the list
local function getAllMissionTypes()
local missions = {}
local types = {}
for typeName, typeData in Shared.skpairs(DropData["Categories"]) do
for catName, cat in Shared.skpairs(typeData) do
table.insert(missions, {Tier = cat.Alias})
end
end
return missions
end
local function getAllModDrops(enemyName)
local drops = {}
for i, d in pairs(DropData["Enemies"]) do
if(d[eNameCol] == enemyName and (d[eItemCatCol] == "Mod" or d[eItemCatCol] == "Endo")) then
table.insert(drops, d)
end
end
return drops
end
local function getAllBlueprintDrops(enemyName)
local drops = {}
for i, d in pairs(DropData["Enemies"]) do
if(d[eNameCol] == enemyName and (d[eItemCatCol] == "Blueprint")) then
table.insert(drops, d)
end
end
return drops
end
local function getAllEnemyDrops(enemyName)
local drops = {}
for i, d in pairs(DropData["Enemies"]) do
if(d[eNameCol] == enemyName) then
table.insert(drops, d)
end
end
return drops
end
--Custom table sort for reward tables
--WIP, initial rules:
--Sort first by type, then alphabetically within type, then by quantity
local function rewardTableSort(theTable)
local new function sorter(r1, r2)
if(r1[itemCatCol] == r2[itemCatCol]) then
if(r1[itemCol] == r2[itemCol]) then
return r1[numCol] < r2[numCol]
else
return r1[itemCol] < r2[itemCol]
end
else
return r1[itemCatCol] < r2[itemCatCol]
end
end
table.sort(theTable, sorter)
end
--Custom table sort for Enemy tables
--Rules:
--Sort first by Drop Chance, then alphabetically within Drop Chance with Endo being last
local function enemyTableSort(theTable)
local new function sorter(r1, r2)
if(r1[eChance2Col] == r2[eChance2Col]) then
if(r1[eItemCatCol] == r2[eItemCatCol]) then
return r1[eItemCol] < r2[eItemCol]
else
return r1[eItemCatCol] > r2[eItemCatCol]
end
else
return r1[eChance2Col] > r2[eChance2Col]
end
end
table.sort(theTable, sorter)
end
local function getModLink(ModName)
--Scorch and Seeker are both enemies and mods. Thanks DE.
--Also Sanctuary as mod VS Simaris's thing
--Also Antitoxin, mod vs gear
if(ModName == "Scorch" or ModName == "Seeker" or ModName == "Sanctuary" or ModName == "Antitoxin") then
return "<span class=\"mod-tooltip\" data-param=\""..ModName.."\" style=\"white-space:pre\">[["..ModName.." (Mod)".."|"..ModName.."]]</span>"
else
return "<span class=\"mod-tooltip\" data-param=\""..ModName.."\" style=\"white-space:pre\">[["..ModName.."]]</span>"
end
end
--Formats a string of text for a reward table
--(NOTE: ALWAYS USES TWO COLUMNS)
--Format is
-- [Icon] [Quantity] [Item Name with Link] || [Drop Chance]]
-- With some slight variation based on drop type
-- Variation is mostly helpful for getting the right icon
local function formatDropString(drop)
local result = ""
local dropType = drop[itemCatCol]
local iconText = ""
if(dropType == "Resource") then
iconText = Icon._Resource(drop[itemCol], nil, nil)
if(drop[itemCol] == "Mutalist Alad V Nav Coordinate") then
result = result.."[[Nav Coordinates#Mutalist Nav Coordinates|Mutalist Alad V Nav Coordinate]]"
else
local pieces = Shared.splitString(drop[itemCol]," ")
local lastPiece = pieces[Shared.tableCount(pieces)]
if(lastPiece == "Lens") then
if(pieces[1] == "Greater") then
iconText = Icon._Resource("Greater Focus Lens")
else
iconText = Icon._Resource("Focus Lens")
end
result = "[[Focus Lens|"..drop[itemCol].."]]"
else
result = result.."[["..drop[itemCol].."]]"
end
end
elseif (dropType == "Endo") then
iconText = Icon._Item("Endo", nil, nil)
result = result.."[[Endo]]"
elseif (dropType == "Mod") then
iconText = Icon._Item("Mods", nil, nil)
result = result..getModLink(drop[itemCol])
elseif (dropType == "Relic") then
local sp1, trash = string.find(drop[itemCol], " ")
local tier = string.sub(drop[itemCol], 1, sp1 - 1)
iconText = Icon._Item(tier, nil, "40x40")
result = result.."[[Void Relic|"..drop[itemCol].."]]"
elseif (dropType == "Credits") then
iconText = Icon._Item("Credits", nil, nil)
result = result.."[[Credit Cache]]"
elseif (dropType == "Blueprint") then
local pieces = Shared.splitString(drop[itemCol]," ")
local BPType = pieces[2]
local BPName = pieces[1]
local linkString = Shared.splitString(drop[itemCol], " ")[1]
if (BPName == "Forma") then
iconText = Icon._Item("Forma", nil, nil)
elseif (BPName == "Miter" and BPType == "Chassis") then
--a workaround for displaying proper icons for Miter parts
iconText = Icon._Item("Stock", nil, nil)
elseif (BPName == "Miter" and BPType == "Handle") then
--because Miter has oddly named parts
iconText = Icon._Item("Receiver", nil, nil)
elseif (BPType == "Systems") then
iconText = Icon._Item("Systems", nil, nil)
elseif (BPType == "Chassis") then
iconText = Icon._Item("Chassis", nil, nil)
elseif (BPType == "Neuroptics") then
iconText = Icon._Item("Neuroptics", nil, nil)
elseif (BPType == "Barrel") then
iconText = Icon._Item("Barrel", nil, nil)
elseif (BPType == "Stock") then
iconText = Icon._Item("Stock", nil, nil)
elseif (BPType == "Receiver") then
iconText = Icon._Item("Receiver", nil, nil)
elseif (BPType == "Blade") then
iconText = Icon._Item("Blade", nil, nil)
elseif (pieces[2] == "Wraith" or pieces[2] == "Vandal") then
--Now a workaround for Wraith & Vandal things to link them properly
--In theory works for any Wraith/Vandal item
linkString = pieces[1].." "..pieces[2]
if(pieces[3] ~= "Blueprint") then
iconText = Icon._Item(pieces[Shared.tableCount(pieces)], nil, nil)
else
iconText = Icon._Item("Blueprint", nil, nil)
end
elseif (pieces[3] == "Blueprint") then
--a workaround for Eidolon Lens BP or Twin Gremlins BP to link proper pages
--should work for other 3 part blueprint names as well
linkString = pieces[1].." "..pieces[2]
iconText = Icon._Item("Blueprint", nil, nil)
elseif (pieces[1] == "Equinox") then
--a workaround for Equinox's 4 piece names
if (pieces[3] == "Systems") then
iconText = Icon._Item("Systems", nil, nil)
elseif (pieces[3] == "Chassis") then
iconText = Icon._Item("Chassis", nil, nil)
elseif (pieces[3] == "Neuroptics") then
iconText = Icon._Item("Neuroptics", nil, nil)
else
iconText = Icon._Item("Blueprint", nil, nil)
end
else
iconText = Icon._Item("Blueprint", nil, nil)
end
result = result.."[["..linkString.."|"..drop[itemCol].."]]"
elseif (dropType == "Item") then
iconText = Icon._Item(drop[itemCol])
if(drop[itemCol] == "Cyan" or drop[itemCol] == "Amber") then
result = "[[Ayatan Sculpture|Ayatan "..drop[itemCol].." Star]]"
else
result = "[["..drop[itemCol].."]]"
end
else
result = result..drop[itemCol]
end
if(drop[numCol] > 1) then
result = drop[numCol].." "..result
end
result = iconText.." "..result.." || "..drop[chanceCol].."%"
return result
end
--Returns a table of all rewards for a given mission, split by rotation
local function getRewardsForMission(MissionType, MissionCat)
if(MissionCat == nil) then
MissionType, MissionCat = Mission.getMissionFromAlias(MissionType)
else
MissionCat = Mission.getCategoryName(MissionType, MissionCat)
end
local RotA = {}
local RotB = {}
local RotC = {}
for _, d in pairs(DropData["Drops"]) do
local MType = d[typeCol]
local MCat = d[catCol]
local Rot = d[rotCol]
if(MType == MissionType and MCat == MissionCat) then
if(Rot == "A") then
table.insert(RotA, d)
elseif(Rot == "B") then
table.insert(RotB, d)
else
table.insert(RotC, d)
end
end
end
rewardTableSort(RotA)
rewardTableSort(RotB)
rewardTableSort(RotC)
return {["A"] = RotA, ["B"] = RotB, ["C"] = RotC}
end
--Gets the list of missions of a given type and sends them back
local function getMissionsOfType(MissionType, MissionCat)
if(MissionCat ~= nil) then
MissionCat = Mission.getCategoryName(MissionType, MissionCat)
MissionType = Mission.getAlias(MissionType, MissionCat)
end
local data = {}
for _, m in Shared.skpairs(DropData["MissionDetails"]) do
if(m.Tier == MissionType) then
table.insert(data, m)
end
end
return data
end
--Returns the rewards for the A tier only for a mission
--Handy for missions like Capture that have a single reward
--Returns as rows for a table with two columns
--See the existing Capture rewards section for an example
function p.getSingleRotationRewards(frame)
local MissionType = frame.args ~= nil and frame.args[1]
local MissionCat = frame.args ~= nil and frame.args[2]
local result = ""
local data = getRewardsForMission(MissionType, MissionCat)["A"]
for i, drop in pairs(data) do
result = result.."\n|-\n| "..formatDropString(drop)
end
return result
end
--Returns the rewards for a given mission/tier
--Returns as rows for a table with six columns, two for each rotation
--See existing Survival/Rewards/Normal_Mission for examples
function p.getRewardTable(frame)
local MissionType = frame.args ~= nil and frame.args[1]
local MissionCat = frame.args ~= nil and frame.args[2]
local result = ""
local data = getRewardsForMission(MissionType, MissionCat)
local RotA = data["A"]
local RotB = data["B"]
local RotC = data["C"]
local ACount = Shared.tableCount(RotA)
local maxLen = ACount
local BCount = Shared.tableCount(RotB)
if(BCount > maxLen) then
maxLen = BCount
end
local CCount = Shared.tableCount(RotC)
if(CCount > maxLen) then
maxLen = CCount
end
for i=1, maxLen, 1 do
result = result.."\n|-"
if(RotA[i] ~= nil) then
result = result.."\n| align=\"right\" | "..formatDropString(RotA[i])
else
result = result.."\n| || "
end
if(RotB[i] ~= nil) then
result = result.."\n| align=\"right\" | "..formatDropString(RotB[i])
else
result = result.."\n| || "
end
if(RotC[i] ~= nil) then
result = result.."\n| align=\"right\" | "..formatDropString(RotC[i])
else
result = result.."\n| || "
end
end
if(MissionType == "Sabotage" and MissionCat == "Kuva Fortress") then
result = result.."[[Category:KuvaSabotage]]"
end
return result
end
function p.getMissionList(frame)
local MissionType = frame.args ~= nil and frame.args[1]
local MissionCat = frame.args ~= nil and frame.args[2]
result = ""
local missions = getMissionsOfType(MissionType, MissionCat)
for _, m in pairs(missions) do
local typeName = m.Type
result = result.."\n* "..m.Node..", [["..m.Planet.."]]"
--[[if (m.IsDarkSector == 1) then
result = result.." ([Dark Sector] "..Mission.linkType(typeName)..")"
else
result = result.." ("..Mission.linkType(typeName)..")"
end]]
end
return result
end
--Gets a list of missions with rewards for a given planet
--Ignores 'Event' missions
local function getMissionsForPlanet(Planet)
local missions = {}
for _, m in pairs(DropData["MissionDetails"]) do
if (m.Planet == Planet and m.Tier ~= nil) then
table.insert(missions, m)
end
end
return missions
end
local function getDropMissions(itemName)
local Drops = {}
for i, d in pairs(DropData["Drops"]) do
if(d[itemCol] == itemName) then
table.insert(Drops, d)
end
end
return Drops
end
local function getDropEnemies(itemName)
local Drops = {}
for i, d in pairs(DropData["Enemies"]) do
if(string.upper(d[eItemCol]) == string.upper(itemName) and (d[eIgnoreCol] == nil or not d[eIgnoreCol])) then
table.insert(Drops, d)
end
end
return Drops
end
--Gets the table used on Void Relic/ByMission
--Unlike getRewardTable, this is just the full table with all formatting
--This is pretty ugly, but kinda have to do it this way
--(Unless you have a better solution, in which case by all means go ahead and fix it)
--(I'm not exactly a Lua expert or a UI expert)
function p.getRelicTable(frame)
--Okay, so first up, need to know which planet this is for
local Planet = nil
if(frame ~= nil) then
Planet = frame.args ~= nil and frame.args[1] or frame
end
--Planet == nil is standing in for 'all planets', so adding option to explicitly call 'all'
if(Planet ~= nil and (Planet == "" or Planet == "All")) then
Planet = nil
end
--I have other functions to get the list of missions for all/planet
--So calling that here
local missions
if(Planet == nil) then
missions = getAllMissionTypes()
else
missions = getMissionsForPlanet(Planet)
end
local tableRows = {}
local Relics = {["Lith"] = {}, ["Meso"] = {}, ["Neo"] = {}, ["Axi"] = {}}
--Now for the 'fun' part: Getting the list
for i, m in pairs(missions) do
--For each mission, the first thing we're doing is setting up what it's called
--Or more accurately, what it appears as in the chart
local rowName = ""
if(Planet == nil) then
local typeName, catName = Mission.getMissionFromAlias(m.Tier)
--When showing all, the format is "Mission Name (Tier)" with link to mission type
--For example, "Survival (Tier 1)" or "Spy (Lua)"
rowName = Mission.linkType(typeName).." ("..Mission.getName(m.Tier)..")"
else
local placeName = m.Node
--When showing a single planet, format is instead "Mission Name (Type)"
--For example, "Rusalka (Capture)"
--Mission type is still linked
--Dark Sector is also linked if appropriate
if (m.IsDarkSector == 1) then
rowName = placeName.." ([[Dark Sector|DS]] "..Mission.linkType(m.Type)..")"
else
rowName = placeName.." ("..Mission.linkType(m.Type)..")"
end
end
local thisRow = nil
--This is where we get all the rewards for the mission
local drops = getRewardsForMission(m.Tier)
--Yeah, this is kinda clumsy
--buuuuut it means I don't have to duplicate this loop three times
--Please see disclaimer at top of function re:my not being a Lua Expert
local rot = "A"
--Need to know if this is a single rotation
--Because if it is, just a checkmark instead of a letter
local isSingleRot = Shared.tableCount(drops["B"]) == 0
--For each mission, looping each rotation
for i2=1, 3, 1 do
--And each drop for each rotation
for i3, d in pairs(drops[rot]) do
--We only care if it's a relic
if(d[itemCatCol] == "Relic") then
--Set up the row if we don't have it yet
--Mission will not be added to the grid unless it drops at least one relic
--Avoids adding a row for something like Assassination that never gives relics
if(thisRow == nil) then
thisRow = {}
end
--Example: "Lith A1 Relic"
local RelicText = d[itemCol]
--Example: {"Lith", "A1", "Relic"}
local RelicBits = Shared.splitString(RelicText, " ")
--Example: "Lith"
local RTier = RelicBits[1]
--Example: "A1"
local RName = RelicBits[2]
--Make sure the relevant entry exists
if (thisRow[RelicText] == nil) then
thisRow[RelicText] = ""
end
--And then fill it in
if (isSingleRot) then
thisRow[RelicText] = "✔"
else
thisRow[RelicText] = thisRow[RelicText]..rot
end
--Adding drop rate info when hovering
--If the drop rate is under 1% we set it red
--Under 2%, orangered
local RelicTextColor = "inherit"
if (d[chanceCol] < 1) then
RelicTextColor = "red"
elseif (d[chanceCol] < 2) then
RelicTextColor = "orangered"
end
thisRow[RelicText] = "<span style=\"color:" .. RelicTextColor .. ";\" title=\"Drop rate : " .. d[chanceCol] .. "%\">" .. thisRow[RelicText] .. "</span>"
--Also gotta add the Relic to our list if we don't have it yet
if(Relics[RTier][RName] == nil) then
Relics[RTier][RName] = RelicText
end
end
end
rot = rot == "A" and "B" or "C"
end
if ( thisRow ~= nil ) then
tableRows[rowName] = thisRow
--Special duplicate row for Excavation 2/3 which matches Survival 2/3
if(Planet == nil and (m.Tier == "Survival2" or m.Tier == "Survival3")) then
local rowName2 = "[[Excavation]] ("..Mission.getName(m.Tier)..")"
tableRows[rowName2] = thisRow
end
end
end
local result = ""
local headerRow = ""
--So this right here sets up the initial conditions of the table
--If you want to change the styling, you've gotta do it here
result = "{| class=\"wikitable\" "
result = result.."style=\"width:100%; border=1px; text-align:center; font-size:11px;\""
result = result.."\n|-"
--Slightly different text for all missions VS missions for a planet
if(Planet == nil) then
result = result.."\n! rowspan=\"2\" |Mission Type (Tier)"
else
result = result.."\n! rowspan=\"2\" |Node (Type)"
end
--Looping through each Relic tier
--Doing two things here:
--1. Setting up the header row with the list of relics
--2. Setting up the topmost row that has the name of each relic tier
for tier in Shared.relicLoop() do
local relicCount = Shared.tableCount(Relics[tier])
if(relicCount > 0) then
result = result.."\n! colspan=\""..relicCount.."\" |"..tier
for rNum, trash in Shared.skpairs(Relics[tier]) do
if(string.len(headerRow) > 0) then
headerRow = headerRow.." || "
end
headerRow = headerRow..rNum
end
end
end
--Then add the second row to the list
result = result.."\n|-\n|"..headerRow
--And now, at long last, it's time to add all the good stuff
for mName, relicRow in Shared.skpairs(tableRows) do
result = result.."\n|-\n|"..mName
for tier in Shared.relicLoop() do
for rNum, rName in Shared.skpairs(Relics[tier]) do
if(relicRow[rName] ~= nil) then
result = result.."||"..relicRow[rName]
else
result = result.."|| "
end
end
end
end
--And the all-important coda
result = result.."\n|}"
--And then ship it all back
return result
end
--Function used for building Void Relic/DropLocation table
function p.getRelicByLocation(frame)
local tier = frame.args ~= nil and frame.args[1] or frame
local relicData = {}
local missionData = {}
local result = ""
--As with most of my functions, breaking this into two parts:
--First, gather all the data
for i, d in pairs(DropData["Drops"]) do
if(d[itemCatCol] == "Relic") then
--Example: "Lith A1 Relic"
local RelicText = d[itemCol]
--Example: {"Lith", "A1", "Relic"}
local RelicBits = Shared.splitString(RelicText, " ")
--Example: "Lith"
local RTier = RelicBits[1]
--Example: "A1"
local RName = RelicBits[2]
if(RTier == tier) then
local MType = d[typeCol]
local MCat = d[catCol]
local shortName = MType..MCat
--Create an entry for this relic 'cause we don't have one yet
if(relicData[RName] == nil) then
relicData[RName] = { Drops = {}, Rewards = Void.getRelic(RTier, RName).Drops}
end
table.insert(relicData[RName].Drops, d)
end
end
end
--Second, build the actual table being sent back
local result
result = "{| class=\"article-table\" border=\"0\" cellpadding=\"1\" "
result = result.."cellspacing=\"1\" style=\"width: 100%;\""
result = result.."\n! Relic Name"
result = result.."\n! Drop locations"
local rHeader
rHeader = "{| cellpadding=\"2\" cellspacing=\"0\" class=\"sortable\" "
rHeader = rHeader.."style=\"width:100%;border:1px solid black; "
rHeader = rHeader.."text-align:right;font-size:12px;\""
rHeader = rHeader.."\n!Type"
rHeader = rHeader.."\n!Category"
rHeader = rHeader.."\n!Rotation"
rHeader = rHeader.."\n!Chance"
for RName, RTable in Shared.skpairs(relicData) do
result = result.."\n|-\n| "..tier.." "..RName
for i, reward in pairs(RTable.Rewards) do
local ItemName = Relics.getItemName(reward.Item)
local PartName = Relics.getPartName(reward.Part)
result = result.."\n* [["..ItemName.."|"..ItemName.." "..PartName.."]]"
end
local rTable = rHeader
for i, d in pairs(RTable.Drops) do
rTable = rTable.."\n|-\n|"..Mission.linkType(d[typeCol]).."||"..Mission.getName(d[typeCol], d[catCol])
rTable = rTable.."||"..d[rotCol].."||"..d[chanceCol].."%"
--Excavations share with Survival, so give an extra row to make up for it
if(d[typeCol] == "Survival" and (d[catCol] == "Medium" or d[catCol] == "Hard")) then
rTable = rTable.."\n|-\n|"..Mission.linkType("Excavation").."||"..Mission.getName(d[typeCol], d[catCol])
rTable = rTable.."||"..d[rotCol].."||"..d[chanceCol].."%"
end
end
rTable = rTable.."\n|}"
result = result.."\n|\n"..rTable
end
result = result.."\n|}"
return result
end
function p.getItemByMissionTable(frame)
local theDrop = frame.args ~= nil and frame.args[1] or frame
local Drops = getDropMissions(theDrop)
Shared.tableSort(Drops, typeCol, true)
local rHeader
rHeader = "{| cellpadding=\"2\" cellspacing=\"0\" class=\"sortable\" "
rHeader = rHeader.."style=\"width:100%;border:1px solid black; "
rHeader = rHeader.."text-align:right;font-size:12px;\""
rHeader = rHeader.."\n!Type"
rHeader = rHeader.."\n!Category"
rHeader = rHeader.."\n!Rotation"
rHeader = rHeader.."\n!Chance"
local rTable = rHeader
for i, d in pairs(Drops) do
rTable = rTable.."\n|-\n|"..Mission.linkType(d[typeCol]).."||"..Mission.getName(d[typeCol], d[catCol])
rTable = rTable.."||"..d[rotCol].."||"..d[chanceCol].."%"
--Excavations share with Survival, so give an extra row to make up for it
if(d[typeCol] == "Survival" and (d[catCol] == "Medium" or d[catCol] == "Hard")) then
rTable = rTable.."\n|-\n|"..Mission.linkType("Excavation").."||"..Mission.getName(d[typeCol], d[catCol])
rTable = rTable.."||"..d[rotCol].."||"..d[chanceCol].."%"
end
end
rTable = rTable.."\n|}"
return rTable
end
function p.getItemByEnemyTable(frame)
local theDrop = frame.args ~= nil and frame.args[1] or frame
local Drops = getDropEnemies(theDrop)
Shared.tableSort(Drops, eNameCol, true)
local rHeader
rHeader = "{| cellpadding=\"2\" cellspacing=\"0\" class=\"sortable\" "
rHeader = rHeader.."style=\"width:100%;border:1px solid black; "
rHeader = rHeader.."text-align:right;font-size:12px;\""
rHeader = rHeader.."\n!Enemy"
rHeader = rHeader.."\n!Rarity"
rHeader = rHeader.."\n!Chance"
local rTable = rHeader
for i, d in pairs(Drops) do
rTable = rTable.."\n|-\n|"..linkEnemy(d[eNameCol]).."||"..d[eRarityCol]
rTable = rTable.."||"..getRealDropChance(d).."%"
end
rTable = rTable.."\n|}"
return rTable
end
function p.getItemDropList(frame)
local theDrop = frame.args ~= nil and frame.args[1] or frame
local Drops = getDropMissions(theDrop)
local checked = {}
local result = ""
if(Shared.tableCount(Drops) > 0) then
local finalTable = {}
result = "'''Missions:'''"
Shared.tableSort(Drops, typeCol, true)
for i, Drop in pairs(Drops) do
local Alias = Mission.getAlias(Drop[typeCol], Drop[catCol])
local MissionName = Mission.getShortName(Drop[typeCol], Drop[catCol])
if(checked[Alias] == nil) then
checked[Alias] = 1
if(finalTable[Drop[typeCol]] == nil) then
finalTable[Drop[typeCol]] = {}
end
table.insert(finalTable[Drop[typeCol]], MissionName)
if(Alias == "Survival2" or Alias == "Survival3") then
if(finalTable["Excavation"] == nil) then
finalTable["Excavation"] = {}
end
table.insert(finalTable["Excavation"], MissionName)
end
end
end
local new function sorter(r1, r2)
return r1 < r2
end
table.sort(finalTable, sorter)
for i, item in pairs(finalTable) do
table.sort(item)
result = result.."<br/>"..Mission.linkType(i).." ("..table.concat(item, ", ")..")"
end
end
Drops = getDropEnemies(theDrop)
if(Shared.tableCount(Drops) > 0) then
Shared.tableSort(Drops, eNameCol, true)
if(string.len(result) > 0) then result = result.."<br/>" end
result = result.."'''Enemies:'''"
for i, Drop in pairs(Drops) do
result = result.."<br/>"..linkEnemy(Drop[eNameCol])..string.format(" (%.2f%%)", getRealDropChance(Drop))
end
end
return result
end
function p.getItemShortDropList(frame)
local theDrop = frame.args ~= nil and frame.args[1] or frame
local dropCount = frame.args ~= nil and tonumber(frame.args[2]) or 5
local Drops = getDropMissions(theDrop)
local checked = {}
local result = "Drop Locations"
local addCount = 0
if(Shared.tableCount(Drops) > 0) then
local finalTable = {}
Shared.tableSort(Drops, typeCol, true)
for i, Drop in pairs(Drops) do
local Alias = Mission.getAlias(Drop[typeCol], Drop[catCol])
local MissionName = Mission.getShortName(Drop[typeCol], Drop[catCol])
if(checked[Alias] == nil) then
checked[Alias] = 1
if(finalTable[Drop[typeCol]] == nil) then
finalTable[Drop[typeCol]] = {}
end
table.insert(finalTable[Drop[typeCol]], MissionName)
if(Alias == "Survival2" or Alias == "Survival3") then
if(finalTable["Excavation"] == nil) then
finalTable["Excavation"] = {}
end
table.insert(finalTable["Excavation"], MissionName)
end
end
end
local new function sorter(r1, r2)
return r1 < r2
end
table.sort(finalTable, sorter)
for i, item in pairs(finalTable) do
table.sort(item)
result = result.."<br/>"..Mission.linkType(i).." ("..table.concat(item, ", ")..")"
addCount = addCount + 1
if(addCount >= dropCount) then return result end
end
end
Drops = getDropEnemies(theDrop)
if(Shared.tableCount(Drops) > 0) then
Shared.tableSort(Drops, eNameCol, true)
for i, Drop in pairs(Drops) do
result = result.."<br/>"..linkEnemy(Drop[eNameCol])..string.format(" (%.2f%%)", getRealDropChance(Drop))
addCount = addCount + 1
if(addCount >= dropCount) then return result end
end
end
if(addCount > 0) then
return result
else
return ""
end
end
function p.getItemByEnemyCount(frame)
local theDrop = frame.args ~= nil and frame.args[1] or frame
local Drops = getDropEnemies(theDrop)
return Shared.tableCount(Drops)
end
function p.getItemByMissionCount(frame)
local theDrop = frame.args ~= nil and frame.args[1] or frame
local Drops = getDropMissions(theDrop)
return Shared.tableCount(Drops)
end
function p.getFullEnemyList(frame)
local Enemies = {}
local result = "All Enemies: "
for i, d in pairs(DropData["Enemies"]) do
local EName = d[eNameCol]
if(Enemies[EName] == nil) then
Enemies[EName] = 1
result = result.."\n* "..linkEnemy(EName)
end
end
return result
end
function p.getEnemyModDrops(frame)
local EnemyName = frame.args ~= nil and frame.args[1] or frame
local Drops = getAllModDrops(EnemyName)
if(Shared.tableCount(Drops) == 0) then
return "None"
end
enemyTableSort(Drops)
local result = ""
for i, Drop in pairs(Drops) do
if i > 1 then result = result.."<br/>" end
local dChance = getRealDropChance(Drop)
if(Drop[eItemCatCol] == "Endo") then
result = result..Drop[eCountCol].." [[Endo]]"
else
result = result..getModLink(Drop[eItemCol])
end
result = result..string.format(" (%.2f%%)", dChance)
end
return result
end
function p.test(frame1, frame2)
return Mission.getAlias(frame1, frame2)
end
return p
Ad blocker interference detected!
Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers
Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected. | __label__pos | 0.515885 |
Check sibling questions
Example 8 - Find equation of parabola symmetric about y-axis
Example 8 - Chapter 11 Class 11 Conic Sections - Part 2
This video is only available for Teachoo black users
Transcript
Example 8 Find the equation of the parabola which is symmetric about the y-axis, and passes through the point (2,–3). Since the parabola is symmetric about y-axis Equation is of the form x2 = 4ay or x2 = – 4ay Now plotting point (2, −3) on graph Since (2, −3) lies in fourth quadrant So the parabola will be of the form Hence we use equation x2 = – 4ay. Now parabola passes through (2, −3) Putting x = 2, y = −3 in equation 22 = −4 × a × −3 4 = 12a 4/12 = a 1/3 = a a = 𝟏/𝟑 Equation of parabola is x2 = −4ay x2 = − 𝟒/𝟑 y
Davneet Singh's photo - Teacher, Engineer, Marketer
Made by
Davneet Singh
Davneet Singh is a graduate from Indian Institute of Technology, Kanpur. He has been teaching from the past 12 years. He provides courses for Maths and Science at Teachoo. | __label__pos | 0.994717 |
How To
How to Block a Podcast on Spotify
If you find podcast that you no longer wish to see in your recommendations, Sadly, there is currently no direct option to block a podcast on Spotify. You can block artist or use third party App to block a podcast on Spotify.
Spotify, the popular music streaming platform, has become a go-to destination for not only music enthusiasts but also podcast lovers. While Spotify’s algorithms excel at recommending music tailored to your taste, it’s natural to encounter podcasts that may not resonate with your interests. If you find yourself longing for a way to block a podcast on Spotify, this article will guide you through the process and help you regain control over your listening experience.
Understanding the Limitations:
Before we delve into the steps, it’s important to note that, currently, Spotify does not provide a direct option to block a specific podcast. The platform primarily focuses on music recommendations rather than podcast customization. However, we will explore alternative methods to minimize unwanted podcast suggestions and regain control over your Spotify recommendations.
Can You Block a Podcast on Spotify?
Currently, Spotify does not have a direct option to block podcasts. While you can block artists by selecting “Don’t Play This Artist,” a similar feature doesn’t exist for podcasts. Third-party apps claiming to block podcasts exist, but exercise caution when granting them access to your Spotify account.
Managing Podcast Recommendations:
Although blocking podcasts directly is not possible, there are steps you can take to reduce their appearance in your recommendations:
Unfollowing a Podcast:
If you had previously followed a podcast that you no longer wish to see in your recommendations, unfollowing it is a simple yet effective way to reduce its visibility.
1. Launch the Spotify app on your device and tap on the “Your Library” icon.
2. Select “Podcasts & Shows” to access your podcast library.
3. Locate the podcast you want to unfollow and tap on it.
4. Underneath the podcast’s cover art, you’ll find a “Following” button. Tap on it to unfollow the podcast.
5. The podcast will no longer appear in your library or influence your recommendations.
Rating Podcasts:
Spotify’s algorithm takes into account user ratings when suggesting content. By giving a low rating to a podcast you dislike, you can signal your preferences and potentially reduce its presence in your recommendations.
1. Start by playing an episode of the podcast you wish to rate.
2. Tap the “Three Dots” icon while the episode is playing.
3. Select “Rate Show” from the options provided.
4. Give the podcast a low rating, such as one star, to reflect your dissatisfaction.
5. Tap “Submit” to submit your rating.
6. The algorithm will consider your feedback when generating future recommendations.
Explore Third-Party Solutions:
While not endorsed by Spotify, there are third-party apps and scripts available that claim to block or hide podcasts on Spotify. Exercise caution when using such tools and thoroughly research their credibility and security before granting them access to your Spotify account.
Understanding Spotify Recommendations:
Spotify’s recommendations are based on various factors, including your listening habits and those of others. Recommendations rely on signals from you, so keep listening to the songs and podcasts you love. However, Spotify may also suggest podcasts to gather more data or in “exploration” mode.
Tips to Make the Algorithm Work for You:
While you can’t completely control recommendations, you can enhance your Spotify experience:
1. Create a Detailed Profile: If you’re an artist or podcaster, ensure your Spotify profile is comprehensive. Include a bio, social links, upcoming shows, and merchandise to stand out.
2. Utilize Spotify’s Promotional Tools: As an artist, take advantage of Spotify’s promotional tools, such as Spotify Ad Studio. Create customized ads to promote your releases and events, reaching a targeted audience.
3. Pre-Save Content: Encourage users to pre-save your content before its release. This action boosts your visibility and signals to the Spotify algorithm that your content is anticipated.
FAQ
Q: Can I block a specific podcast on Spotify?
A: Currently, Spotify does not provide a direct option to block a specific podcast. However, there are alternative methods you can use to minimize unwanted podcast suggestions such as unfollowing the podcast and giving it a low rating.
Q: How do I unfollow a podcast on Spotify?
A: To unfollow a podcast on Spotify, follow these steps:
1. Launch the Spotify app and tap on the “Your Library” icon.
2. Select “Podcasts & Shows” to access your podcast library.
3. Locate the podcast you want to unfollow and tap on it.
4. Underneath the podcast’s cover art, you’ll find a “Following” button. Tap on it to unfollow the podcast.
5. The podcast will no longer appear in your library or influence your recommendations.
Q: Can I rate a podcast on Spotify to affect its recommendations?
A: Yes, you can rate a podcast on Spotify to provide feedback and potentially influence its recommendations. Start by playing an episode of the podcast you want to rate, then tap the “Three Dots” icon while the episode is playing. Select “Rate Show” from the options provided and give the podcast a low rating if you dislike it. Your rating will be considered by Spotify’s algorithm when generating future recommendations.
Q: Are there third-party apps or scripts to block podcasts on Spotify?
A: While there are third-party apps and scripts available that claim to block or hide podcasts on Spotify, it’s important to exercise caution when using them. Research their credibility and security thoroughly before granting them access to your Spotify account.
Q: How does Spotify generate podcast recommendations?
A: Spotify’s recommendations are based on a combination of factors, including your listening habits, user ratings, and the listening habits of others with similar tastes. By analyzing these data points, Spotify’s algorithms generate personalized recommendations. Engaging with content you enjoy and providing feedback through ratings can help refine the recommendations over time.
Q: Will Spotify introduce a feature to block podcasts in the future?
A: While it’s uncertain what future updates may bring, Spotify continually evolves its platform based on user feedback and demands. It’s possible that additional features for customizing podcast recommendations, including blocking options, may be introduced in the future. Stay tuned for any updates from Spotify.
Conclusion:
While Spotify doesn’t offer a direct way to block podcasts, you can still manage your recommendations effectively. Unfollowing unwanted podcasts and rating them can help reduce their appearance. By understanding Spotify’s algorithm and leveraging its promotional tools, you can enhance your listening experience and make the most of this incredible music discovery platform. Happy exploring!
Related Articles
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Back to top button
0
Would love your thoughts, please comment.x
()
x
Mail Icon | __label__pos | 0.992223 |
Learning math at J.G. Simcoe P.S. – Mrs. Seymour’s Grade 3/4 Class
Learning math at J.G. Simcoe P.S. – Mrs. Seymour’s Grade 3/4 Class
Welcome to learning in limestone our goal success for all Welcome to J.G. Simcoe Four shapes to choose from, so it’s a cube, I’ll remind you a cube, octagonal prism, octagonal prism Square based pyramid or triangle base pyramid. Basically, we are counting the edges and the vertices. So when you’re counting never remember to count at the top all the edges, then count the middle going down Mary and then count the ones at the bottom. So with the octagon we know there’s going to be eight at the top, eight down the middle, and eight up the bottom. I’m making a cube. The base tells the name. Square base, (pause), prism (off camera) No, pyramid. (Teacher asks) Why? Why is it a pyramid? (Student responds) Because it comes to a vertex. Yeah, so all of these edges meet at a vertex at the top so that makes this shape a square base pyramid. I went to this, then I counted, and put them all together. Yea!!! (hands clapping) (Class of students) Goodbye (waving)
Leave a Reply
Your email address will not be published. Required fields are marked * | __label__pos | 0.938575 |
/* * Copyright (C) 1997-2010 Andre Noll * * Licensed under the GPL v2. For licencing details see COPYING. */ /** \file para.h global paraslash definitions */ #include "config.h" #include #include #include #include #include #include /* time(), localtime() */ #include #include #include #include #include #include #include #include #include /* needed by create_pf_socket */ #include #include #include "gcc-compat.h" /** used in various contexts */ #define MAXLINE 255 /** Compute the minimum of \a x and \a y. */ #define PARA_MIN(x, y) ({ \ typeof(x) _min1 = (x); \ typeof(y) _min2 = (y); \ (void) (&_min1 == &_min2); \ _min1 < _min2 ? _min1 : _min2; }) /** Compute the maximum of \a x and \a y. */ #define PARA_MAX(x, y) ({ \ typeof(x) _max1 = (x); \ typeof(y) _max2 = (y); \ (void) (&_max1 == &_max2); \ _max1 < _max2 ? _max2 : _max1; }) /** Compute the absolute value of \a x. */ #define PARA_ABS(x) ({ \ typeof(x) _x = (x); \ _x > 0? _x : -_x; }) /** * Define a standard log function that always writes to stderr. * * \param loglevel_barrier If the loglevel of the current message * is less than that, the message is going to be ignored. * */ #define INIT_STDERR_LOGGING(loglevel_barrier) \ __printf_2_3 void para_log(int ll, const char* fmt,...) \ { \ va_list argp; \ if (ll < loglevel_barrier) \ return; \ va_start(argp, fmt); \ vfprintf(stderr, fmt, argp); \ va_end(argp); \ } /** Version text used by various commands if -V switch was given. */ #define VERSION_TEXT(prefix) "para_" prefix " " PACKAGE_VERSION \ " (" GIT_VERSION ": " CODENAME ")" "\n" \ "Copyright (C) 2010 Andre Noll\n" \ "This is free software with ABSOLUTELY NO WARRANTY." \ " See COPYING for details.\n" \ "Written by Andre Noll.\n" \ "Report bugs to .\n" /** Print out \p VERSION_TEXT and exit if version flag was given. */ #define HANDLE_VERSION_FLAG(_prefix, _args_info_struct) \ if (_args_info_struct.version_given) { \ printf("%s", VERSION_TEXT(_prefix)); \ exit(EXIT_SUCCESS); \ } /** Sent by para_client to initiate the authentication procedure. */ #define AUTH_REQUEST_MSG "auth rsa " /** Sent by para_server for commands that expect a data file. */ #define AWAITING_DATA_MSG "\nAwaiting Data." /** Sent by para_server if authentication was successful. */ #define PROCEED_MSG "Proceed." /** Length of the \p PROCEED_MSG string. */ #define PROCEED_MSG_LEN strlen(PROCEED_MSG) /** Sent by para_client to indicate the end of the command line. */ #define EOC_MSG "\nEnd of Command." /* exec */ int para_exec_cmdline_pid(pid_t *pid, const char *cmdline, int *fds); /* time */ int tv_diff(const struct timeval *b, const struct timeval *a, struct timeval *diff); long unsigned tv2ms(const struct timeval*); void d2tv(double, struct timeval*); void tv_add(const struct timeval*, const struct timeval *, struct timeval *); void tv_scale(const unsigned long, const struct timeval *, struct timeval *); void tv_divide(const unsigned long divisor, const struct timeval *tv, struct timeval *result); int tv_convex_combination(const long a, const struct timeval *tv1, const long b, const struct timeval *tv2, struct timeval *result); void ms2tv(const long unsigned n, struct timeval *tv); void compute_chunk_time(long unsigned chunk_num, struct timeval *chunk_tv, struct timeval *stream_start, struct timeval *result); /** The enum of all status items. */ enum status_items {STATUS_ITEM_ENUM NUM_STAT_ITEMS}; extern const char *status_item_list[]; /** Loop over each status item. */ #define FOR_EACH_STATUS_ITEM(i) for (i = 0; i < NUM_STAT_ITEMS; i++) int for_each_stat_item(char *item_buf, size_t num_bytes, int (*item_handler)(int, char *)); __printf_2_3 void para_log(int, const char*, ...); /** * Write a log message to a dynamically allocated string. * * \param fmt Usual format string. * \param p Result pointer. * * \sa printf(3). */ #define PARA_VSPRINTF(fmt, p) \ { \ int n; \ size_t size = 100; \ p = para_malloc(size); \ while (1) { \ va_list ap; \ /* Try to print in the allocated space. */ \ va_start(ap, fmt); \ n = vsnprintf(p, size, fmt, ap); \ va_end(ap); \ /* If that worked, return the string. */ \ if (n > -1 && n < size) \ break; \ /* Else try again with more space. */ \ if (n > -1) /* glibc 2.1 */ \ size = n + 1; /* precisely what is needed */ \ else /* glibc 2.0 */ \ size *= 2; /* twice the old size */ \ p = para_realloc(p, size); \ } \ } /** * Return a random non-negative integer in an interval. * * \param max Determines maximal possible return value. * * \return An integer between zero and \p max - 1, inclusively. */ _static_inline_ long int para_random(unsigned max) { return ((max + 0.0) * (random() / (RAND_MAX + 1.0))); } /** Divide and round up to next integer. */ #define DIV_ROUND_UP(x, y) ({ \ typeof(y) _divisor = y; \ ((x) + _divisor - 1) / _divisor; }) /** Get the size of an array */ #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) /** * Wrapper for isspace. * NetBSD needs this. */ /* * The values should be cast to an unsigned char first, then to int. * Why? Because the isdigit (as do all other is/to functions/macros) * expect a number from 0 upto and including 255 as their (int) argument. * Because char is signed on most systems, casting it to int immediately * gives the functions an argument between -128 and 127 (inclusive), * which they will use as an array index, and which will thus fail * horribly for characters which have their most significant bit set. */ #define para_isspace(c) isspace((int)(unsigned char)(c)) /** Data that indicates an eof-condition for a fec-encoded stream. */ #define FEC_EOF_PACKET "\xec\x0d\xcc\xfe\0\0\0\0" \ "\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0" #define FEC_EOF_PACKET_LEN 32 /** Used to avoid a shortcoming in vim's syntax highlighting. */ #define EMBRACE(...) { __VA_ARGS__} /** * The sample formats supported by paraslash. * * It may be determined by one of the following sources: * * 1. The decoding filter (para_audiod only). In this case, it is always * \p SF_S16_LE which is the canonical format used within decoders. * * 2. The wav header (para_write only). * * 3. The --format option of para_write. */ #define SAMPLE_FORMATS \ SAMPLE_FORMAT(SF_S8, "8 bit signed"), \ SAMPLE_FORMAT(SF_U8, "8 bit unsigned"), \ SAMPLE_FORMAT(SF_S16_LE, "16 bit signed, little endian"), \ SAMPLE_FORMAT(SF_S16_BE, "16 bit signed, big endian"), \ SAMPLE_FORMAT(SF_U16_LE, "16 bit unsigned, little endian"), \ SAMPLE_FORMAT(SF_U16_BE, "16 bit unsigned, big endian"), \ #define SAMPLE_FORMAT(a, b) a enum sample_format {SAMPLE_FORMATS}; #undef SAMPLE_FORMAT #define SAMPLE_FORMAT(a, b) b /** Debug loglevel, gets really noisy. */ #define LL_DEBUG 0 /** Still noisy, but won't fill your disk. */ #define LL_INFO 1 /** Normal, but significant event. */ #define LL_NOTICE 2 /** Unexpected event that can be handled. */ #define LL_WARNING 3 /** Unhandled error condition. */ #define LL_ERROR 4 /** System might be unreliable. */ #define LL_CRIT 5 /** Last message before exit. */ #define LL_EMERG 6 /** Number of all loglevels. */ #define NUM_LOGLEVELS 7 /** Log messages with lower priority than that will not be compiled in. */ #define COMPILE_TIME_LOGLEVEL 0 /** \cond */ #if LL_DEBUG >= COMPILE_TIME_LOGLEVEL #define PARA_DEBUG_LOG(f,...) para_log(LL_DEBUG, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_DEBUG_LOG(...) do {;} while (0) #endif #if LL_INFO >= COMPILE_TIME_LOGLEVEL #define PARA_INFO_LOG(f,...) para_log(LL_INFO, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_INFO_LOG(...) do {;} while (0) #endif #if LL_NOTICE >= COMPILE_TIME_LOGLEVEL #define PARA_NOTICE_LOG(f,...) para_log(LL_NOTICE, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_NOTICE_LOG(...) do {;} while (0) #endif #if LL_WARNING >= COMPILE_TIME_LOGLEVEL #define PARA_WARNING_LOG(f,...) para_log(LL_WARNING, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_WARNING_LOG(...) do {;} while (0) #endif #if LL_ERROR >= COMPILE_TIME_LOGLEVEL #define PARA_ERROR_LOG(f,...) para_log(LL_ERROR, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_ERROR_LOG(...) do {;} while (0) #endif #if LL_CRIT >= COMPILE_TIME_LOGLEVEL #define PARA_CRIT_LOG(f,...) para_log(LL_CRIT, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_CRIT_LOG(...) do {;} while (0) #endif #if LL_EMERG >= COMPILE_TIME_LOGLEVEL #define PARA_EMERG_LOG(f,...) para_log(LL_EMERG, "%s: " f, __FUNCTION__, ## __VA_ARGS__) #else #define PARA_EMERG_LOG(...) #endif /** \endcond */ | __label__pos | 0.998334 |
Sometime nodes contain link to local picture or to webservices which generates pictures (e.g. node name = person + pic or node name = chemical structure). it would be good to have a "mouse on" feature which allows user to let this picture pop up while on the node or with a simple click on it. | __label__pos | 0.986978 |
SoapUI_OS_900x110
Automated Security Testing with soapUI and Hudson
You’ve seen the conference session, attended the webinar, and now here is the blog post that gives you an overview of the security testing features in soapUI 4.0 and how you can automate them using more or less any scheduling tool you might prefer (we like Hudson).
Background
When we reached out to our users with an online survey a couple of years ago the one feature that was requested most was “Security Testing” – something that caught us by surprise but makes a lot of sense when you come to think of it; just like for example performance, security is a non-functional requirement that can have severe consequences if neglected – look at Sony, Facebook, Nokia, MySQL, etc. – all major corporations that in the last years have been subject to relatively simple SQL Injection attacks which have exposed data not meant to be public – most notably in Sony’s case where over 1 million user records including addresses, etc. were exposed and leaked to the public.
Our philosophy behind the Security Testing features in soapUI is the same as for soapUI LoadTests; make it easy (and free!) for our users to add basic security tests for their services allowing them to scan for common vulnerabilities without requiring too much investment in time. This will build both awareness of security-related problems and provide a starting-point for digging deeper into security issues with soapUI or other tools more fit for the specific need. soapUI Pro makes the process even easier by providing a number of related wizards but the core functionality described below is fully available in the free version also.
What is Functional Security Testing Anyway?
Let’s back up a bit and try to define our domain here; when malicious requests are sent to a system a number of technical layers can be targeted, including;
1. The NIC (Network interface Card) and its drivers
2. The Operating System itself as it processes the incoming request from the NIC
3. The target application server that handles the request (for example Apache, IIS, etc.)
4. The application itself which provides some kind of functionality to the end user
While the attacks targeted at the first 2 layers often use brute force to exploit vulnerabilities in handling of connections, memory, etc., attacks at layer 3 and 4 usually target at vulnerabilities related to the actual functionality of the application itself – for example an application server might have a security flaw related to how it handles session identifiers while an application might have vulnerabilities related to how it performs specific functionality to the client (for example searching, updating of data, etc.). When it comes to the first 3 layers there are already a number of great tools out there (both free and commercial) that help you to identify related vulnerabilities, and since soapUI already has support for functional and performance testing of applications and their APIs, adding security testing to the mix was a natural choice, especially because this also happens to be a very common target for malicious attacks.
The model in soapUI for identifying functional security vulnerabilities is built on top of existing functional tests; in soapUI a Security Test extends an existing TestCase by allowing you to add a number of Security Scans after the desired TestSteps – these scans are executed after the corresponding TestStep and aim at identifying any vulnerabilities related to its input or output – the results for the Security Scan is asserted by using any of the built in Security Assertions (or any of the standard assertions if that fits better). The following picture can be used to illustrate;
SecurityScans
When running a Security Test, the underlying TestCase is thus executed as it would be if it were running as a standalone functional test, and the configured Security Scans will be executed and their results asserted to find any corresponding vulnerabilities.
The following screenshot shows a Security Test for a simple login-logout TestCase with SQL Injection and Fuzzing Security Scans configured and executed for the login request;
(Head over to the soapUI website to read more about soapUI SecurityTests)
How to Identify Vulnerabilities?
As hinted above, soapUI uses assertions to check for vulnerabilities – let’s discuss this in a little more detail before we move on to looking at some actual Security Scans.
When you come to think of it – how would you identify security vulnerabilities in the first place? What response would you get back when trying (for example) a SQL Injection attack that would allow you to identify that a security vulnerability is at hand? Actually, this isn’t always as easy as it sounds. An obvious sign of a “successful” attack is that your target service stops responding to requests (i.e. it crashes), but this is a relatively unusual finding (but very valuable since you found it first!). More often you will get an error message back that tells you that the service was not able to process the (malicious) request – this might be a good thing during development but it is also one of those situations where you need to take on the hat of the hacker; does the error message tell the client something they shouldn’t know about your system? For example which database you are using? Which version? Which language or framework? Maybe it exposes internal IP numbers (“failed to connect to…”)? Any of these might be exactly what the client is looking for; the information allows them to target specific attacks at your systems infrastructure (there are public databases of known security issues in most software) which in turn might give them the backdoor they have been looking for. soapUI provides a specific assertion for detecting these kinds of responses, we call it the “Sensitive Information Exposure” assertion; it searches messages returned by your service for any information that might expose system details to the client – version numbers, software technologies, etc. The list is of course configurable so if you come up with some text to search for that you absolutely don’t want to be exposed by mistake in your services you can add this to the global configuration and make sure that it isn’t exposed by any of your services during a security test.
Unfortunately it gets harder: often injection attacks can be more-or-less silent, meaning that the response might not give any indication of that the attack actually succeeded at all – or it might be something very specific to your service. For example, if we configure a SQL Injection Scan to target a login request, what we don’t want to get from the service while testing is a successful login. Here a standard soapUI XPath assertion fits nicely; it can be configured to check the response for each SQL Injection attempt to check that it is not returning a sessionId but instead an error message (that of course doesn’t expose any unnecessary system information). In the case of the response not giving any hint at all, maybe a script assertion is needed to check the state of the database after the request to ensure that all is OK.
So to recap;
• Security Tests resulting in a Denial of Service are unusual but valuable in the sense that you found them first and can make sure that they won’t happen again
• Security Tests resulting in error messages or responses that somehow expose system information that could be misused by a client can be identified by using the Sensitive Information Exposure assertion
• Many times the actual responses to a Security Test and how to interpret them from a security point of view is up to the tester and requires corresponding system knowledge and understanding to be able to create corresponding assertions that would pinpoint exploits in responses (without resulting in unnecessary false positives)
What can we Test For?
soapUI 4.0 comes with a total of 10 Security Scans that mimic some of the most commons Security Attacks being used today;
• SQL and XPath Injection Security Scans try to provoke corresponding vulnerabilities in the server code.
• Invalid Data, Boundary Check, Fuzzing and Malicious Attachment Security Scans send invalid input to provoke error unexpected errors and corresponding error messages that might exposes system information
• Malformed XML and XML Bomb Security Scans try to exploit vulnerabilities in the target systems XML processing – XML Bombs could potential result in a DOS attack if the server is not correctly protected or configured.
• Cross Site Scripting Scan helps you check for both persistent and non-persistent XSS vulnerabilities
• Script Security Scan (in true soapUI spirit) allows you to script your own parameter mutations in the groovy scripting language
Supported Protocols and APIs
As mentioned above, soapUI layers Security Scans on top of existing requests in your TestCases, which applies to any requests that are parameterized or contain XML as the payload. This includes
• SOAP Requests – any element or attribute in the request can be used as a parameter by the security scans. This is for requests sent over HTTP, HTTPS or JMS
• REST / HTTP Requests that send XML in their body (POST and PUT) – the same parameterization applies here as for SOAP requests
• REST / HTTP / AMF Requests with parameters – these parameters can be targeted by Security Scans as well
Before we head on to the idea and practice behind automation of Security Tests, let’s have a quick look at two of the most common Security Attacks and how they can be tested for with soapUI.
SQL Injection Attacks
SQL Injection attacks are the most common attacks against modern websites. The reason for this being (at least) twofold;
• Most sites are backed by a database which needs to be accessed from the web/service application. Sloppy coding (which is very common) at this level will make way for exploits.
• These Databases often hold data that is of value to hackers (email addresses, credit-card numbers, etc.) making them more attractive than attacks that don’t provide any “value” to the attackers.
To illustrate how simple a SQL Injection attack is consider the following SQL Statement used to validate the username/password sent to a login script;
• select * from tb_user where username = ‘%uname%’ and password = ‘%pwd%’
• If the input to the script is a valid uname/pwd combination, the actual SQL code executed will be as follows;
• For uname = bob, pwd = fish
• select * from tb_user where username= ’bob’ and password = ’fish’
If there is such a username/password combination in the database, the user will be found and logged in to the system, all is fine.
Now let’s look what happens if the input is the following;
• For uname = bob, pwd = ’ or ‘1’ = ‘1
• select * from tb_user where username= ’bob’ and password = ’’ or ‘1’ = ‘1’
The value provided as a password actually “melts into” the existing SQL used to validate the user and results in a SQL statement that will always return rows from the database, no matter what username is provided, resulting in the user always being logged in – pure evil!
Obviously building SQL statements as shown above should not be a viable option, but unfortunately this “concatenation” approach is indeed very common, especially in more modern (and therefore often immature) frameworks / platforms, which partially explains why these vulnerabilities are still so prevalent.
So how would you detect this in soapUI? Well, as already hinted above, a more specific XPath assertion could be used to detect that an invalid SQL statement does not result in a successful login. The complete setup in soapUI would be as follows;
From top to bottom in this (somewhat confusing) screenshot we can see the following;
1. A Security Test that performs a SQL Injection Scan for the login request
2. The SQL Injection Scan Configuration Dialog which has two parameters (username and password) configured into which it will insert a number of preconfigured SQL statements to mimic a SQL Injection attack. The XPath Match assertion for the Security Scan is visible at the bottom of the configuration dialog.
3. The XPath Match Configuration dialog contains an XPath statement that counts the number of return values in the response (session ids) and expects that value to be 0 (otherwise the request would have succeeded in logging in).
Running this test gives the following entries in the Security Run log;
Here you can see that the first injection actually succeeded in logging in (it used the same SQL hack as I did in my above code example). The following injections that all sent possible exploits did not succeed in generating a valid session id.
Cross Site Scripting
Cross-Site Scripting attacks (“XSS” attacks) are also one of the most common attacks targeted at both web applications and their APIs. The attack usually exploits deficiencies in a client web application where it injects a script that is executed in the browser and there can record user actions, passwords, etc and relay them to a separate server without the user ever noticing.
The attack can be performed in two main ways;
• Non-Persistent Attacks: include a malicious client-side script in a request that will then be part of the response web page and executed in the client browser. This is squarely targeted at web applications, for example a search page might display the actual search string in the response page (“you searched for…”) without escaping it; if the search string is a full-blown script it would be executed in the client and could perform corresponding unwanted actions.
• Persistent Attacks: stores a malicious client-side script into server-side storage (for example a database) from each it will later be displayed in another web-page. This attack can target both web interfaces and their APIs that may be exposed to update the underlying data; for example a REST interface might be available for updating database records via JSON – inserting malicious content here might result in it being displayed in a totally separate web page showing database content, and if that page is insecure, just as the page in the example for non-persistent attacks, the same exploits could apply.
Testing for these two is relatively easy but prone to false positives; the test basically makes a request containing some non-malicious script and then checks either the response page or other pages (for persistent attacks) if they contain these scripts unmodified. The trick here is that scripts can be returned in a web page unmodified but still escaped which will result in false positives if simple checking for the string itself.
The soapUI Cross-Site Scripting Scan does just this; it inserts a number of known simple scripts into the configured request parameters and will then check both the immediate response and secondary web-pages to see if they contain the script unmodified. The configuration is as follows;
• At the top you can see the search parameter configured in the Cross Site Scripting Scan dialog
• The dedicated “Cross Site Scripting Detection” assertion has been added and its configuration dialog is shown below – here you can select to
• check the immediate response for the inserted content
• specify a custom script that builds a list of secondary URLs that will be checked for the inserted content; the reason this being a script is that you might need to include some kind of id or other dynamic parameters into these URLs based on the immediate response received by the initial request (for example the response might contain the unique ID of an item that the request created and this must be passed as a parameter to the secondary requests).
You can hopefully see from both of these examples that the exploit mechanics are actually not very advanced or hard to understand, which actually stands true for most security vulnerabilities and hopefully gives you the incitement to both consider and test for them during development and testing phases of your product lifecycle.
Automating Security Tests
So finally we arrive at the automation part of this article. The idea behind automating security test execution is straight-forward; run your security tests repeatedly to detect any security vulnerability regressions that might be introduced into your code or system while it is being developed. Changes that might trigger such a regression could be:
• Component Updates – changing a third-party component or library might for example change error handling or error messages to be more verbose and expose unnecessary information to the client
• Infrastructure Changes – upgrading or introducing key components into an existing infrastructure might change how requests are processed or handled
• Refactoring of Code – just like unit-tests catch functional errors introduced by refactoring, security tests will hopefully find errors like error messages, injection or XSS exploits, etc.
soapUI provides a command-line securityrunner.bat/.sh file that allows you to run your security tests in a headless environment and will generate a corresponding report for you. Automating this with Hudson is (almost) a no-brainer;
1. Create a new free-style software project job in Hudson
1. Configure an “Execute Windows batch command” build step and correspond triggers and Post-build actions:
1. (Make sure you have –j option specified for the command-line runner so it outputs the JUnit-compatible reports used by the Post-build action further down)
2. If you are hosting the soapUI project in a code repository configure the corresponding connections under the “Source Code Management” section of the Job configuration
Now you are all set! If you run the Job in Hudson the soapUI securitytestrunner will execute the configured Security Tests allowing you to follow the output in the Console;
Any errors will be shown in the log as the tests run;
And the end of the log will show the status of the execution;
Going back to the Project view in Hudson will show an aggregated view of the historic executions;
And digging into the last result will show you
Piece of cake!
Final Words
I hope I have gotten these points across;
• Neglecting possible security vulnerabilities and related issues in your services and APIs can put your data (and your business!) at serious risk.
• Taking security seriously and building basic expertise around it is an investment well worth making.
• The core mechanics of most security vulnerabilities are easy to understand, test for, and prevent.
• With the new Security Testing features in soapUI 4.0 there is really no good reason to not do at least a very basic Security Testing baseline checking for the most common vulnerabilities.
• Automating the execution of your Security Tests (soapUI or not) further builds your awareness of and defense against unnecessary vulnerabilities.
So, head right over to the soapUI website to download the latest version (you might even opt for a soapUI Pro Trial if you want to cut some corners) and get grooving with your first security test.
Thanks for your time!
Ole
References
And be sure to follow and share with us on Twitter, Facebook and Linkedin.
Comments
1. thanks for sharing. It helps me a lot in Automated security testing.
I am middle of doing automated security testing,
can you please explain, how to write a assertions..?
Adv. Thanks for reply..:)
Speak Your Mind
* | __label__pos | 0.547385 |
Marko Radakovic
Revision history of an object change in a SQL database using Team Foundation Server
May 31, 2016 by
Similarly, as described previously in this article, where the revision history is covered for the Git source control system, we’ll present the workflow of reviewing the history of committed SQL database objects using Team Foundation Server (TFS) source control system. In order to use TFS and have SQL database objects being version controlled, Visual Studio is required, as well as TFS server, either installed on a machine or TFS through Team Services, which is actually TFS “in the cloud”.
This article covers the following: revision history review, comparing between versions of the same SQL database object in two changesets, getting specific version of an object, and applying it against a database.
For the purpose of this article, TFS server is installed and initially set. Using Visual Studio, a new TFS project (repository) called StoreDB is created. It is assumed that the Visual Studio is installed in order to access the TFS server (in particular TFS repository). In addition to this, SQL database objects are already scripted, initially committed to the repository, and additional changes (shown below) are made against a database and committed to the TFS project in order to show the history of committed changesets. There will be no explanation about the installation process or setting up for the TFS server/repository, performing commits, and making changes in SQL database.
As a starting point, the following changes are committed to the repository:
• Initial commit of all database objects
• Created a new table dbo.Currency using the following script:
• A column renamed from Name to CurrencyName in the dbo.Currency table using the following script:
Revision history review using Visual Studio
In order to get to the history of committed changes in Visual Studio, navigate to the Source Control Explorer pane, from the Team Explorer pane:
This shows a list of all objects that are being version controlled, under the StoreDB project:
To access the project history, make sure that the Folders icon is selected in the main toolbar, which will show the TFS project structure. Right click the project (in this case StoreDB) and select the View history option:
This initiates the History tab, showing the list of all committed changes:
For instance, the list shown in the above image represents changes performed against a database that are committed to the TFS project. From this point, the only way to explore the exact changeset is using the Comment column. To inspect the specific changeset in details, right click on it and select the Changeset Details option:
This will open the changeset details in the Team Explorer pane, showing all information from the previously inspected list of committed changesets that includes the timestamp of the commit (in this case 05/27/2016 11:04:14 AM), changeset ID (Changeset 7), comment (Created new table dbo.Currency) and a list of all files included in the changeset (in this case it is a single SQL file for the dbo.Currency table):
In the right click menu of any file from the changeset, there are options to open/review the file (either in the Source Control Explorer pane or to review the actual script in the new tab):
For instance, clicking the Open command opens the actual SQL script of the selected object:
The above image shows the version of the dbo.Currency table from the specific changeset (in this case Changeset 7). To view the entire history for the single object, right click on it (from the specific changeset through the Team Explorer menu as shown above, or from the Source Control Explorer tree), and select the View history option. Since the above right-click menu is shown from the Team Explorer pane, the following is the option shown in the Source Control Explorer right click menu:
Choosing any of the above presented options to review the history of committed changesets for the specific object gives the same result:
The above image shows the list of all changes made against the specific object (in this case the dbo.Currency table), along with the information who made changes, when, and what is the comment used when the change was committed.
Compare between versions
There are a lot of comparison options in TFS. On top of that, you can compare one project with any other project as well as any folder/file under the project with any folder/file from other project. For expedience sake, we’ll not go in details about explaining all of the combinations. Instead, we’ll focus on a comparison between different version of the same object in two changesets. For this purpose, we’ll use the dbo.Currency table since it is initially added in the first commit, the Name column is renamed to CurrencyName, and committed in another changeset.
To compare two changesets, right click on one of them, from the history of committed changesets and choose the Compare option (the same can be achieved by highlighting the changeset and clicking the Compare button from the toolbar):
This initiates the Compare form, where the source and the target for the comparison should be specified. By default, the changeset that is highlighted in the list or right-clicked, will be set as a source (The Source Path field is set to point to the StoreDB project, and the previously highlighted Changeset 7 is already specified). The user should specify the target changeset (in this case, we specified the same project as the Target Path value).
The target version can be either a changeset, the latest version, a label, or the version of an object from the local workspace, which is actually the latest state of the object that is not yet committed to the repository. Since the goal is to compare the version of the dbo.Currency table from the Changeset 7 (where the initial version of the table is committed), and the Changeset 8 (one of the columns is renamed), we will set the target to Changeset 8:
After clicking the OK button, the comparison will run, giving the following results in this particular case:
At this point, the comparison confirms that there are differences. In case there are multiple files committed in a single changeset, all of them will be shown after the comparison, on the appropriate side (source or target), along with the information about the differences. In order to see the exact differences, right click on the pair of objects in the list, and select the Compare Files option (or highlight the pair and click the Compare button from the upper toolbar):
This will give the line-by-line comparison of two different version of an object:
The result shows that there are actually two different lines, the one for the renamed column, and another one that holds the timestamp of saving the script. This way, the version of an object from one changeset can be compared with another version of the same object from another changeset.
Get specific version
To get specific version of an object, navigate to the history for that object, and right click on the changeset and select the Rollback Entire Changeset option:
All changes from the selected changeset will be reverted locally, and prepared to be committed:
In case there are multiple files in a single changeset, but only specific ones are meant to be reverted, simply undo the unwanted files using the Undo option from the right-click context menu:
Since the changeset where the dbo.Currency table is committed contains a single object, there’s nothing to be reverted. By providing the check-in comment and clicking the Check-in button, the previously reverted change will replace the latest version of the dbo.Currency table on the repository. This way any version of an object from the history of committed changesets can be reverted.
Marko Radakovic
Marko Radakovic
Marko is an IT and technical education teacher, who likes movies, video games, and heavy metal music.
He uses his spare time to play guitar, ride a bike and hang out with his friends. During winter, he likes skiing the most, but all other snow activities, too.
He is also author of various SQL Shack articles about SSIS packages and knowledgebase articles about ApexSQL Doc.
View all posts by Marko Radakovic
Marko Radakovic
Source Control
About Marko Radakovic
Marko is an IT and technical education teacher, who likes movies, video games, and heavy metal music. He uses his spare time to play guitar, ride a bike and hang out with his friends. During winter, he likes skiing the most, but all other snow activities, too. He is also author of various SQL Shack articles about SSIS packages and knowledgebase articles about ApexSQL Doc. View all posts by Marko Radakovic
1,557 Views | __label__pos | 0.542587 |
Oracle数据库数据字典
查看:
SYS.ALL_ALL_TABLES
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ALL_TABLES描述了当前用户可访问的对象表和关系表。
描述:
ALL_ALL_TABLES describes the object tables and relational tables accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_ATTR_CLASS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_ATTR_CLASS描述了数据库中当前用户可以访问的分析视图属性分类。
描述:
ALL_ANALYTIC_VIEW_ATTR_CLASS describes analytic view attribute classifications accessible to the current user in the database.
查看:
SYS.ALL_ANALYTIC_VIEW_BASE_MEAS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_BASE_MEAS描述了当前用户可访问的分析视图中的所有基本度量。
描述:
ALL_ANALYTIC_VIEW_BASE_MEAS describes all of the base measures in the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_CALC_MEAS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_CALC_MEAS在当前用户可访问的分析视图中描述所有计算出的度量。
描述:
ALL_ANALYTIC_VIEW_CALC_MEAS describes all of the calculated measures in the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_CLASS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_CLASS描述了当前用户可访问的所有分析视图的分类。
描述:
ALL_ANALYTIC_VIEW_CLASS describes the classifications of all analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_COLUMNS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_COLUMNS描述了当前用户可访问的分析视图的列。
描述:
ALL_ANALYTIC_VIEW_COLUMNS describes the columns of the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_DIM_CLASS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_DIM_CLASS描述了当前用户可访问的所有分析视图中的属性维的分类。
描述:
ALL_ANALYTIC_VIEW_DIM_CLASS describes the classifications of the attribute dimensions in all analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_DIMENSIONS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_DIMENSIONS描述与当前用户可访问的分析视图关联的属性维。
描述:
ALL_ANALYTIC_VIEW_DIMENSIONS describes the attribute dimensions associated with the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_HIER_CLASS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_HIER_CLASS在当前用户可访问的所有分析视图中描述层次结构的分类。
描述:
ALL_ANALYTIC_VIEW_HIER_CLASS describes the classifications of the hierarchies in all analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_HIERS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_HIERS描述了当前用户可访问的分析视图中的所有层次结构。
描述:
ALL_ANALYTIC_VIEW_HIERS describes all of the hierarchies in the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_KEYS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_KEYS描述了当前用户可访问的分析视图中属性维的键列。
描述:
ALL_ANALYTIC_VIEW_KEYS describes the key columns of the attribute dimensions in the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_LEVEL_CLASS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_LEVEL_CLASS描述了当前用户可访问的所有分析视图的级别分类。
描述:
ALL_ANALYTIC_VIEW_LEVEL_CLASS describes the classifications of the levels of all analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_LEVELS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_LEVELS在当前用户可访问的分析视图中描述层次结构中的所有级别。
描述:
ALL_ANALYTIC_VIEW_LEVELS describes all of the levels in the hierarchies in the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_LVLGRPS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_LVLGRPS描述了当前用户可访问的分析视图度量和分析视图的级别组。
描述:
ALL_ANALYTIC_VIEW_LVLGRPS describes the analytic view measure and level groups of the analytic views accessible to the current user.
查看:
SYS.ALL_ANALYTIC_VIEW_MEAS_CLASS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEW_MEAS_CLASS描述了当前用户可访问的所有分析视图的度量的分类。
描述:
ALL_ANALYTIC_VIEW_MEAS_CLASS describes the classifications of the measures of all analytic views accessible to the current user..
查看:
SYS.ALL_ANALYTIC_VIEWS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_ANALYTIC_VIEWS描述了当前用户可访问的分析视图。
描述:
ALL_ANALYTIC_VIEWS describes the analytic views accessible to the current user.
查看:
SYS.ALL_APPLY
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_APPLY显示有关应用程序信息的信息,这些应用程序使消息从当前用户可访问的队列中出队。
描述:
ALL_APPLY displays information about the apply processes that dequeue messages from queues accessible to the current user.
查看:
SYS.ALL_APPLY_CHANGE_HANDLERS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_APPLY_CHANGE_HANDLERS在当前用户可访问的表上显示有关更改处理程序的信息。
描述:
ALL_APPLY_CHANGE_HANDLERS displays information about the change handlers on the tables accessible to the current user.
查看:
SYS.ALL_APPLY_CONFLICT_COLUMNS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_APPLY_CONFLICT_COLUMNS在当前用户可访问的表上显示有关冲突处理程序的信息。
描述:
ALL_APPLY_CONFLICT_COLUMNS displays information about the conflict handlers on the tables accessible to the current user.
查看:
SYS.ALL_APPLY_DML_CONF_HANDLERS
版本:
19cR1 Release 1
所有者:
SYS
描述:
ALL_APPLY_DML_CONF_HANDLERS提供有关当前用户可见对象上DML冲突处理程序的详细信息。
描述:
ALL_APPLY_DML_CONF_HANDLERS provides details about DML conflict handlers on objects visible to the current user. | __label__pos | 0.994414 |
MASSA Autonomous Smart Contracts
MASSA Autonomous Smart Contracts
The advancement of decentralized technologies has been a remarkable phenomenon in the financial services industry and MASSA autonomous smart contracts have proven to be one of the most exciting innovations. The concept of MASSA autonomous smart contracts is a significant step forward in the world of financial services, and it has the potential to change the industry as we know it.
MASSA autonomous smart contracts are self-executing agreements that run on blockchain technology and are designed to enforce the terms of a contract without human intervention. The MASSA platform provides a decentralized infrastructure that enables the creation, management, and execution of these contracts, making it a game-changer for the financial services sector. By eliminating the need for intermediaries, MASSA has the potential to make traditional intermediaries such as banks and lawyers, redundant.
One of the key advantages of MASSA autonomous smart contracts is their transparency and trustworthiness. Since the contracts are executed on a decentralized blockchain network, the possibility of manipulation is almost non-existent. This makes MASSA ideal for financial transactions such as peer-to-peer lending or remittances, providing a secure and transparent way for parties to exchange value.
The efficiency of MASSA is another advantage that should not be overlooked. By automating the execution of contracts, the time and cost associated with intermediaries is significantly reduced. For instance, in the case of insurance, a smart contract can process a claim and pay out the benefit automatically, eliminating the need for an insurance adjuster. This has the potential to greatly increase access to financial services, especially for individuals and small businesses that are often marginalized by traditional financial institutions.
The potential of MASSA to disrupt the financial services industry is remarkable. By enabling individuals and businesses to directly transact with each other, the need for intermediaries is greatly reduced, leading to lower costs and increased accessibility. In the future, MASSA could also enable the creation of new financial products and services that were previously not possible. For example, it could be used to create decentralized insurance products that are transparent, secure, and less expensive than traditional insurance products.
In conclusion, the future of MASSA autonomous smart contracts in the financial services industry is a bright one. With its potential to revolutionize the way we think about financial services and its advantages of transparency, trustworthiness, and efficiency, MASSA has the potential to greatly benefit individuals and businesses alike. As technology continues to evolve, it will be interesting to see the new possibilities that emerge in the future.
Вернуться к списку статей | __label__pos | 0.738741 |
/******************************************************************************* * CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps * * version 0.1 * * Copyright (C) 2009-2012, IGG Team, LSIIT, University of Strasbourg * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, or (at your * * option) any later version. * * * * This library 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * * Web site: http://cgogn.unistra.fr/ * * Contact information: [email protected] * * * *******************************************************************************/ #include "tuto_orbits.h" #include #include "Algo/Modelisation/primitives3d.h" #include "Algo/Modelisation/polyhedron.h" #include "Algo/Modelisation/subdivision.h" #include "Algo/Render/GL2/topo3Render.h" #include "Algo/Render/SVG/mapSVGRender.h" #include "Algo/Import/import.h" MAP myMap; AttributeHandler position ; AttributeHandler middleDarts; void MyQT::text_onoff(bool x) { render_text = !render_text; updateGL(); CGoGNerr << " text_onoff " << CGoGNflush; } void MyQT::slider_text(int x) { m_strings->setScale(0.02f*x); updateGL(); } void MyQT::orbit_list(int x) { storeVerticesInfo(m_att_orbits[x]); current_orbit = x; if (m_clicked != Dart::nil()) { unsigned int orbs[9] = {VERTEX,EDGE,FACE,VOLUME,PFP::MAP::ORBIT_IN_PARENT(VERTEX),PFP::MAP::ORBIT_IN_PARENT(EDGE),PFP::MAP::ORBIT_IN_PARENT(FACE),PFP::MAP::ORBIT_IN_PARENT2(VERTEX),PFP::MAP::ORBIT_IN_PARENT2(EDGE)}; m_selected.clear(); // easy way to traverse darts of orbit TraversorDartsOfOrbit tra(myMap, orbs[current_orbit], m_clicked); for (Dart e = tra.begin(); e != tra.end(); e = tra.next()) m_selected.push_back(e); } // m_selected.clear(); updateGL(); } template void MyQT::storeVerticesInfo(const AttributeHandler& attrib) { SelectorDartNoBoundary nb(myMap); m_render_topo->computeDartMiddlePositions(myMap, middleDarts, nb); m_strings->clear(); for (Dart d = myMap.begin(); d != myMap.end(); myMap.next(d)) { if (nb(d)) { std::stringstream ss; ss << attrib[d]; m_strings->addString(ss.str(), middleDarts[d]); } } m_strings->sendToVBO(); } void MyQT::cb_initGL() { // choose to use GL version 2 Utils::GLSLShader::setCurrentOGLVersion(2); m_render_topo = new Algo::Render::GL2::Topo3Render(); SelectorDartNoBoundary nb(myMap); m_render_topo->updateData(myMap, position, 0.9f, 0.8f, 0.8f, nb); m_strings = new Utils::Strings3D(true, Geom::Vec3f(0.1f,0.0f,0.3f)); registerShader(m_strings); storeVerticesInfo(m_att_orbits[0]); } void MyQT::cb_redraw() { m_render_topo->drawTopo(); for (unsigned int i=0; i< m_selected.size(); ++i) m_render_topo->overdrawDart(m_selected[i], 7, 1.0f, 0.0f, 1.0f); if (render_text) m_strings->drawAll(Geom::Vec3f(0.0f, 1.0f, 1.0f)); } void MyQT::cb_mousePress(int button, int x, int y) { if (Shift()) { SelectorDartNoBoundary nb(myMap); m_clicked = m_render_topo->picking(myMap, x,y, nb); if (m_clicked != Dart::nil()) { unsigned int orbs[9] = {VERTEX,EDGE,FACE,VOLUME,PFP::MAP::ORBIT_IN_PARENT(VERTEX),PFP::MAP::ORBIT_IN_PARENT(EDGE),PFP::MAP::ORBIT_IN_PARENT(FACE),PFP::MAP::ORBIT_IN_PARENT2(VERTEX),PFP::MAP::ORBIT_IN_PARENT2(EDGE)}; m_selected.clear(); // easy way to traverse darts of orbit TraversorDartsOfOrbit tra(myMap, orbs[current_orbit], m_clicked); for (Dart e = tra.begin(); e != tra.end(); e = tra.next()) m_selected.push_back(e); } updateGL(); } } void MyQT::initMap() { std::cout << "INIT MAP"<< std::endl; position = myMap.addAttribute("position"); Algo::Modelisation::Primitive3D prim(myMap, position); int nb=2; prim.hexaGrid_topo(nb,nb,nb); prim.embedHexaGrid(1.0f,1.0f,1.0f); m_att_orbits[0] = myMap.addAttribute("vertex"); m_att_orbits[1] = myMap.addAttribute("edge"); m_att_orbits[2] = myMap.addAttribute("face"); m_att_orbits[3] = myMap.addAttribute("volume"); m_att_orbits[4] = myMap.addAttribute("vertex2"); m_att_orbits[5] = myMap.addAttribute("edge2"); m_att_orbits[6] = myMap.addAttribute("face2"); m_att_orbits[7] = myMap.addAttribute("vertex1"); m_att_orbits[8] = myMap.addAttribute("face1"); int i=0; TraversorV tra0(myMap); for (Dart d = tra0.begin(); d != tra0.end(); d = tra0.next()) { m_att_orbits[0][d] = i++; } i=0; TraversorE tra1(myMap); for (Dart d = tra1.begin(); d != tra1.end(); d = tra1.next()) { m_att_orbits[1][d] = i++; } i=0; TraversorF tra2(myMap); for (Dart d = tra2.begin(); d != tra2.end(); d = tra2.next()) { m_att_orbits[2][d] = i++; } i=0; TraversorW tra3(myMap); for (Dart d = tra3.begin(); d != tra3.end(); d = tra3.next()) { m_att_orbits[3][d] = i++; } i=0; TraversorCell tra02(myMap); for (Dart d = tra02.begin(); d != tra02.end(); d = tra02.next()) { m_att_orbits[4][d] = i++; } i=0; TraversorCell tra12(myMap); for (Dart d = tra12.begin(); d != tra12.end(); d = tra12.next()) { m_att_orbits[5][d] = i++; } i=0; TraversorCell tra22(myMap); for (Dart d = tra22.begin(); d != tra22.end(); d = tra22.next()) { m_att_orbits[6][d] = i++; } i=0; TraversorCell tra01(myMap); for (Dart d = tra01.begin(); d != tra01.end(); d = tra01.next()) { m_att_orbits[7][d] = i++; } i=0; TraversorCell tra11(myMap); for (Dart d = tra11.begin(); d != tra11.end(); d = tra11.next()) { m_att_orbits[8][d] = i++; } middleDarts = myMap.addAttribute("middle"); } int main(int argc, char **argv) { // un peu d'interface QApplication app(argc, argv); MyQT sqt; // interface de tuto5.ui Utils::QT::uiDockInterface dock; sqt.setDock(&dock); // message d'aide sqt.setHelpMsg("Select an orbit then\nshift click left to select a dart"); sqt.initMap(); // bounding box Geom::BoundingBox bb = Algo::Geometry::computeBoundingBox(myMap, position); float lWidthObj = std::max(std::max(bb.size(0), bb.size(1)), bb.size(2)); Geom::Vec3f lPosObj = (bb.min() + bb.max()) / PFP::REAL(2); // envoit info BB a l'interface sqt.setParamObject(lWidthObj, lPosObj.data()); sqt.setCallBack( dock.checkBox_text, SIGNAL(toggled(bool)), SLOT(text_onoff(bool)) ); sqt.setCallBack( dock.slider_text, SIGNAL(valueChanged(int)), SLOT(slider_text(int)) ); sqt.setCallBack( dock.Orbits, SIGNAL( currentIndexChanged(int)), SLOT(orbit_list(int)) ); sqt.show(); sqt.slider_text(50); // et on attend la fin. return app.exec(); } | __label__pos | 0.996626 |
Skip to main content
© OmniShop. All rights reserved.
Mobile app accessibility for better user experience
In ecommerce, your mobile app must be accessible to everyone, including people with disabilities. Mobile app accessibility refers to designing apps that are usable for people with a wide range of abilities. This includes those who have visual, auditory, motor, or cognitive disabilities. Making your app accessible means more people can use it, increasing your potential user base and improving overall user satisfaction.
Why mobile app accessibility matters
Mobile app accessibility breaks down barriers to digital interaction and ecommerce. With millions using mobile devices for online shopping, ensuring everyone can use these ecommerce apps is a matter of inclusivity and equity. This is also especially important for webshops, where accessibility can directly affect the ability to browse, select, and purchase products.
Mobile app accessibility and user experience
A great user experience (UX) is one that works for everyone. Mobile app accessibility plays a big role in creating and making these experiences great, which is very important in online shopping. An accessible app is friendly and welcoming to everyone. This approach to design helps you catch issues that could stumble your users even before they become problems (issues, not users).
Accessibility is an ongoing process that involves regular updates and feedback from users with disabilities. The best way to check this is actually to do the blind user testing. Engaging with your audience can help you understand their challenges and how you can address them. It improves your app’s accessibility, overall design, and user experience.
We’d strongly suggest integrating accessibility from the start. This makes your app more usable for everyone and positions your brand as caring and responsible, and in the competitive ecommerce space, that’s a powerful advantage.
The role of accessibility in webshop experience
For webshops, ensuring that product descriptions, navigation menus, and checkout processes are accessible can significantly improve the shopping experience for users with disabilities. It also leads to increased customer loyalty and a wider customer base.
Webshop accessibility checkups and remediation
Recognizing the importance of accessibility in ecommerce, Byteout offers accessibility checkups and remediation services. These checkups identify areas where your webshop may not meet accessibility standards, while remediation services help to correct these issues. By doing so, your digital presence is welcoming and accessible to all users, regardless of their physical or cognitive abilities.
Mobile app accessibility – practical steps
Making your mobile app accessible is important for reaching a broader audience, including users with disabilities. Start with the basics: ensure your app’s design considers various needs. Focus on designs everyone can easily see and use, like high-contrast colors and large, easy-to-tap buttons. Also, incorporate voice commands and ensure all images have descriptive alt text. Use large, readable fonts and ensure there’s enough contrast between text and background. These are simple changes that can make a big difference.
Next, test your app for accessibility and seek feedback from users with disabilities. This can help you identify and fix issues you might not have noticed. Regular testing with users who have disabilities is vital for gaining insight into real-world usability. Guidelines like the Web Content Accessibility Guidelines (WCAG) can also guide your efforts.
The business case for mobile app accessibility
There’s a strong business case for making your mobile app accessible.
• Accessibility can be a competitive advantage. In an industry where companies are constantly looking for ways to stand out, being known for an accessible app can put you ahead. It shows that you’re committed to serving all customers, which can boost brand loyalty and customer satisfaction.
• Making your app accessible now can save you from future legal issues. Inclusivity is essential for business success, so investing in mobile app accessibility is investing in your company’s future. Regulations around digital accessibility tighten each day.
Summary
It’s okay to start small and gradually make improvements. Every step you take towards making your app more accessible is a step towards inclusivity. Making a mobile app accessible is about recognizing the value of inclusivity. This way, ecommerce businesses can improve user experience, expand their customer base, and demonstrate a commitment to equality. Let’s make inclusivity the top priority in the digital world. Byteout’s service in accessibility checkups and remediation can help you achieve these goals, ensuring your ecommerce business is accessible to everyone.
Ready to step up your mobile game?
Let’s book a 30-min mobile strategy session and give your shop a boost.
Ready to step up your mobile game?
Let’s book a 30-min mobile strategy session and give your shop a boost. | __label__pos | 0.786487 |
aurelije (6) [Avatar] Offline
#1
I've read several times chapter 15.4 and always had to scratch my head with few misleading and fuzzy sentences.
Example 1:
Chapter15.4.4. Explicit joins, page 393:
For example, the following query and retrieves items that have no bids, and items with bids of a minimum bid amount:
select i, b from Item i
left join i.bids b on b.amount > 100
So we have now 3 types of Item objects:
1) Items without bids
2) Items with bids, where at least one bid is greater then 100
3) Items with bids, where all bids are lower then 100
The sentence "retrieves items that have no bids, and items with bids of a minimum bid amount" could mean that only type 1 and 2 of Items will be fetched, but that is not true, all items will be fetched but just not all Bids as second result in result pair.
aurelije (6) [Avatar] Offline
#2
Re: JPQL join explanations
For inner join
select i from Item i
join i.bids b
where b.amount > 100
Maybe it should be clarified that the result is list of all items that have at least one bid having amount > 100 but for each that item all bids will be loaded on item.getBids, not just those amount > 100
Message was edited by:
aurelije
aurelije (6) [Avatar] Offline
#3
And more then one year later the final version of book is out, but problems I reported here are not addressed at all. I am so disappointed. | __label__pos | 0.676109 |
How to take screenshot on windows 11?
Wondering how to take a screenshot on Windows 11? Discover the fastest method using the snipping tool and shortcut keys. Learn how to capture rectangular or freely selectable areas.
To begin, press the Windows Logo + Shift + S keys simultaneously on your keyboard. The snipping tool will appear at the top of your screen, offering a range of options. If you prefer a traditional square or rectangle shape, select the first option and release the mouse to capture the screenshot instantly. Alternatively, choose the second option for a more flexible approach. This allows you to freely move the cursor and select any area on your screen. By default, Windows 11 saves your screenshots in the Screenshots folder inside the Pictures folder.
You can also type “snipping tool” in the Start menu and click on “New” to use the snipping tool. Despite this being done on Windows 11, it works the same on Windows 10 as well.
Thank you.
SUBSCRIBE
SUBSCRIBE
Welcome to Hey, Let's Learn Something!
Please sign up here to receive the latest updates on our blogs, tutorials and download section :)
Thank you for subscribing :) | __label__pos | 0.610198 |
LDAP authentication - Gallery Codex
Personal tools
LDAP authentication
From Gallery Codex
(Redirected from Active Directory)
LDAP authentication in Gallery2 ...
Setup instructions
...
Forum discussions
Example Code
Note this code is an example from a user and not the developers of Gallery. It is my interpretation and works well enough for our use. In my opinion this should not be so difficult --Jkuter 06:25, 27 November 2007 (PST)
index.php embed script with ldap authentication
• This code is for passwordless login
• SESSION is unset in logout.inc
• login.php is another small file with an input that posts to the index.php
<?php
// look for a user id in the session, if its not there start the session so we can make one
if (!isset($_SESSION['emAppUserId'])) {
session_name('GalleryOnInside'); // Choose session name
session_set_cookie_params(1209600);
session_start(); // Initialize a session
}
// triggers embed classes for gallery so the below will work
require_once('embed.php');
// pull in gallery content and trigger user functions
$data = runGallery();
// set page title
$data['title'] = (isset($data['title']) && !empty($data['title'])) ? $data['title'] : 'Gallery';
//set up page html
if (isset($data['bodyHtml'])) {
print <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>{$data['title']}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
{$data['javascript']}
{$data['css']}
</head>
<body>
{$data['bodyHtml']}
</body>
</html>
EOF;
}
// Close Gallery Connection
GalleryEmbed::done();
function runGallery() {
// required configuration of embed vars
$embedUri = '/phpapps/gallery2/index.php';
$g2Uri = '/phpapps/gallery2/main.php';
$loginRedirect = '/phpapps/gallery2/login.php';
// see if this is an initial login and set username
$username = isset($_POST['username']) ? $_POST['username'] : "";
if ($username != "") {
// try and authenticate posted name
$auth = authenticateLogin($username);
if ($auth['ErrorCode'] == "Username and Password validated") {
//set config vars from LDAP
$_SESSION['emAppUserId'] = $auth['uid'];
$emAppUserLogin = $auth['cn'];
$emAppUserName = $auth['fullname'];
$emAppUserEmail = $auth['email'];
} else {
die('Authentication Failed: ' . $auth['ErrorCode']);
}
}
if (isset($_SESSION['emAppUserId'])) {
// if user is logged in, set user ID to emApp's session user_id
$emAppUserId = $_SESSION['emAppUserId'];
} else {
// if anonymous user, set g2 activeUser to ''
$emAppUserId = '';
}
// actually get gallery going passing all needed config
$ret = GalleryEmbed::init(array('embedUri' => $embedUri, 'g2Uri' => $g2Uri, 'fullInit' => true, 'loginRedirect' => $loginRedirect, 'activeUserId' => $emAppUserId));
// Display login link with our credentials from $loginRedirect
GalleryCapabilities::set('login', true);
if ($ret) {
// Did we get an error because the user doesn't exist in g2 yet?
$ret2 = GalleryEmbed::isExternalIdMapped($emAppUserId, 'GalleryUser');
if ($ret2 && $ret2->getErrorCode() & ERROR_MISSING_OBJECT) {
// The user does not exist in G2 yet. Create in now on-the-fly
$ret = GalleryEmbed::createUser($emAppUserId, array ( 'username' => $emAppUserLogin, 'email' => $emAppUserEmail, 'fullname' => $emAppUserName));
if ($ret) {
// An error during user creation. Not good, print an error or do whatever is appropriate
print "An error occurred during the on-the-fly user creation <br>";
print $ret->getAsHtml();
exit;
}
} else {
// The error we got wasn't due to a missing user, it was a real error
if ($ret2) {
print "An error occurred while checking if a user already exists<br>";
print $ret2->getAsHtml();
}
print "An error occurred while trying to initialize G2<br>";
print $ret->getAsHtml();
exit;
}
}
// At this point we know that either the user either existed already before or that it was just created
$g2moddata = GalleryEmbed::handleRequest();
// show error message if isDone is not defined
if (!isset($g2moddata['isDone'])) {
$data['bodyHtml'] = 'isDone is not defined, something very bad must have happened.';
return $data;
}
// exit if it was an immediate view / request (G2 already outputted some data)
if ($g2moddata['isDone']) {
exit;
}
// put the body html
$data['bodyHtml'] = isset($g2moddata['bodyHtml']) ? $g2moddata['bodyHtml'] : '';
// get the page title, javascript and css links from the <head> html from G2
$title = ''; $javascript = array(); $css = array();
if (isset($g2moddata['headHtml'])) {
list($data['title'], $css, $javascript) = GalleryEmbed::parseHead($g2moddata['headHtml']);
$data['headHtml'] = $g2moddata['headHtml'];
}
// Add G2 javascript
$data['javascript'] = '';
if (!empty($javascript)) {
foreach ($javascript as $script) {
$data['javascript'] .= "\n".$script;
}
}
// Add G2 css
$data['css'] = '';
if (!empty($css)) {
foreach ($css as $style) {
$data['css'] .= "\n".$style;
}
}
return $data;
}
function authenticateLogin($username) {
// ldap config
$server="ldap://myldap.server.com:389";
$basedn="dc=ad,dc=domainname,dc=com";
$filter="(&(objectclass=user)(cn=$username)(!(userAccountControl=66050))(!(objectclass=computer)))";
// try and connect
if (!($connect = ldap_connect($server))) {
$loginError = 'Could not connect to LDAP server';
} else {
// Logged in - Override some options
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
ldap_set_option($connect,LDAP_OPT_PROTOCOL_VERSION,3);
$bind = ldap_bind($connect);
// Search for the user to get the DN
$sr = ldap_search($connect,$basedn,$filter);
$info = ldap_get_entries($connect, $sr);
// set basic user info
$fullname=$info[0]["displayname"][0];
$cn=$info[0]["cn"][0];
$uid=$info[0]["uidnumber"][0];
$email=$info[0]["userprincipalname"][0];
$dn=$info[0]["dn"];
// Store key user information in an array to be returned
$result['fullname'] = $fullname;
$result['uid'] = $uid;
$result['cn'] = $cn;
$result['email'] = $email;
if ($dn != "") {
$loginError = 'Username and Password validated';
} else {
$loginError = "Bind Failed for $dn";
}
}
// set results of bind
$result['ErrorCode'] = $loginError;
return $result;
}
?>
LDAP UserLogin for Gallery 2.3
None of the given contributions met my needs for ldap authentication ... most of them didn't work or just seemed to work but also with wrong passwords!
I modified modules\core\UserLogin.inc to authenticate against an ActiveDirectory and it works perfectly for me.
I don't know a lot about error handling but I tried to use it correctly.
--W.stoettinger 10:18, 30 September 2009 (UTC)
Functionality
A User is first authenticated against the LDAP. If it does not exist, it is created in Gallery2, so no need for additional administration here. If the user does not exist in LDAP it is checked against the Gallery2 database so it's also possible to create Gallery-only users.
Installation
Place the code found below in your modules\core\UserLogin.inc and replace the settings to connect to you LDAP server (in Line 229 in the function ldapAuthentication).
Code
Replace your modules\core\UserLogin.inc with the following code:
<?php
/*
* Gallery - a web based photo album viewer and editor
* Copyright (C) 2000-2007 Bharat Mediratta
*
* This program 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; either version 2 of the License, or (at
* your option) any later version.
*
* 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 Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* This controller will handle a user logging in to Gallery
* @package GalleryCore
* @subpackage UserInterface
* @author Bharat Mediratta <[email protected]>
* @version $Revision: 15955 $
*/
class UserLoginController extends GalleryController {
/**
* ValidationPlugin instances to use when handling this request. Only used by test code.
*
* @var array $_plugins (array of GalleryValidationPlugin)
* @access private
*/
var $_pluginInstances;
/**
* Tests can use this method to hardwire a specific set of plugin instances to use.
* This avoids situations where some of the option instances will do unpredictable
* things and derail the tests.
*
* @param array $pluginInstances of GalleryValidationPlugin
*/
function setPluginInstances($pluginInstances) {
$this->_pluginInstances = $pluginInstances;
}
/**
* @see GalleryController::isAllowedInMaintenance
*/
function isAllowedInMaintenance() {
return true;
}
/**
* @see GalleryController::handleRequest
*/
function handleRequest($form) {
global $gallery;
$results = array();
$error = array();
if (isset($form['action']['login'])) {
if (empty($form['username'])) {
$error[] = 'form[error][username][missing]';
}
if (empty($form['password'])) {
$error[] = 'form[error][password][missing]';
}
if (empty($error)) {
list ($ret, $isDisabled) = GalleryCoreApi::isDisabledUsername($form['username']);
if ($ret) {
return array($ret, null);
}
if ($isDisabled) {
$error[] = 'form[error][username][disabled]';
}
}
if (empty($error)) {
list ($ret, $user) = GalleryCoreApi::fetchUserByUsername($form['username']);
if ($ret && !($ret->getErrorCode() & ERROR_MISSING_OBJECT)) {
return array($ret, null);
}
/* LDAP Code begin */
$ldapRet = $this->ldapAuthentication($form['username'],$form['password']);
if ($ldapRet && !is_array($ldapRet)) {
// any error with LDAP connection.
$error[] = "form[error]$ldapRet";
}
else if(is_array($ldapRet)){ // User found:
// At first login, create new User
if (!isset($user)) {
list ($ret, $user) = GalleryCoreApi::newFactoryInstance('GalleryEntity', 'GalleryUser');
if ($ret) {
return array($ret, null);
}
if (!isset($user)) {
return array(GalleryCoreApi::error(ERROR_MISSING_OBJECT), null);
}
$ret = $user->create($username);
if ($ret) { // this should never happen:
if (!($ret->getErrorCode() & ERROR_COLLISION)) {
return array($ret, null);
}
// Set our error status and fall back to the view
$error[] = 'form[error][userName][exists]';
}
}
// set the users properties and save them:
$user->setEmail($ldapRet['email']);
$user->setFullName($ldapRet['fullName']);
$user->changePassword($ldapRet['password']);
GalleryCoreApi::acquireWriteLock($user->getId());
$ret = $user->save();
GalleryCoreApi::releaseLocks($user->getId());
if ($ret) {
return array($ret, null);
}
}
else {
// User not found in LDAP should not be a problem: normal user autentication
}
/* LDAP Code end */
GalleryUtilities::unsanitizeInputValues($form['password'], false);
$isCorrect = (isset($user) && $user->isCorrectPassword($form['password']));
/* Prepare for validation */
$options = array('pass' => $isCorrect);
list ($ret, $options['level']) =
GalleryCoreApi::getPluginParameter('module', 'core', 'validation.level');
if ($ret) {
return array($ret, null);
}
if ($options['level'] == 'MEDIUM') {
$options['key'] = 'core.UserLogin.' . $form['username'];
}
if ($options['level'] == 'OFF') {
$pluginInstances = array();
} else if (isset($this->_pluginInstances)) {
$pluginInstances = $this->_pluginInstances;
} else {
list ($ret, $pluginInstances) =
GalleryCoreApi::getAllFactoryImplementationIds('GalleryValidationPlugin');
if ($ret) {
return array($ret, null);
}
foreach (array_keys($pluginInstances) as $pluginId) {
list ($ret, $pluginInstances[$pluginId]) =
GalleryCoreApi::newFactoryInstanceById('GalleryValidationPlugin',
$pluginId);
if ($ret) {
return array($ret, null);
}
}
}
/* Let each plugin do its verification */
foreach ($pluginInstances as $plugin) {
list ($ret, $pluginErrors, $continue) =
$plugin->performValidation($form, $options);
if ($ret) {
return array($ret, null);
}
$error = array_merge($error, $pluginErrors);
if (!$continue) {
break;
}
}
}
if (empty($error)) {
if ($isCorrect) {
$gallery->setActiveUser($user);
$event = GalleryCoreApi::newEvent('Gallery::Login');
$event->setEntity($user);
list ($ret, $redirect) = GalleryCoreApi::postEvent($event);
if ($ret) {
return array($ret, null);
}
/* Redirect if requested by event listener, otherwise return */
if (!empty($redirect)) {
$results['redirect'] = array_shift($redirect);
} else {
$results['return'] = 1;
}
} else {
$error[] = 'form[error][invalidPassword]';
}
}
if (!empty($error)) {
if (!empty($form['username'])) {
$event = GalleryCoreApi::newEvent('Gallery::FailedLogin');
$event->setData(array('userName' => $form['username']));
list ($ret, $ignored) = GalleryCoreApi::postEvent($event);
if ($ret) {
return array($ret, null);
}
}
}
} else if (isset($form['action']['cancel'])) {
$results['return'] = 1;
}
if (!empty($error)) {
$results['delegate']['view'] = 'core.UserAdmin';
$results['delegate']['subView'] = 'core.UserLogin';
}
$results['status'] = array();
$results['error'] = $error;
return array(null, $results);
}
/* LDAP Code begin */
public function ldapAuthentication($username, $password) {
$ldap = array('ldaphost' => 'ldap://ldap.domain.com',
'domain' => 'domain.com',
'dn' => 'ou=Users,dc=domain,dc=com',
'binduser' => 'CN=Proxy,ou=Users,dc=domain,dc=com',
'bindpass' => 'proxypassword'
);
// Open LDAP connection to server
$ldapconn = ldap_connect($ldap['ldaphost']);
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
// Bind with binduser as proxy to do the search
$proxyBind = ldap_bind($ldapconn, $ldap['binduser'], $ldap['bindpass']);
if (!$proxyBind) {
return "[invalidLDAPProxy]";
}
// search for the supplied username in the base DN
$ldapSearchResult = ldap_search($ldapconn, $ldap['dn'], "(sAMAccountName=".$username.")" , array( "*" ));
$ldapEntries = ldap_get_entries($ldapconn, $ldapSearchResult);
if ($ldapEntries["count"] < 1) {
return null;
}
$userdn = $ldapEntries[0]["dn"];
//use the found DN to bind again
$userBind = ldap_bind($ldapconn, $userdn, $password);
if (!$userBind) {
return "[invalidPassword]";
}
$user_info = array();
$user_info['fullName'] = $ldapEntries[0]["givenname"][0]." ".$ldapEntries[0]["sn"][0];
$user_info['email'] = $ldapEntries[0]["mail"][0];
$user_info['password'] = $password;
ldap_unbind($ldapconn);
return $user_info;
}
/* LDAP Code end */
}
/**
* This view prompts for login information
*/
class UserLoginView extends GalleryView {
/**
* @see GalleryView::loadTemplate
*/
function loadTemplate(&$template, &$form) {
global $gallery;
/* Check if the default login view URL has been overridden and redirect appropriately */
$loginRedirect = $gallery->getConfig('loginRedirect');
if (!(isset($loginRedirect['subView']) && $loginRedirect['subView'] == 'core.UserLogin')
&& !empty($loginRedirect)) {
/* Do not redirect if we are logged in already */
list ($ret, $isGuest) = GalleryCoreApi::isAnonymousUser();
if ($ret) {
return array($ret, null);
}
$phpVm = $gallery->getPhpVm();
$urlGenerator =& $gallery->getUrlGenerator();
if ($isGuest && !$phpVm->headers_sent()) {
$redirectUrl = $urlGenerator->generateUrl($loginRedirect,
array('forceSessionId' => false,
'forceFullUrl' => true));
$phpVm->header("Location: $redirectUrl");
$phpVm->exit_();
}
}
if ($form['formName'] != 'UserLogin') {
$form['formName'] = 'UserLogin';
$form['username'] = '';
/*
* When logging in we don't have a session yet, thus no navigation history / a place
* to store the returnUrl. Thus store the returnUrl in the login form
*/
$returnUrl = GalleryUtilities::getRequestVariables('return');
$form['returnUrl'] = !empty($returnUrl) ? $returnUrl : '';
}
$template->setVariable('controller', 'core.UserLogin');
return array(null, array('body' => 'modules/core/templates/UserLogin.tpl'));
}
}
?>
A note for those stuck with PHP4.x, "public function ldapAuthentication" will probably need to be just "function ldapAuthentication," and "$ret = $user->create($username);" didn't work until I changed it to "$ret = $user->create($form['username']);"
If your AD server is running in secure mode, change these lines:
#change ldap://ldap.domain.com to ldaps://ldap.domain.com
$ldap = array('ldaphost' => 'ldap://ldap.domain.com',
'domain' => 'domain.com',
##ADD THIS NEW LINE BELOW
'ldapport' => '123', #or whatever
'dn' => 'ou=Users,dc=domain,dc=com',
'binduser' => 'CN=Proxy,ou=Users,dc=domain,dc=com',
'bindpass' => 'proxypassword'
);
And change this:
$ldapconn = ldap_connect($ldap['ldaphost']);
To this:
$ldapconn = ldap_connect($ldap['ldaphost'],$ldap['ldapport']);
advertisements | __label__pos | 0.976102 |
top button
Flag Notify
Connect to us
Site Registration
Site Registration
Workflow migration: retain persistent values?
0 votes
705 views
When I migrate workflows from Development repository to Production repository, there is a chekc box "Retain persistent mapping variable values.." in migration wizard. What happens if I check this box? Does it keep e.g. values in the production environment or does it replace these values from the Development repository?
posted Dec 15, 2014 by Amit Sharma
Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
1 Answer
0 votes
If you check the option Retain persistent values for mapping variables, the existing values from the target folder will be kept.
Otherwise, they will be replaced with values from the source folder.
Quote from the Repository Guide:
Retain persistent values for mapping variables. You can choose to retain existing values or replace them with values from the source folder.
Retain persistent values for workflow variables. You can choose to retain existing values or replace them with values from the source folder.
answer Dec 18, 2014 by Shweta Singh
Similar Questions
+2 votes
A large amount of data is coming from source to target. After a successful insertion in target, we have to change the status to every rows as "committed". But when will we know that all datas have come or not in target without directly querying the source?
For example - suppose 10 records have migrated to target from source. We cannot change the status of all the records as "committed" before successful insertion of all records in target.
So before changing the status of all the records, how will we know that 11th record is coming or not? Is there anything that will give me the information about total records in source?
I need a real-time based answer.
+2 votes
As an SQA, I need to verify that all connections associated with a set of workflows have been updated. How can I view all connections associated with a workflow? Is there a connection, or connections, assigned to individual workflows, or would I need to find the connections for each individual session? If so, how do I view the connection(s) of a session?
+2 votes
How to tune the session, workflow for better performance, what are the things we consider for better performance?
... | __label__pos | 0.981692 |
1. Join Now
AVForums.com uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
how secure are pm messaging systems??
Discussion in 'General Chat' started by samjet, Jul 14, 2005.
1. samjet
samjet
Banned
Joined:
Jan 1, 2005
Messages:
1,419
Products Owned:
0
Products Wanted:
0
Trophy Points:
38
Location:
notts
Ratings:
+5
firstly - i want to make it very clear that my comments are NOT directed at any moderators etc on this forum :D
my concerns are about other forums :( is it possible for moderators etc to read your pm's without you knowing - and if the answer is yes are there any encryption systems that you can use :confused:
2. Dr Diversity
Dr Diversity
Guest
Products Owned:
0
Products Wanted:
0
Ratings:
+0
You could write it in code
3. -Jay-
-Jay-
Banned
Joined:
Jul 26, 2002
Messages:
4,932
Products Owned:
0
Products Wanted:
0
Trophy Points:
86
Location:
Kop End
Ratings:
+135
What you trying to hide? lol
4. Dr Diversity
Dr Diversity
Guest
Products Owned:
0
Products Wanted:
0
Ratings:
+0
You could type it very quickly and hope nobody else sees it
5. samjet
samjet
Banned
Joined:
Jan 1, 2005
Messages:
1,419
Products Owned:
0
Products Wanted:
0
Trophy Points:
38
Location:
notts
Ratings:
+5
nothing dodgy but doubts have been expressed in some quarters that big brother may be watching :D
and i reiterate NOT this forum :eek:
6. Gary D
Gary D
Member
Joined:
Jan 9, 2002
Messages:
7,784
Products Owned:
0
Products Wanted:
0
Trophy Points:
136
Ratings:
+838
my understanding is that nothing is safe anymore. in the last week i've heard various people on the news talking about what thewy can see. very very scary!
Gary
7. samjet
samjet
Banned
Joined:
Jan 1, 2005
Messages:
1,419
Products Owned:
0
Products Wanted:
0
Trophy Points:
38
Location:
notts
Ratings:
+5
but what happens if it sits in the recipients in box for hours??
i know moderators private forums are not always secure because they have been hacked :D
8. Dr Diversity
Dr Diversity
Guest
Products Owned:
0
Products Wanted:
0
Ratings:
+0
It was a joke :)
9. Nick_UK
Nick_UK
Banned
Joined:
Nov 13, 2004
Messages:
9,748
Products Owned:
0
Products Wanted:
0
Trophy Points:
103
Ratings:
+270
I don't think that moderators on most forum software can read PM's, but since nearly all forums now use databases to store stuff, it's not beyond the bounds of the administrator of any website to access the database directly and read the contents. To do this, you would need to have access to the server directly, which is normally outside the realms of moderators.
If you have anything you don't want someone else to read, send it by Royal Mail. Even e-mail can be intercepted :eek:
10. samjet
samjet
Banned
Joined:
Jan 1, 2005
Messages:
1,419
Products Owned:
0
Products Wanted:
0
Trophy Points:
38
Location:
notts
Ratings:
+5
does not worry me if gchq reads :D doubt if any keywords are echelon 'listed' but you never know - a list of some words was published in another place and they were quite an eye opener!!
11. Nobber22
Nobber22
Member
Joined:
Jun 6, 2002
Messages:
2,980
Products Owned:
0
Products Wanted:
0
Trophy Points:
86
Location:
Berkshire
Ratings:
+110
Gay code?
12. Dr Diversity
Dr Diversity
Guest
Products Owned:
0
Products Wanted:
0
Ratings:
+0
??
13. samjet
samjet
Banned
Joined:
Jan 1, 2005
Messages:
1,419
Products Owned:
0
Products Wanted:
0
Trophy Points:
38
Location:
notts
Ratings:
+5
one forum i use - obviously checks/reads pms in some form as if you swear in a pm the offending word is deleted - or is this just a programme???
don't see why you can't swear when talking to mates etc :(
14. Nick_UK
Nick_UK
Banned
Joined:
Nov 13, 2004
Messages:
9,748
Products Owned:
0
Products Wanted:
0
Trophy Points:
103
Ratings:
+270
Many forums do this automatically for both public and private messages.
15. Ed Selley
Ed Selley
AVF Reviewer
Joined:
Jun 26, 2003
Messages:
11,169
Products Owned:
0
Products Wanted:
2
Trophy Points:
166
Ratings:
+3,610
Cool- If GCHQ do read everything and respond to keywords, I'm going to have to work out how to "anthrax" and "fatwah" into my signiture to give my friends that work there something to do :laugh:.
16. Nick_UK
Nick_UK
Banned
Joined:
Nov 13, 2004
Messages:
9,748
Products Owned:
0
Products Wanted:
0
Trophy Points:
103
Ratings:
+270
They have robots listening into cell phone calls too.
17. stevegreen
stevegreen
Well-known Member
Joined:
May 14, 2001
Messages:
8,737
Products Owned:
0
Products Wanted:
0
Trophy Points:
136
Location:
in my Hymer
Ratings:
+921
Being a moderator myself, I have the ability to read PM's, edit them, intercept them, make them up, send them from different usernames............everything!
I also have use of a filter sysytem much like the one the government uses, so, if anyone mentions my name in a PM then I am alerted and can deal with any insobordination swiftly and invisibly.
It's great being a moderator!
All of the above is clearly a joke so don't start being silly about it :D
18. mjn
mjn
Distinguished Member
Joined:
May 24, 2001
Messages:
21,691
Products Owned:
0
Products Wanted:
0
Trophy Points:
166
Location:
Herts, England
Ratings:
+9,297
E-Mail IS intercepted.
If you send 2 e-mails to yourself, at the same time, with one having a subject field of "bomb", guess which one will arrive first?
19. Gary D
Gary D
Member
Joined:
Jan 9, 2002
Messages:
7,784
Products Owned:
0
Products Wanted:
0
Trophy Points:
136
Ratings:
+838
steve, you almost made me want to be a mod then :D
Gary
20. Dr Diversity
Dr Diversity
Guest
Products Owned:
0
Products Wanted:
0
Ratings:
+0
If they check both for key words then why does the 'bomb' one take longer?
21. mjn
mjn
Distinguished Member
Joined:
May 24, 2001
Messages:
21,691
Products Owned:
0
Products Wanted:
0
Trophy Points:
166
Location:
Herts, England
Ratings:
+9,297
Because its intercepted...and checked for contents.
22. HMHB
HMHB
Distinguished Member
Joined:
Nov 11, 2001
Messages:
26,529
Products Owned:
0
Products Wanted:
0
Trophy Points:
166
Location:
Nottinghamshire
Ratings:
+5,192
So it's you who's been sending me the love letters :D
23. stevegreen
stevegreen
Well-known Member
Joined:
May 14, 2001
Messages:
8,737
Products Owned:
0
Products Wanted:
0
Trophy Points:
136
Location:
in my Hymer
Ratings:
+921
No, It was IanJ :p :laugh:
24. hornydragon
hornydragon
Well-known Member
Joined:
Dec 19, 2001
Messages:
28,343
Products Owned:
0
Products Wanted:
0
Trophy Points:
136
Location:
Somewhere near the M4 most of the time......
Ratings:
+1,218
Stuart does have access to them PM's on this site until they are delted that is (well i guess he may be able to retreive those) and any filter system is not perfect neither is any encryption but the simplest ones to use a multiple part transmissions ie parlty sent email, PM, SMS, phone call etc there are huge amounts of data flaoting around so much infact that to generate anything meaning full the filter has to be very very tight otherwise eveything gets through think of google for example probably the most used search engine on the web with the biggest database of sites but even that is no where near accuarte enough for general searches. Googlewhacking is a sport *** the mos secure system in the land is PSTN the good old landline analogue, voice only no packets or flags and needs a court order to be tapped/checked...............could you imagine the confusion at the CIA if they had Xbox live comms searched the number of people being shot bombed crashed killed etc they wouldn't be able to cope.............
25. Nick_UK
Nick_UK
Banned
Joined:
Nov 13, 2004
Messages:
9,748
Products Owned:
0
Products Wanted:
0
Trophy Points:
103
Ratings:
+270
Does it give you access to the spelling checker too ? :D :rotfl:
26. Ian J
Ian J
Banned
Joined:
Aug 6, 2001
Messages:
25,568
Products Owned:
0
Products Wanted:
0
Trophy Points:
166
Ratings:
+4,905
No wonder Sean didn't get them. It was you diverting them again :mad:
27. MartinImber
MartinImber
Active Member
Joined:
Apr 5, 2001
Messages:
3,854
Products Owned:
0
Products Wanted:
0
Trophy Points:
71
Location:
Worcester
Ratings:
+21
GCHQ is a funny place, the workers there are allowed to tell you some details of their work ie job title. If they say they are not allowed to tell you it is because they have a low level job. IE they can say they are a secretary or a librarian or an engineer, but not what they actually do.
A friend who used to work there told me this, he left because he didn't do that much - his work got less and less as time went on, and the bosses he was getting were basically waiting for retirement, some days he just sat around working for himself. He could possibly have cross trained but prefered to leave.
Below is public knowlege
The things which are known about GCHQ are quite interesting - like they invented an encryption algorythm which was then patented by some yanks about 10 years later - because GCHQ wanted it kept secret (fair enough).
One thing I will mention, most of the staff are like you and me - they want a safe Britain and are patriotic. Apart from a few "I am so important" losers and a few "unions are more important than national security" they do the job for the good training, pay and interesting job.
However if I could ask them one question - it would be "have you cracked Videoguard?"
Anyway GCHQ doesn't worry me, but the US does, they are not as good as the British at their job and they are a lot more gungho
28. Dr Diversity
Dr Diversity
Guest
Products Owned:
0
Products Wanted:
0
Ratings:
+0
Nice way to upset any secretaries, librarians and engineers reading this post :rotfl:
29. Nobber22
Nobber22
Member
Joined:
Jun 6, 2002
Messages:
2,980
Products Owned:
0
Products Wanted:
0
Trophy Points:
86
Location:
Berkshire
Ratings:
+110
GCHQ is like any government agency: there are about 9 people actually doing any important work. The rest are drinking coffee, attending pointless meetings and waiting for 4pm.
Those 9 are highly trained and work bloody hard, but like any govt agency GCHQ is also under-staffed. If you think they have time to check everything going through every ISP all the time......... :rolleyes:
30. Nick_UK
Nick_UK
Banned
Joined:
Nov 13, 2004
Messages:
9,748
Products Owned:
0
Products Wanted:
0
Trophy Points:
103
Ratings:
+270
Well, you've done it now ! You know they're reading this, don't you ? :D
Seriously though, one thing I didn't realise when I signed the Official Secrets Act is that you can't un-sign it :eek:
Share This Page
Loading... | __label__pos | 0.981066 |
How to use ASP.NET Membership class to validate users in C# | Tutorial | Example | HowtoASP.NET
How to use ASP.NET Membership class to validate users in C#
The Membership class provides a method for validating a membership user. If a user has entered his user name and password in a login mask, you can use the ValidateUser() method for programmatically validating the information entered by the user, as follows:
protected void LoginAction_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(UsernameText.Text, PasswordText.Text))
{
FormsAuthentication.RedirectFromLoginPage(UsernameText.Text, false);
}
else
{
LegendStatus.Text = “Invalid user name or password!”;
}
} | __label__pos | 0.999484 |
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
Sign up
Here's how it works:
1. Anybody can ask a question
2. Anybody can answer
3. The best answers are voted up and rise to the top
I have headings that appear before items in an enumerated list. The problem is that I think it looks ugly when a heading appears at the end of a page with the content of that heading on the next page. I'd like it so that at least one line of text from the item contents appears after a heading. I've tried \nopagebreak[4] (doesn't appear to do anything?) and begin{samepage} wrapping the heading and entire paragraph (left big empty spaces on pages). I'm hoping there's a nice way to solve it!
Here's sample code to reproduce the issue:
\documentclass[letterpaper]{article}
\usepackage{enumitem}
\usepackage{lipsum}
\begin{document}
\begin{enumerate}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\end{enumerate}
\end{document}
And an image of the problematic output (see bottom of page). In this case, I'd either like the heading to be pushed to the next page or at least the first line of text from the paragraph to be pulled onto the first page.
enter image description here
share|improve this question
up vote 3 down vote accepted
The needspace package allows reserving vertical space before doing the next thing. If the space does not exist, it issues a page break. Here, I redefined \item to perform a \needspace before it. You can change the value I used (\baselineskip), but it works for your MWE.
\documentclass[letterpaper]{article}
\usepackage{enumitem}
\usepackage{lipsum}
\usepackage{needspace}
\let\svitem\item
\def\item{\needspace{\baselineskip}\svitem}
\begin{document}
\begin{enumerate}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\item[]{\Huge{Heading}}
\item{\lipsum[1]}
\end{enumerate}
\end{document}
It is possible that you might still get burned, since the lipsum paragraphs will also issue a \needspace and could break a page on that account. A better way would be as follows, where a separate \Hitem is defined which alone issues the \needspace:
\documentclass[letterpaper]{article}
\usepackage{enumitem}
\usepackage{lipsum}
\usepackage{needspace}
\def\Hitem#1{\needspace{\baselineskip}\item[]{\Huge{#1}}}
\begin{document}
\begin{enumerate}
\Hitem{Heading}
\item{\lipsum[1]}
\Hitem{Heading}
\item{\lipsum[1]}
\Hitem{Heading}
\item{\lipsum[1]}
\Hitem{Heading}
\item{\lipsum[1]}
\end{enumerate}
\end{document}
share|improve this answer
This seems to have done the trick for me, thanks very much! – aardvarkk Feb 21 '14 at 20:07
A solution using the stackengine package: it's by construction that the "Heading" part cannot be separated from the first line of the content since it belongs to the first line. It also has the advantage to greatly simplify the code – unless you have specific reasons to type the heading with its own \item command:
\documentclass[a4paper]{article}
\usepackage{enumitem}
\usepackage{stackengine}
\usepackage{lipsum}
\usepackage[bottom=45mm]{geometry}
\clubpenalty = 3500
\setstackgap{S}{\baselineskip}
\begin{document}
\lipsum[1]
\begin{enumerate}[label =\arabic*.\stackon{}{\rlap{\hspace{\labelsep}\Huge Heading}}]%
\item \lipsum[1]
\item \lipsum[1]
\item \lipsum[1]
\item \lipsum[1]
\item \lipsum[1]
\end{enumerate}
\end{document}%
enter image description here
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.999807 |
Raid: Mtn and Airtel Zambia free (unlimited) internet on Slow dns - TECH FOE
Raid: Mtn and Airtel Zambia free (unlimited) internet on Slow dns
Its Zambia again. This time it does't have anything to do with XP Psiphon or the Zambian free unlimited internet trick we released. This is for MTN and Airtel Zambian users.
I decided to drop this since the main mtn and Airtel free internet trick on XP Psiphon ain't ready yet. Now lets look at what we have. This free internet trick works on Tunnel guru for Pc and Slow dns for Android and can be made to browse unlimited either by getting a premium account or downloading the tweaked version. Note that this dns trick works well on Airtel but sometimes misbehaves on the mtn network.
Requirements:
1. You must have an mtn or Airtel simcard
2. An Android device or PC
3. Slow dns or Tunnel guru
4. The procedures below
Slow dns Procedures for Android:
1. First click here to download slow dns for android
2. Open the app and install it this way
3. Leave the space for Username and password blank
4. Now input any of this as your Dns: 10.150.2.66, 10.150.2.73
5. Next configure: 275 on the left and 20 on the right
6. Now tick the last two options and click on it to connect. When it does, open your browser and enjoy free internet.(for unlimited internet access refer to the write-up in the beginning of this post)
Tunnel guru Procedures for PC:
1. Click here to download Tunnel guru for PC
2. Install the app and then configure your dns with any of this: 10.150.2.6610.150.2.73
3. When you are done, click on connect and enjoy free internet
Please endeavor to drop your comments regarding this post.
Note: This post is for EDUCATIONAL purpose only! You are responsible for any of your actions, Techfoe only drop such to alert ISPs of their vulnerabilites.
11 comments:
1. Replies
1. You are welcome. Keep visiting for more tricks!
Delete
2. Papi can you please send me the cell c s.a config....i just downloaded xp psiphon v5 so am ready...i dont mind to wait for it to connect i have got patients....
[email protected]
Thnx alot
Delete
2. Wow! another great work from Pappi. Thanks a bunch
ReplyDelete
3. thanks, enjoying the Vodafone tricks.. but how can I use the Vodafone settings on a PC?
ReplyDelete
4. Bro hav been trying were can I put the dns is it were its written tunnel DNS query?
ReplyDelete
5. Anonytun has stopped working on mtn Zambia
Please help
ReplyDelete
Powered by Blogger. | __label__pos | 0.955352 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I have a student who is working on a Tower Defense game in AS3 and has an issue that has stumped me. He is using hitTestObject to change the direction that a movieClip is moving. The movieClip has its own timeline with frames for the different directions that the object is facing and a linked .as file with the code for the behavior of the object.
When he calls gotoAndStop to change the internal frame of the movieClip, the removed event is triggered, but the object stays on the screen and no longer moves.
All of my searches find answers about removing objects, but I have not seen anything about preventing an object from removing itself.
The following code is a loop triggered by an ENTER_FRAME event in the .as class file for the movieClip object:
private function eFrame(event:Event):void
{
if (_root.isPaused == false)
{
//MOVING THE ENEMY
this.x += speed * xDir;
this.y -= speed * yDir;
if (health <= 0)
{
_root.currency += 4;
this.parent.removeChild(this);
}
if (this.x > 770)
{
this.parent.removeChild(this);
_root.health -= 10;
_root.gotHit = true;
}
//checking if touching any invisible markers
for (var i:int=0; i<_root.upHolder.numChildren; i++)
{
//the process is very similar to the main guy's testing with other elements
var upMarker:DisplayObject = _root.upHolder.getChildAt(i);
if (hitTestObject(upMarker))
{
yDir = 1;
xDir = 0;
this.gotoAndStop(3);
}
}
for (i=0; i<_root.downHolder.numChildren; i++)
{
//the process is very similar to the main guy's testing with other elements
var downMarker:DisplayObject = _root.downHolder.getChildAt(i);
if (hitTestObject(downMarker))
{
yDir = -1;
xDir = 0;
this.gotoAndStop(7);
}
}
for (i=0; i<_root.rightHolder.numChildren; i++)
{
//the process is very similar to the main guy's testing with other elements
var rightMarker:DisplayObject = _root.rightHolder.getChildAt(i);
if (hitTestObject(rightMarker))
{
yDir = 0;
xDir = 1;
this.gotoAndStop(6);
}
}
for (i=0; i<_root.leftHolder.numChildren; i++)
{
//the process is very similar to the main guy's testing with other elements
var leftMarker:DisplayObject = _root.leftHolder.getChildAt(i);
if (hitTestObject(leftMarker))
{
yDir = 0;
xDir = -1;
this.gotoAndStop(2);
}
}
}
}
private function remove(event:Event):void
{
trace("remove");
removeEventListener(Event.ENTER_FRAME, eFrame);
_root.enemiesLeft -= 1;
}
}
When the gotoAndStop line executes, the frame of the movieClip changes and then the code jumps directly to a function that is triggered by the REMOVED event.
Does anyone have an idea why the REMOVED event might be triggered by this code?
Thank you for your help.
share|improve this question
2 Answers 2
up vote 1 down vote accepted
The REMOVED Event is triggered by anything that is removed from the stage inside the MovieClip or Sprite that is containing it, if I'm not mistaken. And especially with MovieClips that have animation, things get removed and added everytime, for instance if some part of the animation ends on the timeline, or at keyframes.
Event.REMOVED_FROM_STAGE is dispatched only when the container itself is removed from stage. Maybe that's causing your confusion? I can't see from your code example exactly what event type you're listening for.
share|improve this answer
Thank you. Changing my Event Listener from REMOVED to REMOVED_FROM_STAGE solved the problem. – wrTechTeacher Feb 22 '13 at 16:54
Where are you adding the remove-listener?
Without more information, I would guess that you are listening to a clip inside an animation, and that it's not there on all frames (or, maybe even more likely - that the instance is being swapped out for another, identical one, by flash pro. This can happen depending on in what order you added keyframes, the alignment of the moon and fluctuations in the ionosphere. It's easiest fixed by simply removing all key-frames and then re-creating them. And then never using flash pro for anything ever again.)
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.994704 |
Hi guys, I've been playing around with my processor (athlon xp 2600 barton) and managed to do the l5 mod to turn it into a mobile athlon mp, which is pretty cool. Unfortunately, my processor is superlocked, so I can't change the multi from the bios, my only option for changing it is through windows using PowerNow! tech with programs like CPUMSR or CRYSTALCPUID.
Problem is, I have an NFORCE2 chipset, and whenever I try to change the multi, I get a freeze. I've been searching around and it seems that I need to do the following
"nVidia: nForce 2 (reg. E7, bit 4 = FID_Change Detect; reg. 6F, bit 4 = Halt Disconnect) - But there is high change this won't work, good solution hasn't been found to this date."
I have the program WPCREDIT to edit my bits and registers, but i'm a little unsure exactly what I'm supposed to do here. Can someone please explain to me what they want me to do with Register E7, bit 4? What does it mean by FID_CHANGE DETECT?
Thanks for any help! | __label__pos | 0.751143 |
edit_post_link( string $text = null, string $before = , string $after = , int|WP_Post $post, string $css_class = ‘post-edit-link’ )
Displays the edit post link for post.
Parameters
$textstringoptional
Anchor text. If null, default is ‘Edit This’.
Default:null
$beforestringoptional
Display before edit link.
Default:''
$afterstringoptional
Display after edit link.
Default:''
$postint|WP_Postoptional
Post ID or post object. Default is the global $post.
$css_classstringoptional
Add custom class to link. Default 'post-edit-link'.
Default:'post-edit-link'
More Information
Displays a link to edit the current post, if a user is logged in and allowed to edit the post. Can be used within The Loop or outside of it. If outside the loop, you’ll need to pass the post ID. Can be used with pages, posts, attachments, and revisions.
Use get_edit_post_link to retrieve the url.
Source
function edit_post_link( $text = null, $before = '', $after = '', $post = 0, $css_class = 'post-edit-link' ) {
$post = get_post( $post );
if ( ! $post ) {
return;
}
$url = get_edit_post_link( $post->ID );
if ( ! $url ) {
return;
}
if ( null === $text ) {
$text = __( 'Edit This' );
}
$link = '<a class="' . esc_attr( $css_class ) . '" href="' . esc_url( $url ) . '">' . $text . '</a>';
/**
* Filters the post edit link anchor tag.
*
* @since 2.3.0
*
* @param string $link Anchor tag for the edit link.
* @param int $post_id Post ID.
* @param string $text Anchor text.
*/
echo $before . apply_filters( 'edit_post_link', $link, $post->ID, $text ) . $after;
}
Hooks
apply_filters( ‘edit_post_link’, string $link, int $post_id, string $text )
Filters the post edit link anchor tag.
Changelog
VersionDescription
4.4.0The $css_class argument was added.
1.0.0Introduced.
User Contributed Notes
You must log in before being able to contribute a note or feedback. | __label__pos | 0.960039 |
• Announcements
• khawk
Download the Game Design and Indie Game Marketing Freebook 07/19/17
GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Wraithe
Members
• Content count
6
• Joined
• Last visited
Community Reputation
121 Neutral
About Wraithe
• Rank
Newbie
1. Thank you both again for the replies! I do not ever think to use the debugger =(, will do my best to remember. There was some error about std::mem_copy or something similar, so it must have been vector copying errors.
2. Sorry to post so many times in a row, but I found a solution. The program only crashes when I use a vector of my button class. If I make it a vector of pointers, it works. Anyone know why this is? (Not a big deal, pointers are fine, I simply don't understand why that would cause a crash).
3. I have also tried freeing the rendered text surface immediately after creation, and the program crashes, yet the pointer is not NULL. Again, my other programs work just fine with TTF, what on earth could the issue be? Edit: Finally got a crash report (Only does it once out of every 10 runs ) Problem signature: Problem Event Name: APPCRASH Application Name: Space Invaders.exe Application Version: 0.0.0.0 Application Timestamp: 51e53cc5 Fault Module Name: ntdll.dll Fault Module Version: 6.1.7600.16385 Fault Module Timestamp: 4a5bdb3b Exception Code: c0000005 Exception Offset: 000335f2 OS Version: 6.1.7600.2.0.0.256.1 Locale ID: 1033 Additional Information 1: e3cc Additional Information 2: e3cc0ee538989a7b66ab90686b3c00a6 Additional Information 3: d22a Additional Information 4: d22a3993b2d48ddd96705e026b50390c Fault Module Name: ntdll.dll <-- What is this?
4. Thanks for the replies! As far as I can tell (with error checking) the pointers are valid. I set up error checking and not a single error occurs. The program just crashes when a text rendered surface hits the blit function. Edit: Yes, I have even tried filling in all the render text solid parameters with solid values, generated IN that function, and the crash still occured at the blit function.
5. I have been using SDL (pre 2.0) with SDL_ttf, SDL_image and irrKland (for audio). I have started touching on OpenGL, but that is mostly for fun at the moment. Lazy Foo is THE site to learn SDL and OpenGL. He doesn't really go into game mechanics much, but the APIs he covers very well. Then I would hit up StaysCrisps tutorials over at DreaminCode, as he has a wonderful intro game engine design tutorial series (he now also recommends a book called SDL Game Development, looks great and teaches TinyXML, I cant WAIT to get this =D ). I have been looking for someone to program with (I am terrible at art) and my custom game engine (using SDL and irrKlang) is nearing completion, let me know if you and your friend would like an extra partner =) !
6. Hello all, Looking for a little help. I have used SDL with TTF quite a bit and I am fairly comfortable with it at this point. This error has me dumbfounded however, and I have no more ideas of how to proceed. I have tested the Font loading and TTF_RenderText_Solid. The surface returned from the rendertext function is not a null pointer, but it must be the issue, as my program crashes anytime I try to blit a text surface. I have used the same blitting function for standard images, and it works just fine. I have also checked all my compiler linking (I am using code::blocks), it is fine. I have loaded up old programs, recompiled them, and they work just fine. I have no idea where to go from here. My button class is where I am trying to utilize text, so that is what I will be showing. Edit: In case anyone ends up asking, I did call TTF_Init(); #include "text.h" std::map <std::string, SDL_Color> Text::mColors; std::map <std::string, TTF_Font *> Text::mFonts; SDL_Surface * Text::applyText( std::string strText, std::string strFont, std::string strColor, int * w, int * h ) { SDL_Surface * surface = NULL; surface = TTF_RenderText_Solid( mFonts[ strFont ], strText.c_str(), mColors[ strColor ] ); TTF_SizeText( mFonts[ strFont ], strText.c_str(), w, h ); return surface; } #ifndef TEXT_H #define TEXT_H #include <map> #include <string> #include "SDL/sdl_ttf.h" class Text { public: static SDL_Surface * applyText( std::string strText, std::string strFont, std::string strColor, int * w, int * h ); static std::map <std::string, SDL_Color> mColors; static std::map <std::string, TTF_Font *> mFonts; }; #endif // TEXT_H // inside of Display.cpp void Display::loadFonts() { initInput( "Resources/ResourceListFonts.txt" ); while( !isFile.eof() ) { readLine(); if( !strData.empty() ) { std::string strFont = strData; readLine(); std::string strFontPath = strPath + strData; int fontSize = readValue(); TTF_Font * newFont = NULL; newFont = TTF_OpenFont( strFontPath.c_str(), fontSize ); mFonts.insert( std::pair <std::string, TTF_Font *> ( strFont, newFont ) ); } } freeInput(); } // in button.cpp Button::Button( int iX, int iY, std::string strSurf, std::string strFunc, std::string strText ) { x = iX; y = iY; w = Display::getImageWidth( strSurf ); h = Display::getImageHeight( strSurf ); iTextW = 0; iTextH = 0; strFunction = strFunc; strSurface = strSurf; surfaceText = NULL; if( !strText.empty() ) { strSurfaceText = strText; surfaceText = Display::applyText( strSurfaceText, "monospaceTypewriter12", "black", &iTextW, &iTextH ); } sClipX = 0; sClipY = 0; } void Button::render() { Display::applySurface( x, y, strSurface, sClipX, sClipY ); if( surfaceText != NULL ) { Display::applySurface( ( x + ( iTextW / 2 ) ), ( y + ( iTextH / 2 ) ), surfaceText ); } } | __label__pos | 0.75898 |
Index APIedit
Adds a JSON document to the specified data stream or index and makes it searchable. If the target is an index and the document already exists, the request updates the document and increments its version.
You cannot use the index API to send update requests for existing documents to a data stream. See Update documents in a data stream by query and Update or delete documents in a backing index.
Requestedit
PUT /<target>/_doc/<_id>
POST /<target>/_doc/
PUT /<target>/_create/<_id>
POST /<target>/_create/<_id>
You cannot add new documents to a data stream using the PUT /<target>/_doc/<_id> request format. To specify a document ID, use the PUT /<target>/_create/<_id> format instead. See Add documents to a data stream.
Prerequisitesedit
• If the Elasticsearch security features are enabled, you must have the following index privileges for the target data stream, index, or index alias:
• To add or overwrite a document using the PUT /<target>/_doc/<_id> request format, you must have the create, index, or write index privilege.
• To add a document using the POST /<target>/_doc/, PUT /<target>/_create/<_id>, or POST /<target>/_create/<_id> request formats, you must have the create_doc, create, index, or write index privilege.
• To automatically create a data stream or index with an index API request, you must have the auto_configure, create_index, or manage index privilege.
• Automatic data stream creation requires a matching index template with data stream enabled. See Set up a data stream.
Path parametersedit
<target>
(Required, string) Name of the data stream or index to target.
If the target doesn’t exist and matches the name or wildcard (*) pattern of an index template with a data_stream definition, this request creates the data stream. See Set up a data stream.
If the target doesn’t exist and doesn’t match a data stream template, this request creates the index.
You can check for existing targets using the resolve index API.
<_id>
(Optional, string) Unique identifier for the document.
This parameter is required for the following request formats:
• PUT /<target>/_doc/<_id>
• PUT /<target>/_create/<_id>
• POST /<target>/_create/<_id>
To automatically generate a document ID, use the POST /<target>/_doc/ request format and omit this parameter.
Query parametersedit
if_seq_no
(Optional, integer) Only perform the operation if the document has this sequence number. See Optimistic concurrency control.
if_primary_term
(Optional, integer) Only perform the operation if the document has this primary term. See Optimistic concurrency control.
op_type
(Optional, enum) Set to create to only index the document if it does not already exist (put if absent). If a document with the specified _id already exists, the indexing operation will fail. Same as using the <index>/_create endpoint. Valid values: index, create. If document id is specified, it defaults to index. Otherwise, it defaults to create.
If the request targets a data stream, an op_type of create is required. See Add documents to a data stream.
pipeline
(Optional, string) ID of the pipeline to use to preprocess incoming documents. If the index has a default ingest pipeline specified, then setting the value to _none disables the default ingest pipeline for this request. If a final pipeline is configured it will always run, regardless of the value of this parameter.
refresh
(Optional, enum) If true, Elasticsearch refreshes the affected shards to make this operation visible to search, if wait_for then wait for a refresh to make this operation visible to search, if false do nothing with refreshes. Valid values: true, false, wait_for. Default: false.
routing
(Optional, string) Custom value used to route operations to a specific shard.
timeout
(Optional, time units) Period the request waits for the following operations:
Defaults to 1m (one minute). This guarantees Elasticsearch waits for at least the timeout before failing. The actual wait time could be longer, particularly when multiple waits occur.
version
(Optional, integer) Explicit version number for concurrency control. The specified version must match the current version of the document for the request to succeed.
version_type
(Optional, enum) Specific version type: external, external_gte.
wait_for_active_shards
(Optional, string) The number of shard copies that must be active before proceeding with the operation. Set to all or any positive integer up to the total number of shards in the index (number_of_replicas+1). Default: 1, the primary shard.
See Active shards.
require_alias
(Optional, Boolean) If true, the destination must be an index alias. Defaults to false.
Request bodyedit
<field>
(Required, string) Request body contains the JSON source for the document data.
Response bodyedit
_shards
Provides information about the replication process of the index operation.
_shards.total
Indicates how many shard copies (primary and replica shards) the index operation should be executed on.
_shards.successful
Indicates the number of shard copies the index operation succeeded on. When the index operation is successful, successful is at least 1.
Replica shards might not all be started when an indexing operation returns successfully—by default, only the primary is required. Set wait_for_active_shards to change this default behavior. See Active shards.
_shards.failed
An array that contains replication-related errors in the case an index operation failed on a replica shard. 0 indicates there were no failures.
_index
The name of the index the document was added to.
_type
The document type. Elasticsearch indices now support a single document type, _doc.
_id
The unique identifier for the added document.
_version
The document version. Incremented each time the document is updated.
_seq_no
The sequence number assigned to the document for the indexing operation. Sequence numbers are used to ensure an older version of a document doesn’t overwrite a newer version. See Optimistic concurrency control.
_primary_term
The primary term assigned to the document for the indexing operation. See Optimistic concurrency control.
result
The result of the indexing operation, created or updated.
Descriptionedit
You can index a new JSON document with the _doc or _create resource. Using _create guarantees that the document is only indexed if it does not already exist. To update an existing document, you must use the _doc resource.
Automatically create data streams and indicesedit
If request’s target doesn’t exist and matches an index template with a data_stream definition, the index operation automatically creates the data stream. See Set up a data stream.
If the target doesn’t exist and doesn’t match a data stream template, the operation automatically creates the index and applies any matching index templates.
Elasticsearch includes several built-in index templates. To avoid naming collisions with these templates, see Avoid index pattern collisions.
If no mapping exists, the index operation creates a dynamic mapping. By default, new fields and objects are automatically added to the mapping if needed. For more information about field mapping, see mapping and the update mapping API.
Automatic index creation is controlled by the action.auto_create_index setting. This setting defaults to true, which allows any index to be created automatically. You can modify this setting to explicitly allow or block automatic creation of indices that match specified patterns, or set it to false to disable automatic index creation entirely. Specify a comma-separated list of patterns you want to allow, or prefix each pattern with + or - to indicate whether it should be allowed or blocked. When a list is specified, the default behaviour is to disallow.
The action.auto_create_index setting only affects the automatic creation of indices. It does not affect the creation of data streams.
PUT _cluster/settings
{
"persistent": {
"action.auto_create_index": "my-index-000001,index10,-index1*,+ind*"
}
}
PUT _cluster/settings
{
"persistent": {
"action.auto_create_index": "false"
}
}
PUT _cluster/settings
{
"persistent": {
"action.auto_create_index": "true"
}
}
Allow auto-creation of indices called my-index-000001 or index10, block the creation of indices that match the pattern index1*, and allow creation of any other indices that match the ind* pattern. Patterns are matched in the order specified.
Disable automatic index creation entirely.
Allow automatic creation of any index. This is the default.
Put if absentedit
You can force a create operation by using the _create resource or setting the op_type parameter to create. In this case, the index operation fails if a document with the specified ID already exists in the index.
Create document IDs automaticallyedit
When using the POST /<target>/_doc/ request format, the op_type is automatically set to create and the index operation generates a unique ID for the document.
POST my-index-000001/_doc/
{
"@timestamp": "2099-11-15T13:12:00",
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
}
The API returns the following result:
{
"_shards": {
"total": 2,
"failed": 0,
"successful": 2
},
"_index": "my-index-000001",
"_id": "W0tpsmIBdwcYyG50zbta",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"result": "created"
}
Optimistic concurrency controledit
Index operations can be made conditional and only be performed if the last modification to the document was assigned the sequence number and primary term specified by the if_seq_no and if_primary_term parameters. If a mismatch is detected, the operation will result in a VersionConflictException and a status code of 409. See Optimistic concurrency control for more details.
Routingedit
By default, shard placement — or routing — is controlled by using a hash of the document’s id value. For more explicit control, the value fed into the hash function used by the router can be directly specified on a per-operation basis using the routing parameter. For example:
POST my-index-000001/_doc?routing=kimchy
{
"@timestamp": "2099-11-15T13:12:00",
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
}
In this example, the document is routed to a shard based on the routing parameter provided: "kimchy".
When setting up explicit mapping, you can also use the _routing field to direct the index operation to extract the routing value from the document itself. This does come at the (very minimal) cost of an additional document parsing pass. If the _routing mapping is defined and set to be required, the index operation will fail if no routing value is provided or extracted.
Data streams do not support custom routing unless they were created with the allow_custom_routing setting enabled in the template.
Distributededit
The index operation is directed to the primary shard based on its route (see the Routing section above) and performed on the actual node containing this shard. After the primary shard completes the operation, if needed, the update is distributed to applicable replicas.
Active shardsedit
To improve the resiliency of writes to the system, indexing operations can be configured to wait for a certain number of active shard copies before proceeding with the operation. If the requisite number of active shard copies are not available, then the write operation must wait and retry, until either the requisite shard copies have started or a timeout occurs. By default, write operations only wait for the primary shards to be active before proceeding (i.e. wait_for_active_shards=1). This default can be overridden in the index settings dynamically by setting index.write.wait_for_active_shards. To alter this behavior per operation, the wait_for_active_shards request parameter can be used.
Valid values are all or any positive integer up to the total number of configured copies per shard in the index (which is number_of_replicas+1). Specifying a negative value or a number greater than the number of shard copies will throw an error.
For example, suppose we have a cluster of three nodes, A, B, and C and we create an index index with the number of replicas set to 3 (resulting in 4 shard copies, one more copy than there are nodes). If we attempt an indexing operation, by default the operation will only ensure the primary copy of each shard is available before proceeding. This means that even if B and C went down, and A hosted the primary shard copies, the indexing operation would still proceed with only one copy of the data. If wait_for_active_shards is set on the request to 3 (and all 3 nodes are up), then the indexing operation will require 3 active shard copies before proceeding, a requirement which should be met because there are 3 active nodes in the cluster, each one holding a copy of the shard. However, if we set wait_for_active_shards to all (or to 4, which is the same), the indexing operation will not proceed as we do not have all 4 copies of each shard active in the index. The operation will timeout unless a new node is brought up in the cluster to host the fourth copy of the shard.
It is important to note that this setting greatly reduces the chances of the write operation not writing to the requisite number of shard copies, but it does not completely eliminate the possibility, because this check occurs before the write operation commences. Once the write operation is underway, it is still possible for replication to fail on any number of shard copies but still succeed on the primary. The _shards section of the write operation’s response reveals the number of shard copies on which replication succeeded/failed.
{
"_shards": {
"total": 2,
"failed": 0,
"successful": 2
}
}
Refreshedit
Control when the changes made by this request are visible to search. See refresh.
Noop updatesedit
When updating a document using the index API a new version of the document is always created even if the document hasn’t changed. If this isn’t acceptable use the _update API with detect_noop set to true. This option isn’t available on the index API because the index API doesn’t fetch the old source and isn’t able to compare it against the new source.
There isn’t a hard and fast rule about when noop updates aren’t acceptable. It’s a combination of lots of factors like how frequently your data source sends updates that are actually noops and how many queries per second Elasticsearch runs on the shard receiving the updates.
Timeoutedit
The primary shard assigned to perform the index operation might not be available when the index operation is executed. Some reasons for this might be that the primary shard is currently recovering from a gateway or undergoing relocation. By default, the index operation will wait on the primary shard to become available for up to 1 minute before failing and responding with an error. The timeout parameter can be used to explicitly specify how long it waits. Here is an example of setting it to 5 minutes:
PUT my-index-000001/_doc/1?timeout=5m
{
"@timestamp": "2099-11-15T13:12:00",
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
}
Versioningedit
Each indexed document is given a version number. By default, internal versioning is used that starts at 1 and increments with each update, deletes included. Optionally, the version number can be set to an external value (for example, if maintained in a database). To enable this functionality, version_type should be set to external. The value provided must be a numeric, long value greater than or equal to 0, and less than around 9.2e+18.
When using the external version type, the system checks to see if the version number passed to the index request is greater than the version of the currently stored document. If true, the document will be indexed and the new version number used. If the value provided is less than or equal to the stored document’s version number, a version conflict will occur and the index operation will fail. For example:
PUT my-index-000001/_doc/1?version=2&version_type=external
{
"user": {
"id": "elkbee"
}
}
Versioning is completely real time, and is not affected by the near real time aspects of search operations. If no version is provided, then the operation is executed without any version checks.
In the previous example, the operation will succeed since the supplied version of 2 is higher than the current document version of 1. If the document was already updated and its version was set to 2 or higher, the indexing command will fail and result in a conflict (409 http status code).
A nice side effect is that there is no need to maintain strict ordering of async indexing operations executed as a result of changes to a source database, as long as version numbers from the source database are used. Even the simple case of updating the Elasticsearch index using data from a database is simplified if external versioning is used, as only the latest version will be used if the index operations arrive out of order for whatever reason.
Version typesedit
In addition to the external version type, Elasticsearch also supports other types for specific use cases:
external or external_gt
Only index the document if the given version is strictly higher than the version of the stored document or if there is no existing document. The given version will be used as the new version and will be stored with the new document. The supplied version must be a non-negative long number.
external_gte
Only index the document if the given version is equal or higher than the version of the stored document. If there is no existing document the operation will succeed as well. The given version will be used as the new version and will be stored with the new document. The supplied version must be a non-negative long number.
The external_gte version type is meant for special use cases and should be used with care. If used incorrectly, it can result in loss of data. There is another option, force, which is deprecated because it can cause primary and replica shards to diverge.
Examplesedit
Insert a JSON document into the my-index-000001 index with an _id of 1:
PUT my-index-000001/_doc/1
{
"@timestamp": "2099-11-15T13:12:00",
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
}
The API returns the following result:
{
"_shards": {
"total": 2,
"failed": 0,
"successful": 2
},
"_index": "my-index-000001",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"result": "created"
}
Use the _create resource to index a document into the my-index-000001 index if no document with that ID exists:
PUT my-index-000001/_create/1
{
"@timestamp": "2099-11-15T13:12:00",
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
}
Set the op_type parameter to create to index a document into the my-index-000001 index if no document with that ID exists:
PUT my-index-000001/_doc/1?op_type=create
{
"@timestamp": "2099-11-15T13:12:00",
"message": "GET /search HTTP/1.1 200 1070000",
"user": {
"id": "kimchy"
}
} | __label__pos | 0.684593 |
Who’s responsible for securing software?
A Venify report showed that the number of companies where DevOps is responsible for the security and the number who assign this to their Infosec department is almost evenly split. But should there really be this ambiguity regarding the responsibility of software security?
When you look at the situation on paper, you might say that Information Security should find holes in the apps because they are normally penetration testing the company’s running software anyway. But equally compelling is to claim that because DevOps knows how the software works and is likely one of the few units with access to the codebase, they should be at work making sure hackers cannot exploit the software.
From this perspective, it seems that both of these views are right. DevOps should patch their programs - and make sure there are none of those pesky off-by-one errors - while Infosec has the knowledge necessary to send a running program off the rails.
So for you and me, it seems obvious to us what the roles of those two departments should be.
But what about who takes responsibility when a cyberattack happens?
I’m not really the one posing this question. Executives often assign this taking-in-charge to either DevOps or Infosec, provided that both exist. We don’t see most businesses sharing collective blame after a hack, right? So why don’t they just make one department responsible for protecting the company from breaches?
That would be a poor approach to the problem because merely pentesting the program for vulnerabilities ignores the fact that hackers can try a completely new attack vector to enter the organization. And while DevOps can guard against basic flaws such as null dereference, they don’t have the time that Infosec has to run different tests to catch new vulnerabilities continuously.
I don’t believe that incident response should be a blame game and that all departments which play a part in the application interacting process should take responsibility to protect the software they use at their company and write, not only for their own company but for clients that also use the software in their products as well.
Cover Image by maxxyustas from Envato Elements
Subscribe our latest updates
Don't miss out. Be the first one to know when a new guide or tool comes out.
Subscription Form
Support Us ❤
Creating learning material requires a lot of time and resources. So if you appreciate what we do, send us a tip to bc1qm02xguzxxhk7299vytrt8sa8s6fkns2udf8gjj. Thanks! | __label__pos | 0.807251 |
Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I have a simple query:
SELECT u_name AS user_name FROM users WHERE user_name = "john";
I get Unknown Column 'user_name' in where clause. Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name'?
share|improve this question
I dont understand why this many upvotes for this question ..! – Chella Jan 3 at 4:54
add comment
16 Answers
SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name as not yet occurred.
share|improve this answer
11
Rather than "backwards" I think it makes more sense to say "inside out" – Joe Philllips May 26 '10 at 3:35
add comment
select u_name as user_name from users where u_name = "john";
Think of it like this, your where clause evaluates first, to determine which rows (or joined rows) need to be returned. Once the where clause is executed, the select clause runs for it.
To put it a better way, imagine this:
select distinct(u_name) as user_name from users where u_name = "john";
You can't reference the first half without the second. Where always gets evaluated first, then the select clause.
share|improve this answer
add comment
See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html
"A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses."
share|improve this answer
add comment
What about: SELECT u_name AS user_name FROM users HAVING user_name = "john";
share|improve this answer
add comment
No you need to select it with correct name. If you gave the table you select from an alias you can use that though.
share|improve this answer
add comment
corrected:
SELECT u_name AS user_name FROM users WHERE u_name = 'john';
share|improve this answer
add comment
Either:
SELECT u_name AS user_name
FROM users
WHERE u_name = "john";
or:
SELECT user_name
from
(
SELECT u_name AS user_name
FROM users
)
WHERE u_name = "john";
The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.
share|improve this answer
add comment
If you're trying to perform a query like the following (find all the nodes with at least one attachment) where you've used a SELECT statement to create a new field which doesn't actually exist in the database, and try to use the alias for that result you'll run into the same problem:
SELECT nodes.*, (SELECT (COUNT(*) FROM attachments
WHERE attachments.nodeid = nodes.id) AS attachmentcount
FROM nodes
WHERE attachmentcount > 0;
You'll get an error "Unknown column 'attachmentcount' in WHERE clause".
Solution is actually fairly simple - just replace the alias with the statement which produces the alias, eg:
SELECT nodes.*, (SELECT (COUNT(*) FROM attachments
WHERE attachments.nodeid = nodes.id) AS attachmentcount
FROM nodes
WHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;
You'll still get the alias returned, but now SQL shouldn't bork at the unknown alias.
share|improve this answer
1
I was facing this exact problem, and came across your answer - thank you! Just to note, it is (understandably) a little slow on large databases, but I'm dealing with a stupid inherited database setup anyway. – Liam Newmarch Sep 8 '11 at 10:55
I believe you have an extra ( in your query before the (COUNT(*) which isn't closed anywhere. – tftd Nov 27 '12 at 16:09
add comment
No you cannot. user_name is doesn't exist until return time.
share|improve this answer
add comment
Unknown column in WHERE clause caused by lines 1 and 2 and resolved by line 3:
1. $sql = "SELECT * FROM users WHERE username =".$userName;
2. $sql = "SELECT * FROM users WHERE username =".$userName."";
3. $sql = "SELECT * FROM users WHERE username ='".$userName."'";
share|improve this answer
add comment
SELECT user_name
FROM
(
SELECT name AS user_name
FROM users
) AS test
WHERE user_name = "john"
share|improve this answer
add comment
May be it helps.
You can
SET @somevar := '';
SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john";
It works.
BUT MAKE SURE WHAT YOU DO!
• Indexes are NOT USED here
• There will be scanned FULL TABLE - you hasn't specified the LIMIT 1 part
• So, - THIS QUERY WILL BE SLLLOOOOOOW on huge tables.
But, may be it helps in some cases
share|improve this answer
add comment
I had the same problem, I found this useful.
mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'");
remember to put $user in ' ' single quotes.
share|improve this answer
add comment
Your defined alias are not welcomed by the WHERE clause you have to use the HAVING clause for this
SELECT u_name AS user_name FROM users HAVING user_name = "john";
OR you can directly use the original column name with the WHERE
SELECT u_name AS user_name FROM users WHERE u_name = "john";
Same as you have the result in user defined alias as a result of subquery or any calculation it will be accessed by the HAVING clause not by the WHERE
SELECT u_name AS user_name ,
(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name
FROM users WHERE u_name = "john" HAVING user_last_name ='smith'
share|improve this answer
add comment
While you can alias your tables within your query (i.e., "SELECT u.username FROM users u;"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned.
share|improve this answer
add comment
Not as far as I know in MS-SQL 2000/5. I've fallen foul of this in the past.
share|improve this answer
add comment
protected by ThiefMaster Mar 22 '12 at 8:26
This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site. | __label__pos | 0.873991 |
When you release Alt, the symbol will appear. As you can see, it is possible to do this via the Symbol dialog, but it is anything but easy and straightforward. Type currency symbols. If you would like to use the phone symbol in a document such as Word, e-mail, editor etc., then it is recommended to use the correct Unicode. Click on man symbols below to copy and paste male symbol, boy emoji ♂. First select the symbol then you can drag&drop or just copy&paste it anywhere you like. Method D – How to use ALT codes by editing the registry setting and using the hexadecimal code point of a character. To find it, go to the ‘Insert’ tab in Word. It's sort of a full name full of Greek pathos is The Spear and Shield of Mars. 2. "My car" will suggest the "[car]" emoji. How to Type the Shrug Emoji ¯\_(ツ)_/¯ in 2 Seconds Flat Pro tip: If you don't want the emoji to take the place of the word, but rather appear beside it, put a space between the word before you tap your desired emoji. Girl sign ♀, also known as woman sign, symbol of women, or female sign, or Venus symbol from FSymbols. Linux keyboard shortcuts for text symbols. Find how to type female sign directly from your keyboard. For example, hold Alt key and then type 9997 keys on the numeric pad will produce the writing hand symbol . You can copy & paste, or drag & drop any symbol to textbox below, and see how it looks like. In Javascript you should write like a = "this \u2669 symbol" if you want to include a special symbol in a string. This is the screen lock icon. Alt + X Shortcuts for Hands Symbols for Microsoft Word. Beside gender it's also used as an astrological and astronomical symbol (yes, these are different things) for planet Mars. Tap it to release and the button will go back to black. CharMap allows you to view and use all characters and symbols available in all fonts (some examples of fonts are "Arial", "Times New Roman", "Webdings") installed on your computer. You can input mail symbol using it. Hit the Return Key to Jump to a New Line – Without Sending the Message In iOS, just hit the Return key to jump onto the next line within an iMessage. Play – Some type of audio is playing (song, podcast, audiobook). Love symbol is a copy and paste text symbol that can be used in any desktop, web, or mobile applications. Please, read a guide if you're running a laptop. Codes can be used within HTML, Java..etc programming languages. You press Alt and, while holding it, type a code on Num Pad while it's turned on. ⚧️ Transgender Symbol Emoji Meaning. You can put it in Facebook, Youtube or Instagram. Biology and medicine. This article will show you how to easily type line breaks and insert new lines into Messages on iPhone and iPad. Female sign html entity. Even if the keys are unlabeled, the keypad will still work when Num Lock is on. Type mathematics symbols. Change the size of your keyboard. Well, you can shake your iPhone to … VPN – iPhone is connected to a VPN network. Some Apple devices support Animoji and Memoji.Two Private Use Area characters are not cross-platform compatible but do work on Apple devices: Apple logo Beats 1 logo 117 new emojis are now available in iOS 14.2 and macOS 11 Big Sur. See the iPhone special characters list below. How to type symbols, accents, special characters, and weird punctuation acute accents: lowercase a with acute accent: In my case the, the x in the box that you refer to appeared on my phone screen as an elongated x in a standing rectangle. NumLock must be enabled. There actually are 3 different ways to type symbols on Linux with a keyboard. Shortcut technique that works on Desktops and most Laptops running MS Windows. It can also help you lookup Unicode codes for entering symbols with keyboard. Alt-Codes can be typed on Microsoft Operating Systems: Unicode codes can not be typed. Emoji predictions will show up whenever you type something that has a corresponding emoji. Simple and beautiful way to discover how to add a virtual keyboard for Emoji symbols visible as small pictures. Text Symbols with iPhone Emoji keyboard . While you're using an app, you can switch to a different keyboard, like a … It was first used to denote the effective gender of plants by Carolus Linnaeus in 1751. If you like, or need at times, to type one-handed, there's a simple … For example, press option + 26A3 will produce the gay symbol like ⚣. 12 gender signs, female symbol, male symbol and other gender symbol variations. Portrait orientation lock – iPhone screen is locked in portrait mode Alarm – Alarm is on. Example: Type 262F, then p ress and hold the left ALT key, press the X key, then release both keys. Symbol Test Box. Telephone Symbol Unicode ☎☏ - That's how it works Details Manuel Solvemix Android Smartphones. Step 1: Open your word processor and locate either Alt key on your keyboard. Step 1, Click on the location where you want to insert the symbol. Typically, the Alt keys are located on either side of your spacebar. Then click ‘Symbol’ to open the symbol menu and click ‘More Symbols…’. Using it is even better than typing out ‘K’ in place of ‘Ok’ or ‘Okay’ and it induces far less range on the recipient’s side when it is sent. Hold Alt and type the number below using the numeric pad on your keyboard to insert mathematics symbols. If I go to the Symbols keyboards in the Standard Motorola keyboard input, and long press any symbol key, it will display a blue rectangle, showing the symbol, and whether there are other symbols available from that key. It’s white when engaged. How? This enters the yin yang symbol ☯. The Mobile Phone symbol can be found under the ‘Extended Characters - Plane 1’ Subset in Microsoft Word. Reply Hold Alt and type the number below using the numeric pad on your keyboard. I started noticing it about 1-1/2 years ago when I would visit with my nephew via text. Takes about 5-10 minutes to set things up, but you'll be typing like a boss. Tap the letter, number, or symbol that contains the alternative you want to access. Facebook Twitter. In addition, Unicode consortium also added transgender symbol in 2020 emoji list. Click on girl symbol below to copy it automatically. I added some other text symbols for men into the mix, hope you'll find something new in them. Press and hold the ALT key and type the number 11 for male symbol, After you long-press, drag your finger upward to choose a character from the pop-up palette. The three standard sex symbols are the male symbol ♂ and the female symbol ♀, and the hybrid symbol ×.They were first used to denote the effective sex of plants (i.e. And on the right you can pick a font variation of the same symbol. Male and female symbols are part of emoji symbols that you can type using quick emoji panel in Windows 10 and Mac. If you still have an affinity for typed emoticons like me, especially the timeless ¯\_(ツ)_/¯ emoticon, here’s how you can type it in two seconds flat on a Mac, Windows, iPhone, and Android. Character map allows you to view and use all characters and symbols available in all fonts (some examples of fonts are "Arial", "Times New Roman", "Webdings") installed on your computer. Tap on the appropriate symbol in QuickType bar to type the symbol offered. You can type many frequently used symbols with this method. How to type all symbols characters for Windows, Mac, and in HTML. A symbol commonly used to represent those in the transgender community. An Android cable is called a Micro-USB cable. Apple. Step #1. The keyboard itself is preinstalled on your iOS device, so you don't have to download, or buy anything. In the center are all the characters within a given category. Configure your keyboard layout in Windows so that you can type all additional symbols you want as easy as any other text. When you are typing in Messages, Notes, Mail etc, touch and hold on the letter, number, or symbol, which has these character(s). You can copy & paste, or drag & drop any symbol to textbox below, and see how it looks like. How to Type Special Characters and Symbols on iPhone or iPad. Character Palette allows you to view and use all characters and symbols, including male sign, available in all fonts (some examples of fonts are "Arial", "Times New Roman", "Webdings") installed on your computer. Gender Emoji Symbols in Windows and Mac. The secret is to long-press a key, such as the A key, shown here. Special symbol pop-up palette thing. Open Settings. Be a man. sex of individual in a given crossbreed, since most plants are hermaphroditic) by Carl Linnaeus in 1751. The thumbs-up symbol, not to mention the thumbs-down which Facebook doesn’t support, is pretty universal in meaning. As one type … 3. For example, "I'm happy" will predict "[smiley face]". Copy and paste the gender symbols or use unicode numbers as well. Male sign ♂ is a symbol for masculine gender. These symbols include accented letters and other common characters. In old manuscripts it is usually interpreted as the shield and spear from the war god Ares. The following three symbols ☎☏ have been included in Unicode version 1.1 since May 1993. To learn how to make the icons bigger on iPhone, use the following steps: 1. Tough, right? You will see that a … Type the hexadecimal code in the second column of the table then press alt and x keys. Step #2. Call Forwarding – The iPhone is setup for call forwarding. Male: 2642; To make sure that the character is being displayed as an emoji and not a black and white character, you need to add the special “Variation Selector-16” emoji behind the gender sign. Look to the top right hand side where you’ll see a button with the icon of a lock with a circular arrow around it. Shake to UndoWant to quickly undo a text you typed or pasted? 2. You may be able to type ♀ girl text symbol right from your keyboard - read below for that. TTY – Set to work with TTY machine. Male sign ♂ is a symbol for masculine gender. Type the following shorthand to trigger the QuickType keyboard to offer a symbol replacement: For trademark, type: TM. This table explains the meaning of every love symbol. [1] X Research sourceStep 2, Press Alt.Step 3, Type 0153 on the keypad for the trademark (™) … 3.2. This enters the yin yang symbol ☯. It's sort of a full name full of Greek pathos is The Spear and Shield of Mars. and for the female sign press 12. An iPhone cable is described as an Apple Lightning cable, to correspond with the iPhone’s unique Lightning connector. On an Android, go to the number and symbols keyboard, then hit … Hold down the period in the symbols keyboard and an ellipses will show up. If your keyboard doesn't have a dedicated numeric keypad but has one as a sub-function of other keys, press Fn or NumLock to activate the numeric keypad. Access the Home Screen of your iPhone by pressing on the Home button once. Make Icons Larger on iPhone. Emojis displayed on iPhone, iPad, Mac, Apple Watch and Apple TV use the Apple Color Emoji font installed on iOS, macOS, watchOS and tvOS. Beside gender it's also used as an astrological and astronomical symbol (yes, these are different things) for planet Mars. You can assign male symbol ♂ and any other text characters to your keyboard using this technique. Choose your system and find out how to type male symbol from your keyboard. Why? Press and hold the ALT key and type the number 11 for male symbol, and for the female sign press 12. Lock – iPhone is locked. The Character Code for this is: FE0F. I'm (still) using the average ICS (4.0.4) on a Motorola Atrix 2. Read below. You can type many frequently used symbols with this method. If both connectors are USB Type-A, it would be a USB Type-A cable (or a USB male to male cable or, simply, a USB cable). This symbol for male gender has been in use since the Renaissance also denoting elements in alchemy, specifically the metal iron. Copy and paste the gender symbols or use unicode numbers as well. You need to tap on the gear icon from your Home Screen to open up Settings. To use them in facebook, twitter, textbox or elsewhere just follow the instructions at top. Interestingly, you might also be able to type male text symbol right from your keyboard. Please, read a guide if you're running a laptop . Male symbol sign meaning. Male sign ♂ is a depiction of a circle with an arrow emerging from it, pointing at at angle to the upper right. Female symbol keyboard alt code and more. However, you need to have a separate numeric keypad for entering decimal numbers. Used within the draft emoji sequence for the Transgender Flag emoji, and also given emoji presentation on Samsung devices.. Shows as a plain text character on other platforms. Switch to another keyboard. You press Alt and, while holding it, type a code on Num Pad while it's turned on. Interestingly, when you flip the girl sign 180° you can get planet Earth symbol ♁. Hope this helps – John. Following is a list of HTML and JavaScript entities for male symbol. For registered symbol, type (R) For Copyright symbol, type ©. To type in a TM symbol Macs use, for example: Open your word processor of choice; Call the Mac symbols menu But only third and fourth level chooser keys and unicode hex codes can produce male text symbol. Here, you’ll see all kinds of categories on the left: Emoji, Arrows, Currency Symbols, etc. Characters within a given crossbreed, since most plants are hermaphroditic ) by Carl Linnaeus in 1751 a keyboard &! A font variation of the table then press Alt and X keys iPhone is setup for call –. Usually interpreted as the a key, such as the Shield and Spear from war... Kinds of categories on the gear icon from your keyboard layout in Windows 10 and.! And beautiful way to discover how to type male symbol, type ( R ) for planet.! Typed or pasted you lookup Unicode codes for entering symbols with keyboard help you lookup Unicode codes for decimal. The girl sign 180° you can type using quick emoji panel in so... You want as easy as any other text in JavaScript you should write like how to type male symbol on iphone.! In any desktop, web, or drag & drop any symbol to textbox below, and for the sign! And insert new lines into Messages on iPhone and iPad usually interpreted as a! Version 1.1 since May 1993 `` [ car ] '' kinds of categories on the right you drag. Full name full of Greek pathos is the Spear and Shield of Mars type symbols on with. And iPad Windows 10 and Mac, such as the a key such! Kinds of categories on the Home button once on man symbols below to it... X keys as an astrological and astronomical symbol ( yes, these different... Type many frequently used symbols with keyboard the keys are located on how to type male symbol on iphone side of spacebar. Alchemy, specifically the metal iron button will go back to black to your.... And type the number 11 how to type male symbol on iphone male symbol sign meaning + X Shortcuts for Hands symbols for men into mix... And other gender symbol variations Unicode numbers as well May 1993 ; and other... The same symbol be typing like a boss it 's sort of a full name full of pathos. Screen to open the symbol offered 're running a laptop portrait mode Alarm – Alarm on... A list of HTML and JavaScript entities for male symbol & male ; use! Steps: 1 with keyboard can drag & drop any symbol to textbox,. Individual in a given category your Home Screen to open the symbol offered release,! Can assign male symbol & male ; can drag & drop or just copy & paste anywhere... Even if the keys are unlabeled, the keypad will still work when Lock! Ll see all kinds of categories on the appropriate symbol in 2020 emoji list type something that has corresponding. Then press Alt and, while holding it, type a code on Num pad it. A guide if you like and Mac Shield of Mars many frequently used with. Girl text symbol playing ( song, podcast, audiobook ) when Num Lock is.... The number and symbols keyboard, then hit … ⚧️ transgender symbol in QuickType bar to type hexadecimal! Planet Earth symbol ♁ insert the symbol then you can type all additional you. Reply the Mobile Phone symbol can be found under the ‘ Extended -... Paste text symbol how to type male symbol on iphone from your keyboard - read below for that and. In QuickType bar to type female sign directly from your keyboard using this technique a! ’ s unique Lightning connector will show up whenever you type something that a. ; and any other text characters to your keyboard or Venus symbol from FSymbols assign male symbol male... Do this via the symbol offered and then type 9997 keys on the appropriate symbol in emoji... Will go back to black has a corresponding emoji show up whenever you type something that has corresponding. 12 gender signs, female symbol, boy emoji & male ; it sort... Bigger on iPhone, use the following steps: 1 Messages on iPhone, use the following symbols... Symbol replacement: for trademark, type ( R ) for planet Mars ways type... And for the female sign press 12: 1 quickly undo a text you typed or pasted reply Mobile... Discover how to make the icons bigger on iPhone, use the following three symbols ☎☏ have included! Separate numeric keypad for entering symbols with keyboard either side of your spacebar Systems: Unicode codes for symbols. Can put it in Facebook, Youtube or Instagram denote the effective gender of plants by Carolus Linnaeus 1751. Or Venus symbol from your keyboard type ( R ) for planet Mars anywhere you,... Be able to type male text symbol that contains the alternative you want to include a Special symbol 2020... Universal in meaning and Mac able to type the symbol dialog, but you 'll typing! Woman sign, symbol of women, or need at times, to correspond the. Visit with My nephew via text to quickly undo a text you typed or pasted be! In a string & female ; girl text symbol that can be used within HTML, Java etc... Suggest the `` [ car ] '' but easy and straightforward but 'll... Entering symbols with this method female sign, or need at times, to correspond with the iPhone s... Symbols below to copy it automatically visible as small pictures, when you release Alt, the keypad will work... For trademark, type ( R ) for planet Mars replacement: for,... Running a laptop an iPhone cable is described as an Apple Lightning cable, to the. On either side of your iPhone by pressing on the left:,! In Windows 10 and Mac works on Desktops and most Laptops running MS Windows if you,! Anything but easy and straightforward visit with My nephew via text entities for male has!, to type male text symbol that can be used within HTML, Java.. etc programming languages press hold! And astronomical symbol ( yes, these are different things ) for planet Mars that! New lines into Messages on iPhone and iPad Unicode codes can not typed! Earth symbol ♁ in addition, Unicode consortium also added transgender symbol in 2020 emoji.... Currency symbols most plants are hermaphroditic ) by Carl Linnaeus in 1751 to type symbol! A separate numeric keypad for entering decimal numbers download, or drag & drop any to. It, go to the number and symbols on iPhone or iPad i Some... In 1751 iPhone and iPad codes can be used within HTML, Java.. etc programming languages male &... A list of HTML and JavaScript entities for male symbol symbol is a list of HTML and entities! Then hit … ⚧️ transgender symbol emoji meaning found under the ‘ insert ’ tab Word! Symbol dialog, but it is usually interpreted as the Shield and Spear from the war god Ares happy will., web how to type male symbol on iphone or drag & drop any symbol to textbox below, and how. The center are all the characters within a given crossbreed, since most plants are hermaphroditic by. Preinstalled on your keyboard - read below for that it to release and button. Anywhere you like, or drag & drop or just copy & paste, or female sign symbol. Shortcuts for Hands symbols for Microsoft Word 11 for male symbol and other gender symbol.. And Mac 's sort of a full name full of Greek pathos is the Spear and of. [ car ] '' characters within a given crossbreed, since most plants are hermaphroditic ) Carl... Beautiful way to discover how to type female sign, or Venus symbol your... In any desktop, web, or female sign, symbol of women, or female sign, or that. Type line breaks and insert new lines into Messages on iPhone or.... Home Screen of your iPhone by pressing on the numeric pad on your.. Hope you 'll find something new in them: emoji, Arrows, currency symbols,.... Use Unicode numbers as well the Renaissance also denoting elements in alchemy, specifically the metal.... Song, podcast, audiobook ) anything but easy and straightforward ) on a Motorola 2... Woman sign, or Venus symbol from FSymbols symbol that contains the alternative you want as as... And any other text symbols for Microsoft Word audio is playing ( song, podcast, ). Will produce the writing hand symbol into Messages on iPhone, use the following three symbols have. On Microsoft Operating Systems: Unicode codes can produce male text symbol that can be used within HTML Java. In Microsoft Word symbols visible as small pictures preinstalled on your keyboard of emoji that. Used as an astrological and astronomical symbol ( yes, these are different things ) planet. Predictions will show up numbers as well the location where you want to insert the symbol textbox below and. ) using the hexadecimal code point of a full name full of Greek pathos is the and! Then click ‘ More Symbols… ’ the following shorthand to trigger the keyboard... Symbol that can be used within HTML, Java.. etc programming languages My nephew via.... At times, to type male text symbol right from your keyboard layout in Windows 10 Mac. Have to download, or Mobile applications can pick a font variation of table! A string make the icons bigger on iPhone, use the following shorthand trigger! Commonly used to denote the effective gender of plants by Carolus Linnaeus 1751. And straightforward symbols visible as small pictures with this method symbols ☎☏ have been included in Unicode 1.1. | __label__pos | 0.5182 |
Connor Bishop Connor Bishop - 5 months ago 33
MySQL Question
SQL - Update multiple records in one query with Composite Key
I have looked at this question which addresses updating multiple records in one query.
The general solution is
UPDATE table_name
SET field_to_update = CASE table_key
WHEN key_value1 THEN field_value1
WHEN key_value2 THEN feild_value2
ELSE feild_to_update
END
WHERE table_key IN(key_value1 , key_value2);
My question is who can this be adapted to cater for a composite key. Say if I have columns
(id_1, id_2, column_to_update)
where id_1 and id_2 form a composite primary key.
My problem is made simpler by the fact that one of the id columns will be constant for a particular query.
For example, I need something along the lines of
UPDATE table_name
SET field_to_update = CASE (key1, key2)
WHEN (1,1) THEN field_value1
WHEN (2,1) THEN feild_value2
ELSE feild_to_update
END
WHERE (key1, key2) IN ( (1, 1) , (2, 1) );
Can anyone help please?
Answer
The use of tuple in case is not allowed case allow only one operand if you use a tuple like in your case you have the error "Operand should contain 1 column(s)" because are 2 operands
but you can override with some manipulation eg a concat (and implicit conversion )
UPDATE table_name
SET field_to_update = CASE concat(key1, key2)
WHEN concat(1,1) THEN field_value1
WHEN concat(2,1) THEN feild_value2
ELSE feild_to_update
END
WHERE concat(key1, key2) IN ( concat(1, 1) , concat(2, 1) ); | __label__pos | 0.975306 |
Integer sum() Method in Java
The java.lang.Integer.sum() is a built-in method in java which returns the sum of its arguments. The method adds two integers together as per the + operator.
Syntax :
public static int sum(int a, int b)
Parameter: The method accepts two parameters which are to be added with each other:
a : the first integer value.
b : the second integer value.
Return Value: The method returns the sum of its arguments.
Exception: The method throws an ArithmeticException when the result overflows an int.
Examples
Input: a = 170, b = 455
Output: 625
Input: a = 45, b = 45
Output: 90
Below programs illustrate the Java.lang.Integer.sum() method:
Program 1: For a positive number.
filter_none
edit
close
play_arrow
link
brightness_4
code
// Java program to illustrate the
// Java.lang.Integer.sum() method
import java.lang.*;
public class Geeks {
public static void main(String[] args)
{
int a = 62;
int b = 18;
// It will return the sum of two arguments.
System.out.println("The sum is =" + Integer.sum(a, b));
}
}
chevron_right
Output:
The sum is =80
Program 2: Below program illustrates the exception.
filter_none
edit
close
play_arrow
link
brightness_4
code
// Java program to illustrate the
// Java.lang.Integer.sum() method
import java.lang.*;
public class Geeks {
public static void main(String[] args)
{
// When very large integer is taken
int a = 92374612162
int b = 181;
// It will return the sum of two arguments.
System.out.println("The sum is =" + Integer.sum(a, b));
}
}
chevron_right
Output:
prog.java:8: error: integer number too large: 92374612162
int a = 92374612162;
^
1 error
My Personal Notes arrow_drop_up
lets make it a lil simple
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below. | __label__pos | 0.98659 |
How to pass Microsoft 70-568 Real Exam in 24 Hours [study guide 106-120]
High value of 70-568 brain dumps materials and bootcamp for Microsoft certification for customers, Real Success Guaranteed with Updated 70-568 pdf dumps vce Materials. 100% PASS Today!
2016 Mar 70-568 Study Guide Questions:
Q106. You create a Microsoft ASP.NET application by using the Microsoft .NET Framework version 3.5.You plan to submit text that contains HTML code to a page in the application.You need to ensure that the HTML code can be submitted successfully without affecting other applications that run on the Web server.What should you do?
A. Add the following attribute to the @Page directive. EnableEventValidation="true"
B. Add the following attribute to the @Page directive. ValidateRequest="true"
C. Set the following value in the Web.config file.
<system.web>
<pages validateRequest="false"/>
</system.web>
D. Set the following value in the Machine.config file.
<system.web>
<pages validateRequest="false"/>
</system.web>
Answer: C
Q107. You are creating a Windows Forms application for inventory management by using the .NET Framework 3.5.The application provides a form that allows users to maintain stock balances. The form has the following features:
A dataset named dsStockBalance to store the stock information A business component named scInventory The scInventory component provides a method named Save. You need to ensure that only the modified stock balances of dsStockBalance are passed to the scInventory.Save method. Which code segment should you use?
A. if(dsStockBalance.HasChanges()) dsStockBalance.AcceptChanges();
dsUpdates = dsStockBalance.GetChanges();
scInventory.Save(dsStockBalance);
B. if(dsStockBalance.HasChanges())
dsUpdates = dsStockBalance.GetChanges();
dsStockBalance.AcceptChanges();
scInventory.Save(dsStockBalance);
C. if(dsStockBalance.HasChanges())
{
dsStockBalance.AcceptChanges();
dsUpdates = dsStockBalance.GetChanges();
scInventory.Save(dsUpdates);
}
D. if(dsStockBalance.HasChanges())
{
dsUpdates = dsStockBalance.GetChanges();
dsStockBalance.AcceptChanges();
scInventory.Save(dsUpdates);
}
Answer: D
Q108. You create an application by using the Microsoft .NET Framework 3.5 and Microsoft ADO.NET. The application connects to a Microsoft SQL Server 2005 database.You write the following code segment. (Line numbers are included for reference only.)
01 Using connection As New SqlConnection(connectionString)
02 Dim cmd As New SqlCommand(queryString, connection)
03 connection.Open()
04
05 While sdrdr.Read()
06 ' use the data in the reader
07 End While
08 End Using
You need to ensure that the memory is used efficiently when retrieving BLOBs from the database.Which code segment should you insert at line 04?
A. Dim sdrdr As SqlDataReader = _ cmd.ExecuteReader()
B. Dim sdrdr As SqlDataReader = _ cmd.ExecuteReader(CommandBehavior.[Default])
C. Dim sdrdr As SqlDataReader = _
cmd.ExecuteReader(CommandBehavior.SchemaOnly)
D. Dim sdrdr As SqlDataReader = _
cmd.ExecuteReader(CommandBehavior.SequentialAccess)
Answer: D
Q109. You create an application by using the Microsoft .NET Framework 3.5 and Microsoft ADO.NET.You write the following code segment. (Line numbers are included for reference only.)
01 private void Update (SqlCommand cmdA, SqlCommand cmdB)
02 {
03 using (TransactionScope scope = new TransactionScope())
04 {
05
06 }
07 }
You need to execute the SqlCommand objects named cmdA and cmdB within a single distributed transaction.Which code segment should you insert at line 05?
A. try {
cmdA.Connection.Open();
cmdB.Connection.Open();
cmdA.ExecuteNonQuery();
cmdB.ExecuteNonQuery();
scope.Complete();
} catch (Exception exp) {}
B. SqlTransaction trans = null;
try { cmdA.Connection.Open();
using (trans = cmdA.Connection.BeginTransaction()) {
cmdB.Connection = trans.Connection;
cmdB.Connection.Open();
cmdA.ExecuteNonQuery();
cmdB.ExecuteNonQuery();
trans.Commit(); }
} catch (Exception exp) {
trans.Rollback(); }
C. SqlTransaction trans = null;
try { cmdA.Connection.Open();
cmdB.Connection.Open();
trans = cmdA.Connection.BeginTransaction();
cmdA.Transaction = trans; cmdB.Transaction = trans;
cmdA.ExecuteNonQuery(); cmdB.ExecuteNonQuery();
trans.Commit(); }
catch (Exception exp) {
trans.Rollback();}
D. SqlTransaction trans = null;
try { cmdA.Connection.Open();
using (trans = cmdA.Connection.BeginTransaction()) {
cmdB.Connection.Open(); cmdA.Transaction = trans;
cmdB.Transaction = trans; cmdA.ExecuteNonQuery();
cmdB.ExecuteNonQuery(); trans.Commit(); }
}catch (Exception exp) {
trans.Rollback();
}
Answer: A
Q110. You create a Microsoft ASP.NETWeb application by using the Microsoft .NET Framework version 3.5.The application uses ASP.NET AJAX, and you plan to deploy it in a Web farm environment.You need to configure SessionState for the application. Which code fragment should you use?
A. <sessionState mode="InProc"
cookieless="UseCookies"
/>
B. <sessionState mode="InProc"
cookieless="UseDeviceProfile"
/>
C. <sessionState mode="SQLServer"
cookieless="false"
sqlConnectionString="Integrated Security=SSPI;data source=MySqlServer;"
/>
D. <sessionState mode="SQLServer"
cookieless="UseUri"
sqlConnectionString="Integrated Security=SSPI;data source=MySqlServer;"
/>
Answer: C
70-568 latest exam
Renewal 70-568 free draindumps:
Q111. You create a Microsoft ASP.NET application by using the Microsoft .NET Framework version 3.5.You plan to deploy the application to a test server.You need to ensure that during the initial request to the application, the code-behind files for theWeb pages are compiled. You also need to optimize the performance of the application. Which code fragment should you add to the Web.config file?
A. <compilation debug="true">
B. <compilation debug="false">
C. <compilation debug="true" batch="true">
D. <compilation debug="false" batch="false">
Answer: B
Q112. You create an application by using the Microsoft .NET Framework 3.5 and Microsoft ADO.NET. The application connects to a Microsoft SQL Server 2005 database that contains the tblOrderDetails table. You plan to create an exception handler for the application.The tblOrderDetails table has been created by using the following DDL statement. CREATE
TABLE tblOrderDetails(
[OrderID] int NOT NULL FOREIGN KEY REFERENCES
tblCustomerOrders(OrderID),
[ProductID] int NOT NULL,
[Qty] int NOT NULL,
[UnitPrice] float CONSTRAINT ckPositivePrice CHECK (UnitPrice >=0),
[Discount] float CONSTRAINT ckPositiveDiscount CHECK (Discount >=0))
You need to ensure that the users are notified when an update to the tblOrderDetails table causes a violation of any constraint. What should you do?
A. Catch the System.Exception exception.
Extract the message value.
Display the message value to the user.
B. Catch the System.Data.SqlClient.SqlException exception.
Extract the message value.
Display the message value to the user.
C. Catch the System.Exception exception.
Loop through all the error objects.
Capture the relevant data from each object.
display the data to the user.
D. Catch the System.Data.SqlClient.SqlException exception.
Loop through all the error objects.
Capture the relevant data from each object.
Display the data to the user.
Answer: D
Q113. You create an application by using the Microsoft .NET Framework 3.5 and Microsoft ADO.NET. The application contains a SqlDataAdapter object named daOrder. The SelectCommand property of the daOrder object is set. You write the following code segment. (Line numbers are included for reference only.)
01 private void ModifyDataAdapter() {
02
03 }
You need to ensure that the daOrder object can also handle updates. Which code segment
should you insert at line 02?
A. SqlCommandBuilder cb = new SqlCommandBuilder(daOrder);
cb.RefreshSchema();
B. SqlCommandBuilder cb = new SqlCommandBuilder(daOrder);
cb.SetAllValues = true;
C. SqlCommandBuilder cb = new SqlCommandBuilder(daOrder);
daOrder.DeleteCommand = cb.GetDeleteCommand();
daOrder.InsertCommand = cb.GetInsertCommand();
daOrder.UpdateCommand = cb.GetUpdateCommand();
D. SqlCommandBuilder cb = new SqlCommandBuilder(daOrder);
cb.RefreshSchema(); cb.GetDeleteCommand();
cb.GetInsertCommand(); cb.GetUpdateCommand();
Answer: C
Q114. You are creating a Windows application by using the .NET Framework 3.5.You create an instance of the BackgroundWorker component named backgroundWorker1 to asynchronously process time-consuming reports in the application.You write the following code segment in the application. (Line numbers are included for reference only.)
02 Private Sub backgroundWorker1_RunWorkerCompleted( _ ByVal sender As Object, _
ByVal e As RunWorkerCompletedEventArgs) _ Handles
backgroundWorker1.RunWorkerCompleted
02
03 End Sub
You need to write a code segment that reports to the application when the background process detects any of the following actions:
An exception is thrown.
The process is cancelled.
The process is successfully completed.
Which code segment should you insert at line 02?
A. If e.Cancelled = Nothing Then MessageBox.Show("Report Cancelled")
Else MessageBox.Show("Report Completed") End If
B. If e.Result = "Cancelled" Or e.Result = "Error" Then
MessageBox.Show("Report Cancelled") Else
MessageBox.Show("Report Completed") End If
C. If backgroundWorker1.CancellationPending = True Then
MessageBox.Show("Report Cancelled") Else
MessageBox.Show("Report Completed") End If
D. If e.Error IsNot Nothing Then MessageBox.Show(e.Error.Message)
ElseIf (e.Cancelled) Then MessageBox.Show("Report Cancelled") Else
MessageBox.Show("Report Completed") End If
Answer: D
Q115. You create an application by using the Microsoft .NET Framework 3.5 and Microsoft
ADO.NET. The application connects to a Microsoft SQL Server 2005 database. You write
the following code segment. (Line numbers are included for reference only.)
01 Using connection As New SqlConnection(connectionString)
02 Dim cmd As New SqlCommand(queryString, connection)
03 connection.Open()
04
05 While sdrdr.Read()
06 ' use the data in the reader
07 End While
08 End Using
You need to ensure that the memory is used efficiently when retrieving BLOBs from the
database.Which code segment should you insert at line 04?
A. Dim sdrdr As SqlDataReader = _ cmd.ExecuteReader()
B. Dim sdrdr As SqlDataReader = _ cmd.ExecuteReader(CommandBehavior.[Default])
C. Dim sdrdr As SqlDataReader = _
cmd.ExecuteReader(CommandBehavior.SchemaOnly)
D. Dim sdrdr As SqlDataReader = _
cmd.ExecuteReader(CommandBehavior.SequentialAccess)
Answer: D
70-568 test questions
Approved 70-568 braindumps:
Q116. You create an application by using the Microsoft .NET Framework 3.5 and Microsoft
ADO.NET.The application has a DataTable object named OrderDetailTable. The object has
the following columns:
·ID
·OrderID
·ProductID
·Quantity
·LineTotal
The OrderDetailTable object is populated with data provided by a business partner. Some of
the records contain a null value in the LineTotal field and 0 in the Quantity field.You write
the following code segment. (Line numbers are included for reference only.)
01 DataColumn col = new DataColumn("UnitPrice", typeof(decimal));
02
03 OrderDetailTable.Columns.Add(col);
You need to add a DataColumn named UnitPrice to the OrderDetailTable object.Which line of code should you insert at line 02?
A. col.Expression = "LineTotal/Quantity";
B. col.Expression = "LineTotal/ISNULL(Quantity, 1)";
C. col.Expression = "LineTotal.Value/ISNULL(Quantity.Value,1)";
D. col.Expression = "iif(Quantity > 0, LineTotal/Quantity, 0)";
Answer: D
Q117. You create a Microsoft ASP.NET application by using the Microsoft .NET Framework version 3.5.You plan to monitor the execution of the application at daily intervals.You need to modify the application configuration to enable WebEvent monitoring. What should you do?
A. Enable the Debugging in the Web site option in the ASP.NET configuration settings.
Modify the Request Execution timeout to 10 seconds.
B. Register the aspnet_perf.dll performance counter library by using the following command.
regsvr32 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_perf.dll
C. Add the following code fragment to the <healthMonitoring> section of the Web.config
file of the application.
<profiles>
<add name="Default" minInstances="1" maxLimit="Infinite" ?
minInterval="00:00:10"
custom="" />
</profiles>
D. Add the following code fragment to the <system.web> section of the Web.config file of
the application.
<healthMonitoring enabled="true" heartbeatInterval="10">
<rules>
<add name="Heartbeats Default" eventName="Heartbeat" provider="EventLogProvider"
profile="Critical"/>
</rules>
</healthMonitoring>
Answer: D
Q118. You create a Microsoft ASP.NET application by using the Microsoft .NET Framework version 3.5.The application contains the following code segment.
Public Class CapabilityEvaluator
Public Shared Function ChkScreenSize( _ByVal cap As
System.Web.Mobile.MobileCapabilities, _ ByVal arg As String) As Boolean
Dim screenSize As Integer = cap.ScreenCharactersWidth * _ cap.ScreenCharactersHeight
Return screenSize < Integer.Parse(arg) End Function
End Class
You add the following device filter element to the Web.config file.
<filter name="FltrScreenSize" type="MyWebApp.CapabilityEvaluator,MyWebApp"
method="ChkScreenSize" />
You need to write a code segment to verify whether the size of the device display is less than 80 characters.Which code segment should you use?
A. Dim currentMobile As MobileCapabilities
currentMobile = TryCast(Request.Browser, MobileCapabilities) If
currentMobile.HasCapability("FltrScreenSize", "80") Then End If
B. Dim currentMobile As MobileCapabilities
currentMobile = TryCast(Request.Browser, MobileCapabilities) If
currentMobile.HasCapability( _
"FltrScreenSize", "").ToString() = "80" Then
End If
C. Dim currentMobile As MobileCapabilities
currentMobile = TryCast(Request.Browser, MobileCapabilities) If
currentMobile.HasCapability( _
"CapabilityEvaluator.ChkScreenSize", "80") Then
End If
D. Dim currentMobile As MobileCapabilities
currentMobile = TryCast(Request.Browser, MobileCapabilities) If
currentMobile.HasCapability( _
"CapabilityEvaluator.ChkScreenSize", "").ToString() = "80" Then
End If
Answer: A
Q119. You create a Microsoft ASP.NET application by using the Microsoft .NET Framework version 3.5. The application consumes a Microsoft Windows Communication Foundation (WCF) service.The WCF service exposes the following method.
<WebInvoke()> _
Function UpdateCustomerDetails(ByVal custID As String) As String
The application hosts the WCF service by using the following code segment. Dim host As
New WebServiceHost(GetType(CService), _New Uri("http://win/"))
Dim ep As ServiceEndpoint = host.AddServiceEndpoint( _ GetType(ICService), New
WebHttpBinding(), "")
You need to invoke the UpdateCustomerDetails method. Which code segment should you use?
A. dim wcf As New WebChannelFactory(Of ICService)( _ New Uri("http: //win"))
Dim channel As ICService = wcf.CreateChannel()
Dim s As String = channel.UpdateCustomerDetails("CustID12")
B. dim wcf As New WebChannelFactory(Of ICService)( _ New Uri("http:
//win/UpdateCustomerDetails"))
Dim channel As ICService = wcf.CreateChannel()
Dim s As String = channel.UpdateCustomerDetails("CustID12")
C. Dim cf As New ChannelFactory(Of ICService)( _ New WebHttpBinding(), "http:
//win/UpdateCustomerDetails")
Dim channel As ICService = cf.CreateChannel()
Dim s As String = channel.UpdateCustomerDetails("CustID12")
D. Dim cf As New ChannelFactory(Of ICService)( _ New BasicHttpBinding(), "http: //win
") cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
Dim channel As ICService = cf.CreateChannel()
Dim s As String = channel.UpdateCustomerDetails("CustID12")
Answer: A
Q120. You create a Microsoft ASP.NET application by using the Microsoft .NET Framework version 3.5.You create a Web page that has a GridView control named GridView1. The GridView1 control displays the data from a database named Region and a table named Location.You write the following code segment to populate the GridView1 control. (Line numbers are included for reference only.)
01 Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As EventArgs)
02 Dim connstr As String
03 ...
04 SqlDependency.Start(connstr)
05 Using connection As New SqlConnection(connstr)
06 Dim sqlcmd As New SqlCommand()
07 Dim expires As DateTime = DateTime.Now.AddMinutes(30)
08 Dim dependency As SqlCacheDependency = _
09 New SqlCacheDependency("Region", "Location")
10 Response.Cache.SetExpires(expires)
11 Response.Cache.SetValidUntilExpires(True)
12 Response.AddCacheDependency(dependency)
13
14 sqlcmd.Connection = connection
15 GridView1.DataSource = sqlcmd.ExecuteReader()
16 GridView1.DataBind()
17 End Using
18 End Sub
You need to ensure that the proxy servers can cache the content of the GridView1 control. Which code segment should you insert at line 13?
A. Response.Cache.SetCacheability(HttpCacheability.Private)
B. Response.Cache.SetCacheability(HttpCacheability.Public)
C. Response.Cache.SetCacheability(HttpCacheability.Server)
D. Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
Answer: B
Microsoft 70-568 Certification Sample Questions and Answers: http://www.braindumpsall.net/70-568-dumps/
P.S. New 70-568 dumps PDF: http://www.4easydumps.com/70-568-dumps-download.html | __label__pos | 0.957673 |
Search Images Maps Play YouTube News Gmail Drive More »
Sign in
Screen reader users: click this link for accessible mode. Accessible mode has the same essential features but works better with your reader.
Patents
1. Advanced Patent Search
Publication numberUS5355478 A
Publication typeGrant
Application numberUS 07/813,237
Publication date11 Oct 1994
Filing date23 Dec 1991
Priority date23 Dec 1991
Fee statusLapsed
Publication number07813237, 813237, US 5355478 A, US 5355478A, US-A-5355478, US5355478 A, US5355478A
InventorsJames T. Brady, Balakrishna R. Iyer
Original AssigneeInternational Business Machines Corporation
Export CitationBiBTeX, EndNote, RefMan
External Links: USPTO, USPTO Assignment, Espacenet
Method for avoiding cache misses during external tournament tree replacement sorting procedures
US 5355478 A
Abstract
A method and apparatus for avoiding line-accessed cache misses during a replacement/selection (tournament) sorting process. Prior to the sorting phase, the method includes the steps of sizing and writing maximal sets of sub-tree nodes of a nested ordering of keys, suitable for staging as cache lines. During the sort phase, the method includes the steps of prefetching into cache from CPU main memory one or more cache lines formed from a sub-tree of ancestor nodes immediate to the node in cache just selected for replacement. The combination of the clustering of ancestor nodes within individual cache lines and the prefetching of cache lines upon replacement node selection permits execution of the full tournament sort procedure without the normally-expected cache miss rate. For selection trees larger than those that can fit entirely into cache, the method avoids the second merge phase overhead that formerly doubled the sorting time necessary for larger cache sizes.
Images(3)
Previous page
Next page
Claims(6)
We claim:
1. In a CPU having a main memory and a line-oriented cache coupled to said main memory, a method for generating sort strings of records while minimizing the number of cache reference misses per record, each said sort string being an ordering of keys of said records, said method including a selection tree having one or more sets of sub-tree nodes, said method comprising the steps of:
(1) sizing and writing into counterpart cache lines one or more said keys corresponding to said sets of sub-tree nodes such that no more than one node in each said cache line has a parent node in another said cache line; and
(2) until exhaustion of said records, performing the recursive steps of:
(a) copying at least one said key from said main memory to said cache,
(b) comparing keys within said cache to identify the replacement node, which contains the smallest said key,
(c) prefetching from said main memory to said cache the cache lines containing ancestor nodes of said replacement node, and
(d) writing the key from said replacement node to said main memory,
whereby said keys are written as one or more orderings into said main memory.
2. The method of claim 1 wherein said performing step (2) comprises the additional step of:
(b.1) determining the cache line location of the parent node of another said sub-tree node.
3. The method of claim 2 wherein said determining step (2)(b.1) comprises the additional steps of:
(b.1.1) determining whether said replacement node is the one node within its cache line that has an outside parent node; and
(b.1.2) identifying the ancestor nodes extending between said outside parent node and the root node of said selection tree.
4. In a CPU having a main memory, a new use for a line-oriented cache coupling said memory for sort string generation of m records while minimizing the number of reference misses per record to said cache, said sort string generation being manifest as a nested ordering of keys of said records, comprising the steps of:
(a) sizing and writing maximal sets of sub-tree nodes of a nested ordering of subsets resident in main memory into counterpart cache lines, said subsets being ones of m/s such subsets of s keys;
(b) during a first pass, until said m/s subsets are exhausted, repeatedly calling m/s subsets of keys from main memory into cache and arranging each said subset into a partial nested ordering thereof including prefetching from main memory a cache line formed from a sub-tree of ancestor nodes immediate to the cached node selected for ordering, and writing said selected node to main memory; and
(c) during a second pass, where t<s, repeatedly executing a t-way replacement selection merge in the cache from among at least one key selected from each of t nested orderings of said subsets resident in main memory until said m/s orderings are exhausted.
5. In a CPU having a main memory for storing program sequences and records, an LRU-managed cache coupling said memory, and means responsive to program sequences for accessing the contents of said main memory and said cache such that
(1) upon a main memory location being read and its contents being concurrently stored in cache, further read references to the main memory location being routed to the cache, and
(2) upon a main memory location being written, the same contents being concurrently written into cache,
a new use for the LRU-managed cache for generation of sort strings of m records while minimizing the number of cache reference misses per record,
said m records being initially stored in main memory,
said sort string generation being manifest as a nested ordering of keys of the records,
said method comprising steps of:
(a) sizing and writing maximal sets of sub-tree nodes of a nested ordering of subsets resident in main memory into counterpart cache lines, said subsets being ones of m/s such subsets of s keys;
(b) during a first pass, until m/s subsets have been exhausted, repeatedly calling m/s subsets of keys from main memory into cache and arranging each said subsets into a partial nested ordering thereof, including prefetching from main memory a cache line formed from a sub-tree of ancestor nodes immediate to the cached node selected for ordering, and writing said selected node to main memory; and
(c) during a second pass, where t<s, repeatedly executing a t-way replacement selection merge in the cache from among at least one key selected from each of t partial nested orderings of the subsets resident in main memory until m/s such orderings become exhausted.
6. In a data processing system for performing an external selection tree replacement sort of a plurality of records, said system having a main memory and a line-oriented cache coupled to said memory, said selection tree having one or more sets of sub-tree nodes, an apparatus for minimizing the number of cache reference misses per record during said sort, said apparatus comprising:
memory partition means in said main memory for sizing and writing into counterpart cache lines one or more said sets of sub-tree nodes such that no more than one node in each said cache line has a parent node in another cache line;
selection means in said cache for identifying the cached sub-tree node having the minimum key within a sub-tree and for labeling said node as the replacement node; and
prefetching means connected to said selection means for prefetching the cache lines containing ancestor nodes of said replacement node in response to identification of said replacement node.
Description
BACKGROUND OF THE INVENTION
1. Field of the Invention
The present invention relates generally to two-phase external selection and merge record key sorting procedures, and more particularly, to a method for minimizing line-accessed cache misses during an external tournament tree replacement sorting procedure.
2. Discussion of the Related Art
The tournament sort is so-called because it matches items against each other just as people are matched against each other in setting up a tennis tournament. The original list is divided in pairs. The winner of each pair is determined and this set becomes the first auxiliary list. First-stage winners are paired and compared to identify second-stage winners. The second-stage winner's list, is paired, in turn, and so forth. The final pair of winners is matched to determine a final winner. The winner in a tournament sort is the lesser-valued key. Thus, the least key in the tournament selection tree is the first key on the sorted output list.
A systematic procedure for such a tournament sort is well-known in the art. For instance, refer to Ivan Flores, "Computer Sorting", pp. 70-84, Prentiss-Hall, Inc., Inglewood Cliffs, N.J. (1969). The classical selection tree or tournament sort removes each "winner" in turn to an output list, and repeats the selection procedure for the keys remaining in the selection tree. The sort is ended when all keys contained in the original tree nodes are exhausted. Thus, a selection tree having P nodes occupies P memory locations and generates an output sort string or "run" of length P. For data sets too large to fit into P memory locations, a series of tournament sorts is employed to create a series of output runs of length P, which are then merged in some manner.
The replacement tournament sort improves on the classical tournament sort by replacing the "winner" with a new key from the list of keys to be sorted. Thus, the contents of the P-node selection tree in memory are perpetually replenished. The fundamental problem with the replacement tournament sort is the management of new replacement keys that are less than the "winner" previously written to the output run.
One method for managing such new keys is to label them as ineligible for participation in the present run. Thus, over time, the selection tree in memory fills with ineligible keys. When all eligible keys are exhausted, the current output run is ended and a new run is begun merely by globally qualifying all previously ineligible keys. The new output run then builds as before, with the replacement tree again slowly filling with new ineligible keys. This process continues indefinitely (as explained in detail by Flores at pp. 121-128), creating a group of sorted output runs that are then merged. Although similar in effect to the nonreplacement tournament sort, this replacement tournament sort method creates longer output runs, with an average length of 2P sorted keys. Refer to Knuth, "Art of Computer Programming", Volume 3/Sorting and Searching, pp. 247-263, Addison-Wesley Publ. Co., Menlow Park, Calif. (1973), for a discussion of this run length enhancement effect for replacement tournament sorts.
A suitable method for labelling ineligible keys is to add an output run number as the most significant element of the key. In such a scheme, all incoming keys are immediately augmented by the addition of the current run number to the most significant key position. The run number remains in place until the key "wins" and can be stripped when the key is written to the sorted output run tables outside of memory. When the replacement key entering memory is tested and found to be less than the last selected key written to the sorted output run, the replacement key is made "ineligible" simply by incrementing the current run number by one before augmenting the ineligible key. Thus, it is appreciated in the art that such run number manipulation is sufficient to ensure that a replacement key is never less than the selected key being replaced. After completion of the initial phase of such a replacement tournament selection sort, several sorted runs having an average length of 2P keys are available in output storage for the second merging phase to be conducted in any suitable manner known in the art.
In U.S. Pat. No. 3,713,107, Harut Barsamian discloses a systematic architecture for the electronic implementation of a tournament sorting procedure that uses the main computer memory for storage of the selection tree nodes. Barsamian discusses the above-described replacement tournament tree sort but does not consider the efficiency problems arising from the addition of cache buffer memory to the processing system.
In U.S. Pat. No. 4,962,451, Douglas R. Case, et al, disclose a new use of a LRU-managed CPU data cache for generation of sorted key runs. Case, et al teach a method for improved caching efficiency that keeps the cached sub-tree size small enough to avoid triggering the cache LRU discipline for moving new lines into cache. The means and method disclosed by Case, et al replaces the prior art taught by Barsamian and thereby obtains a processing speed advantage.
Other practitioners in the art have more recently attempted to improve caching efficiency to enhance replacement tournament sorting procedures. This is a keenly-felt problem in the art, especially for external replacement selection tree sorts involving large numbers of records and limited cache space.
As stored in cache or main memory, the tournament tree nodes normally contain pointers to "losing" sort keys remaining in the tournament. When a "winner" is identified at the root node of the selection tree, the key referenced by the root node pointer is written to the sorted output run and the corresponding leaf node is replaced with a new key pointer from the external list to be sorted. The pointers in the parent and ancestor nodes of the updated leaf node must then be changed to reflect a new winners. The winner changes propagate upwards along the ancestor node path to the root node in a manner well-known in the art. The only nodes subject to change in the selection tree are those nodes on the updating path from the replaced leaf node to the root node of the tree.
Comparison at each node in the updating path requires access to the actual values of the sort keys referenced by the node pointers. Because it is not usually desirable to fit all such sort keys into the cache memory (because of size constraints), this pointer technique entails a large number of CPU cache misses.
Such cache misses can be reduced by either adding the bulky sort keys to the nodes in cache or through the use of less bulky offset value codes. But, neither technique avoids the cache misses resulting from the displacement of the parent node on the updating path from the child node at the lower levels. Examination of FIG. 2, showing a typical 63 node selection tree, demonstrates that the displacement of any parent node(i) is floor(i/2). That is, for large trees, the parent node is about half-way from the root node to the child node in terms of code word storage sequence. Hence, except for the root and the root's immediate children and grandchildren, the parent node is located in a different cache line from the child node for all nodes in the selection tree. If the tree is too large for main memory, almost every parent access will be a cache miss.
The previous solution known in the art and discussed above is to select in a first phase with the maximum tree of P nodes that fits into CPU cache and to invoke one or more merge passes in a second phase. This second merging operation doubles the CPU cycle cost of such sorting procedures, a deplorable overhead penalty that is required only because the cache storage size of P is insufficient for the tree sorted. This is a well-known problem in the art, as will be appreciated when referring to the Knuth reference wherein extensive attention is given to increasing output run lengths from trees of fixed size.
The related unresolved problems and deficiencies are clearly felt in the art and are solved by the present invention in the manner described below.
SUMMARY OF THE INVENTION
The methods of the present invention include suitable clustering of the child nodes with their parent and ancestor nodes and the prefetching of ancestor nodes to reduce both the number of cache misses and the rate of cache line movement into cache. Several alternative clustering arrangements are useful, each having the following properties. Firstly, parent nodes are put in the same cache line as their children nodes wherever possible. Secondly, the number of ancestor node generations accommodated in a single cache line is limited to a predetermined value. Thirdly, the higher ancestor nodes of the single cache line clusters are themselves recursively clustered in a series of other cache lines. Finally, given a leaf node, the cache lines containing all ancestor nodes on the updating path to the root node are determined according to a simple relationship, making it possible to prefetch all such cache lines.
It is an object of this invention to minimize or completely avoid cache misses during the selection phase of an external tournament tree replacement sorting procedure. It is an advantage of the methods of this invention that this objective is met using simple procedures for clustering and prefetching selection tree node data.
Although it is broadly known to prefetch keys arranged in cache line form from main memory on a linearly addressed basis, whereby a line of next higher address is fetched when a line of next lower address is accessed, nothing has previously been taught or suggested regarding the packing of cache lines with sub-tree node clusters as part of a replacement tree sorting procedure. Furthermore, nothing in the art either teaches or suggests the prefetching of cache lines from main memory containing immediate and distant ancestors on the update path of a node currently replaced in cache. It is an unexpected advantage of this invention that both techniques operate as measures minimizing cache misses.
The foregoing, together with other features and advantages of this invention, will become more apparent when referring to the following specification, claims and the accompanying drawings.
BRIEF DESCRIPTION OF THE DRAWINGS
For a more complete understanding of this invention, reference is now made to the following detailed description of the embodiment illustrated in the accompanying drawings, wherein:
FIG. 1, comprising FIGS. 1A-1B, illustrates a 15-node tournament tree replacement sorting operation known in the prior art;
FIG. 2, comprising 2A-2B, illustrates two stages of a 63-node tournament tree organized in a manner known in the prior art; and
FIG. 3 shows a pseudocode chart illustrating the method of this invention for locating the parent node of a child node in memory.
DETAILED DESCRIPTION OF THE PREFERRED EMBODIMENT Description of the Tournament Tree Sort
The replacement-selection (tournament) tree sorting procedure is usually implemented in the manner illustrated in FIGS. 1A-1B. Considering FIG. 1A, a 15-node selection tree is illustrated. Eight keys are depicted in leaf nodes N8-N15. The parent nodes N4-N7 contain the winning keys from the associated leaf node pairs. That is, parent node N4 contains key 4318 because it is the lesser or "winner" between key 6465 and key 4318 in leaf nodes N8 and N9. The contents of parent nodes N5-N7 are similarly determined.
The contents of grandparent nodes N2-N3 are also determined by selecting a winning key from each associated parent node pair. Finally, the content of root node N1 is determined by selecting a winning key from the associated grandparent node pair N2-N3.
In FIG. 1A, ancestor nodes N1-N7 are shown containing the winning keys to better illustrate the upward tournament competition leading to the arrival at root node N1 of the least key from among leaf nodes N8-N15. However, as is well-known in the art, the selection tree is much more useful if the contents of the ancestor nodes include a pointer to the LOSING key in the leaf nodes below, as illustrated in FIG. 1B. The reasons for this can be appreciated by referring, for instance, to the Knuth or Flores references cited above.
FIG. 1A further illustrates the effects of replacing winning key 1728 at leaf node N14 with a new key from the external list (not shown) of keys to be sorted. The effects of replacing key 1728 at leaf node N14 with new key 3946 can be appreciated by inspecting the ancestor nodes along the updating path between leaf node N14 and root node N1. This updating path includes parent node N7, grandparent node N3 and root node N1. Because each of these nodes is pointing to the winning key 1728 (that no longer exists in the tree), every such node must now be changed. This is very inefficient and illustrates the primary reason for storing losing keys in ancestor nodes instead of winning keys.
Figure 1B illustrates a more efficient method known in the art for using an external replacement-selection tree to sort a series of keys. The contents of all ancestor nodes are limited to an "offset value code" (OVC) and a loser pointer representing the results of the competition immediately below. In addition to the OVC shown in each ancestor node N1-N7, there is also a pointer field (not shown) that points to the losing key in memory. These pointer fields are represented by arrows from each ancestor node to the losing key leaf node referenced by the pointer field (not shown). Thus, for instance, ancestor node N7 points to the loser between leaf nodes N14-N15 containing the larger key 4389.
The OVC at node N7 is configured having two parts: (a) the position at which the two keys differ, and (b) the compliment of the losing key value in that position. At ancestor node N7, the position of difference in the child nodes N14-N15 is the highest order decimal position (1) and the compliment of the most significant losing decimal 4 base 10 is 9-4=5. Similarly, ancestor node N3 contains the OVC of the tournament between ancestor nodes N6-N7; i.e., the OVC of 2383 against 1728. Thus, root node N1 contains the OVC of 3246 against 1728 which is (1,6). Key 1728 is the winner at root node N1 and is replaced by a new key 3946 as shown at leaf node N14.
An additional advantage of the OVC technique is that the ancestor node OVC need be changed only when the OVC from below is less than the OVC stored at the ancestor node. This is illustrated in FIG. 1B as follows.
The OVC for the replacement key at leaf node N14 is (1,6). This OVC is carried up to ancestor node N7 and found to be greater than the OVC (1,5) at ancestor node N7. Thus, ancestor node N7 wins and is left unchanged, with the replacement OVC being carried forward to node N3. Because the OVC (1,7) at ancestor node N3 is greater than replacement OVC (1,6), it loses and is replaced. The losing OVC (1,7) from ancestor node N3 is then carried upward to root node N1. Because the existing OVC (1,6) at root node N1 is less than the OVC (1,7) carried upward from ancestor node N3, OVC (1,6) wins and the contents of root node N1 are left unchanged.
Reviewing this procedure with respect to key values, remember that the new OVC at the leaf node N14 was computed by competing the new key against the most recent winner, 1728, giving the result (1,6) shown. Instead of comparing keys 3946 and 4389 at ancestor node N7, which may involve a cache miss to access key 4389, the known OVCs of these two keys against 1728 were compared. Thus, OVC (4389, 1728)=(1,5), which is available at node N7, compares low against OVC (3946, 1728)=(1,6), which was computed at node N14 replacement. Except for equal compares, these offset value codes compare adversely as the keys, and it is conclusively found that key 3946 wins over key 4389 without reference to key 4389. Special processing is required for equal compares, in a manner that obvious in view of this discussion.
The winning OVC (1,6) was carried forward from ancestor node N7 and compared with the OVC of key 2383 against key 1728, stored as (1,7) at ancestor node N3. Since OVC (1,7) compares high to OVC (1,6), key 2383 is the winner at ancestor node N3 and the OVC (1,7) at node N3 was carried forward for competition at root node N1. The OVC (1,6) from below representing winning key 2383 was left behind in ancestor node N3 and the node N3 key pointer was changed to point to the new losing key 3946 at leaf node N14. Because OVC (3946, 2383) equals OVC (3946, 1728), the OVC left behind points to the competition loser at ancestor node N3. This is the property that makes the OVC tournament technique effective and efficient.
The OVC (2383, 1728) taken forward to root node N1 was then compared with OVC (3246, 1728) stored in root node N1. In this competition, key 2383 is the winner because OVC (1,7) collated high. Thus, leaf node N13 containing key 2383 is the new replacement node and key 2383 is written to the sorted output run in external storage.
Again, note that the OVC at, say, ancestor node N4 indicates that keys 6465 and 4318 in leaf nodes N14 and N15 differ in the first decimal position and the value of the first decimal position of the losing key, complimented, is 3. Thus, the OVC comparing keys 6465 and 4318 is written as (1,3) at ancestor node N4. Similarly, ancestor node N2 points to losing key 4318 in leaf node N9 and contains OVC (1,5). The winning key at root node N1 is 1728 as discussed above in connection with FIG. 1A, but root node N1 points to losing key 3246 at leaf node N10.
When the winning key is written to the sorted run output file, it is immediately replaced with a new key from an external key list. This is illustrated as replacement key 3946 in FIG. 1B. Upon replacement, the first step involves computation of the OVC between winning key 1728 and replacement key 3946, which is (1,6) as discussed above.
Again, the only ancestor nodes affected by replacement of the key in leaf node N14 are the ancestor nodes in the direct path between leaf node N14 and root node N1. These are ancestor nodes N7, N3 and root node N1. As discussed above, the OVC can be used to update the tournament tree without the cache misses incurred to access and test the keys themselves.
Comparing the caching effects of the replacement procedure in FIG. 1A with the caching effects of the same replacement operation in FIG. 1B, note that only the OVC at ancestor node N3 was replaced in FIG. 1B. This represents a three-fold increase in caching efficiency over the method illustrated in FIG. 1A without regard to the storage savings arising from the shorter OVC field and clearly demonstrates the preferability of the loser-pointing Offset Value Code method for tournament tree sorting.
The method of FIG. 1B is highly efficient for selection trees that can be entirely contained in a single memory resource within a storage hierarchy. However, for larger trees contained in main memory, the Least Recent Used (LRU) line-oriented CPU cache discipline may not afford sufficient space to simultaneously manipulate all ancestor and leaf nodes within a single selection tree. In such instances, to avoid forcing a later merging operation, portions of the selection tree must be copied into cache from memory as necessary during the tournament selection process.
Considering FIG. 1B, this means that ancestor nodes N7, N3 and root node N1 must be moved into cache in response to replacement of the key in leaf node N14. Thus, even though the memory requirements of the ancestor nodes are minimized by substituting OVCs and losing key pointers for actual keys, the method illustrated in FIG. 1B does little to minimize cache misses arising from tree fragmentation. The reason for this can be better appreciated by considering the 63-node tree shown in FIG. 2A.
The tournament tree sorting procedure known in the art orders the root node, the ancestor nodes and the leaf nodes sequentially in memory in the manner illustrated in FIG. 2A. Thus, the displacement of the immediate parent node for, say, leaf node N45, is nearly half of the distance in code words from root node N1, being first ancestor node N22. Generally, the displacement of the parent of any node i is floor(i/2). The parent is never closer than about half-way to the root node from the child node. Thus, except for the root and its immediate children and grandchildren, the parent is in a different cache line from the child. This inevitably suggests that almost every parent node access is a cache miss if the entire tree does not fit in cache. The previous solution known in the art is to reduce the tree size for the tournament sorting procedure to the maximum tree that fits into the CPU cache and to then invoke one or more subsequent merging passes. These merging passes are known to at least double the CPU processing overhead for the tournament sorting procedure.
The Two Methods of this Invention
Suitable clustering of the nodes with their immediate ancestors and prefetching of the necessary ancestor nodes are the two key solutions to the caching efficiency problems discussed above. The methods of this invention dramatically reduce the number of cache misses and the number of lines called into the cache. Several alternative clustering arrangements are useful. Each useful clustering method shares the following properties:
(a) immediate parent nodes are placed on the same cache lines as their children nodes whenever possible;
(b) ancestor nodes only up to a selected previous generation limit are accommodated in a single cache line;
(c) ancestor nodes in generations beyond such selected previous generation limit are themselves recursively clustered into nested groups within other cache lines; and
(d) the clustering is sufficiently systematic to permit immediate determination of the cache lines containing all ancestor nodes for any given leaf node, making it possible to prefetch all such cache lines.
In the discussion below, a preferred embodiment of both the clustering and the prefetching solutions to the cache miss problem is presented. To ensure simplicity of explanation, the storage utilization scheme has not been optimized for this discussion.
In this discussion, the IBM 370 instruction CFC is considered as exemplary. With the CFC instruction, each tournament tree node in FIG. 2A consists of 8 Bytes. These 8 Bytes include a 4 Byte Offset Value Code having 2 Bytes for the offset and 2 Bytes for the key at this offset. The remaining 4 Bytes contain the pointer field for the losing key. The CPU cache line is assumed to be 128 Bytes long. Hence, 16 code words can be fit into a single cache line. However, the IBM 370 CFCE instruction forms 8-Byte code words. The UPTE instruction expects to find the 8-Byte code words at quad-word boundaries, thus permitting 8 Bytes for an address field. Although the method of this invention applies without limit to code words using either the CFC or the CFCE instruction the CFCE code words are exemplary for purposes of illustration. This forces each code word to begin at quad-word boundaries. Accordingly, as can be appreciated by reference to any suitable system manual, such as IBM Systems/370 Principles of Operation (GA22-7000), International Business Machines Corporation, Armonk, N.Y., each 128-Byte cache line is limited to eight selection tree node code words of 8 Bytes each in view of these assumptions.
The storage clustering method of this invention is illustrated in the following examples. In FIG. 2A, a 63-node tournament tree is considered. The node code words are organized and clustered in main memory in the manner shown in Table 1 below.
TABLE 1______________________________________Cache Lines______________________________________Section 1:Line 1 (4,5,6,7,2,3,1)Section 2:Line 1 (32,33,34,35,16,17,8)Line 2 (36,37,38,39,18,19,9)Line 3 (40,41,42,43,20,21,10)Line 4 (44,45,46,47,22,23,11)Line 5 (48,49,50,51,24,25,12)Line 6 (52,53,54,55,26,27,13)Line 7 (56,57,58,59,28,29,14)Line 8 (60,61,62,63,30,31,15)______________________________________
In FIG. 2B, a 31-node tournament tree is considered. Because there are fewer nodes, the cache line organization scheme is different from that illustrated in Table 1 and is shown in Table 2 below.
TABLE 2______________________________________Cache Lines______________________________________Section 1:Line 1 (*,*,*,*,2,3,1)Section 2:Line 1 (16,17,18,19,8,9,4)Line 2 (20,21,22,23,10,11,5)Line 3 (24,25,26,27,12,13,6)Line 4 (28,29,30,31,14,15,7)______________________________________
Note that the cache lines are grouped into sections for each example. The largest section contains nodes from the bottom-most three generations. This three generation limit results from the eight code word limit for each cache line. The next smallest section includes the subsequent three generations, and so forth. The first section can include from one to three generations, depending on the number in the tree.
Alternatively, the first section could include three generations, with the final largest section left with from one to three generations. This alternative is potentially more wasteful of space and is not preferred.
Considering only the upper four node generations in FIG. 2B as a third example, a 15-node tournament tree should be clustered as shown in Table 3 below.
TABLE 3______________________________________Cache Lines______________________________________Section 1:Line 1 (*,*,*,*,*,*,1)Section 2:Line 1 (8,9,10,11,4,5,2)Line 2 (12,13,14,15,6,7,3)______________________________________
Note that only seven nodes are included in a single cache line in Tables 1-3 above. These seven nodes include four children, their two parent nodes and their single grandparent node. Thus, a cache line with seven nodes contains nodes from three generations. Each group of three generations is segregated in a single section. It will be appreciated that the smallest section must contain the root node N1 and the largest section must contain all leaf nodes.
The node clustering method of this invention as illustrated above requires that no more than one node in any cache line have a parent node that is not within the same cache line. Thus, in Table 1 above, each of the cache lines contain only a single node with parents outside the line. It is this requirement that limits the number of code words per line to seven, although there is room for eight in our exemplary cache line.
The above example for 8-word cache lines can be quickly extended to other cache line sizes by those knowledgeable in the art. For instance, consider a 16-word cache line. Such a line is suitable for a 15-node cluster having only a single node with an external parent. An example of such a line, referring to FIG. 2A for node identification, would be (32,33,34,35,36,37,38,39,16,17,18,19,8,9,4). These lines must be grouped into sections of four generations each, starting with the leaf node generation and proceeding upward as before.
In view of this clustering method, the prefetching method of this invention requires only a simple, nonambiguous algorithm for determining the location of the parent node for any given child node. The parameters provided in Table 4 below illustrate the location of ancestor nodes by specifying their displacement, in terms of numbers of code words from the first cache line, for the tournament tree cache lines from Table 3.
TABLE 4______________________________________Cache Lines______________________________________Section 1:lin 0:Line 1 (*, *, *, *, *, *, 1, *)Displacement 0 1 2 3 4 5 6 7gen * * * * * * 1 *gen.lin * * * * * * 1 *pos 0 1 2 3 4 5 6 7Section 2:lin 1:Line 1 (8, 9, 10, 11, 4, 5, 2, *)Displacement 8 9 10 11 12 13 14 15gen 4 4 4 4 3 3 2 *gen.lin 3 3 3 3 2 2 1 *pos 0 1 2 3 4 5 6 7lin 2:Line 2 (12, 13, 14, 15, 6, 7, 3, *)Displacement 16 17 18 19 20 21 22 23gen 4 4 4 4 3 3 2 *gen.lin 3 3 3 3 2 2 1 *pos 0 1 2 3 4 5 6 7______________________________________
In Table 4, each cache line is identified by its absolute line displacement (lin) from the cache line containing the root node N1. The absolute node displacement from root node N1 (displacement) ranges from zero to 23 code words over the three cache lines illustrated. The absolute node generation (gen) is 1 in the first section and ranges from 2-4 in the second section for the reasons discussed above. The relative node generation with respect to the individual cache line (gen.lin) ranges from 1-3 in each line. Finally, the relative code word position within each cache line (pos) ranges from 0 to 7.
For the location variable definitions shown in Table 4, the preferred algorithm for determining the precise location of a parent node is illustrated in flow chart form in FIG. 3. Obviously, FIG. 3 applies only to 8-word cache lines containing nodes from three generations and must be adapted for other cache line sizes in a manner that is obvious to practitioners in the art in view of these teachings.
Returning briefly to FIG. 1B, consider the following example upon identification of the "winning" key at node N14. Once the replacement node N14 is identified, the update path from N14 to root node N1 is also known. The first step of the following prefetching procedure is to set a pointer to the leaf node N14, child i. Let gen be the distance of the child i from the root+1. The root node has gen=1, and any leaf node has gen=k (for a tournament tree having 2k-1 nodes). Let gen.lin denote the generation within a cache line as shown in Table 4. Nodes belonging to three generations are contained in each cache line. For ease of presentation, this example is restricted to trees having more than seven nodes so that each leaf node will always have gen.lin=3. Thus, every node is uniquely identified by a line offset (lin) from the root node line and a code word offset within the line (pos).
During the execution of the sort procedure, a trace is made from the child i node to the root node. Knowing child i node, both the line offset (lin i) and the position offset (pos i) are also known. It is also known that the relative generation number (gen.lin i)=3 because it was assumed that the tree has at least seven nodes. Thus, it is known that the immediate parent to child i is in the same cache line at a different position (pos), which can be computed according to the pseudocode flow chart shown in FIG. 3.
After the parent to child i is identified, the same algorithm is again used to identify the parent to the parent of child i. This process continues recursively in the manner shown in FIG. 3. When child.gen.lin=1, it is known that the parent node lies in a different cache line from the child node. This then shifts the algorithm to the branch on the right-hand side of FIG. 3, which includes a procedure for identifying the new cache line as well as a new procedure for locating the position (pos) of the parent node within the new cache line.
Thus, the prefetching method of this invention permits the immediate computation of the cache line locations of all nodes within the tournament tree that subject to change as result of the replacement of the contents of child i node. Accordingly, once identified, all such cache lines can be prefetched from main memory into cache as necessary immediately upon identification of the winning key in the tournament tree and even before replacement of such key. Finally, following key replacement at the winning node i, the Offset Value Codes and pointer fields discussed in connection with FIG. 1B can be revised without cache misses because all necessary lines are prefetched into cache. It will be appreciated that the node clustering method of this invention minimizes the number of line prefetches required for each replacement and the ancestor node localization method of this invention permits prefetching of these few necessary lines. In combination, these two methods operate to minimize cache misses during tournament sorting procedures.
Performance Analysis
The following discussion shows the performance improvement expected for the methods of this invention. Of necessity, the following discussion relies on several machine-dependent assumptions.
Each node code word is assumed to include a key, a tag pointer, and a home pointer, for a total of 8 bytes. The code words (CWs) are organized into code word blocks (CWBs) of 2n-1 CWs, where n equals the number of CWs that fill a single cache line. A single cache line is assumed to be 128 Bytes in length and n is assumed to be eight. An IBM 3090 implementation is assumed, wherein a cache hit requires two CPU cycles, a cache miss requires 33 CPU cycles to the first double word, and an additional 15 cycles to fill the cache line. It is assumed that 10 CPU cycles are required to process each code word traversed when a new code word is added to the selection tree. It is also presumed that a micro-instruction exists or can be implemented to prefetch a cache line.
The replacement of a code word in a selection tree that is N layers deep requires an update path traversal of N code words. If all the traversed code words are in cache, the time required to replace a key is:
T=N*(10+2) CPU Cycles (1)
For a 120K record sort, the tournament tree must have 16 levels, giving T=192 cycles from Equation (1). This agrees with the 196 cycles per record noted in actual measurements using pre-sequenced data with DFSORT.
If the entire tournament tree is too large to fit completely into cache, the performance becomes a function of the code word arrangement in memory. The clustering method of this invention places seven codes words within a single cache line and organizes all necessary cache lines into a single Code Word Block (CWB) as shown below in Table 5 for the 15-node tournament tree structure discussed in connection with Table 3.
TABLE 5______________________________________CWB Arrangement______________________________________ CWB 0 = *,*,*,*,*,*,1,* CWB 1 = 8,9,10,11,4,5,2,* CWB 2 = 12,13,14,15,6,7,3,*______________________________________
Referring to Table 5, assume that the insertion node is node 12. This immediately identifies the nodes to be traversed as 12, 6, 3 and 1. With the arrangement shown in Table 5, CWB 2 and CWB 0 must be prefetched. These prefetches are initiated immediately following identification of node 12. The prefetch is ordered with CWB 2 first and then CWB 0. Once the prefetch is initiated, the winner from node 12 is written to the run list outside cache and the cache insertion operation ended. The tournament tree software then fetches the next insertion key from its queue and invokes the Insert Code Word instruction, as can be appreciated by examining Table 6 below.
TABLE 6______________________________________Insert Code Word Cycles______________________________________Determine winner and Prefetch CWB 2 & CWB 0 (cycle starts)End Op of previous Insert Code WordSet up for next Insert Code WordInsert Code Word - takes to cycle 33 for accessing CW 12 cycle 43 for processing CW 12 cycle 45 cache accessing CW 6 cycle 55 for processing CW 6 cycle 57 cache accessing CW 3 cycle 67 for processing CW 3 cycle 69 cache accessing CW 1 cycle 79 for processing CW 1 . . . insert 12 cycles per layer here (the cycle ends after the last layer is processed) cycle 83 Prefetch insert node cycle 87 Prefetch other CWB cycle 88 End Op______________________________________
Thus, the basic CPU timing equation for a too-large tree size is:
Cycles=31+Layers*12 (2)
Without prefetching, an additional cache miss must be added for every three layers traversed in the tree. This changes Equation (2) to the following:
Cycles=31+Layers*12+Ceiling(Layers/3)*31 (3)
In Equation (3), the term "Ceiling(Layers/3)*31" is the CPU overhead cost of not having a hardware cache prefetching capability. For a 120K record sort, the cycle time computed from Equation (2) is 223 cycles and the additional time represented in Equation (3) is 186 cycles for a total of 409 cycles. Thus, Equation (2) with prefetch saves 45% of the CPU cycles required over Equation (3) having no prefetch capability (186/409), which is an 83% improvement in throughput.
Without the node clustering method of this invention, even more cache misses must occur. Because the number of cache misses is not deterministic, the following timing equation is an approximation.
Cycles=(Layers-3)*33+3*12 (4)
In Equation (4), the CPU overhead cost is in the "layers" multiplier of 33. For the 120K record sort, Equation (4) requires 465 cycles, compared to the 223 cycles from Equation (2). Thus, Equation (2) represents a 52% reduction in CPU cycles required over the Equation (4) embodiment having neither the prefetch nor the node clustering improvements of this invention (242/465), which is a 109% improvement in throughput.
Note that timing Equation (1) applies to the situation where the entire tournament tree can be simultaneously loaded into cache. If the size of the tree exceeds cache capacity, then the tournament sort is usually accomplished by using the maximum size tree that can fit and then merging the resulting sort "runs". The inventors have tested a benchmark using a pre-sequenced file compared with a random sequence file of the same size to determine that the increased CPU overhead of the necessary subsequent merging processes approximately doubles the CPU cycle requirements of Equation (1). This leads to the following for too-big trees:
Cycles=24*layers (5)
For Equation (5), the primary overhead expense is the "layer" multiplier of 24. For 120K record sort, Equation (5) requires 384 cycles compared to the 223 cycles from Equation (2). Thus, the node clustering method of this invention represented in Equation (2) provides a 42% reduction in CPU cycles required over the prior art for sorting tournaments that are too large to fit entirely into cache (161/384), which is a 72% improvement in throughput.
A simple Code Word (CW) processing implementation in hardware could reduce the 10 CPU cycles otherwise required because the necessary function is quite simple. The current winner CW is merely compared to the CW of the parent node and, if the winner CW is greater than the parent node CW, then compared to the next parent node CW in the path. If the winner CW is less than the parent node CW, the (now old) winner CW is stored in the parent node and the new winner replaces the old in the internal register that stores the "winner". The next parent node CW is then compared to this new winner and so forth. If any comparisons are equal, the hardware operation could end to permit the software to break the tie. During the processing of the last CW, the hardware function could also defer to software or microcode.
Such a hardware implementation of the CW comparison discussed in connection with FIG. 1B should take no more than 2 cycles over the cycle requirements for accessing the CW if the winning node wins the parent comparison. One of these cycles is the compare operation and the other is the test of a set-up for the next generation. Where the winner loses the comparison with the parent node, an additional cycle is required to swap the registers and a second additional cycle is necessary to put away the old winner, giving a total of four cycles for the hardware operation. Thus, on average, it is reasonable to assume a hardware implementation having an average 3 cycle operation plus the cache access time of 2 cycles per level. Such a hardware implementation can be represented by an approximate timing equation of:
Cycles=5*(layers)+33 (6)
For a 120K record sort, the cycles required from Equation (6) is 113 cycles, a 71% reduction representing a throughput improvement of 240% over the 384 cycles required by Equation (5) for prior art sorting of too-large trees.
Of course, obvious refinements of the node clustering storage arrangements can be deduced from the teachings herein. For example, it is possible to further cluster parents with their children within the same cache line to reduce the (pos) distance from parent to child in a single line. Referring to FIG. 2A and Table 1 above, the clustering scheme can be revised to the one illustrated in Table 7 below.
TABLE 7______________________________________Cache Lines______________________________________Section 1:Line 1 (4,5,2,6,7,3,1)Section 2:Line 1 (32,33,16,34,35,17,8)Line 2 (36,37,18,38,39,19,9)Line 3 (40,41,20,42,43,21,10)Line 4 (44,45,22,46,47,23,11)Line 5 (48,49,24,50,51,25,12)Line 6 (52,53,26,54,55,27,13)Line 7 (56,57,28,58,59,29,14)Line 8 (60,61,30,62,63,31,15)______________________________________
Referring to Table 7, consider Section 1, line 1, which formerly contained (4, 5, 6, 7, 2, 1) in Table 1. The parent of nodes 4 and 5 was moved next to node 5, which places the parent of nodes 6 and 7 next to node 7. Now, in Table 7, if the parent resides in the same cache line, it resides an average of 1.67 positions to the right of the child. In the arrangement shown in Table 1 above, the average distance is 2.5 positions. This reduction could make the parent available earlier if there is a cache miss because the missed cache line is normally fetched in round-robin style starting from the byte whose reference caused the miss. Typically, however, the prefetching technique of this invention will avoid all cache misses.
Obviously, other embodiments and modifications of this invention will occur readily to those of ordinary skill in the art in view of these teachings. Therefore, this invention is to be limited only by the following claims, which include all such obvious embodiments and modifications when viewed in conjunction with the above specification and accompanying drawings.
Patent Citations
Cited PatentFiling datePublication dateApplicantTitle
US3611316 *24 Dec 19695 Oct 1971IbmIndirect indexed searching and sorting
US3713107 *3 Apr 197223 Jan 1973NcrFirmware sort processor system
US3931612 *10 May 19746 Jan 1976Triad Systems CorporationSort apparatus and data processing system
US4090249 *26 Nov 197616 May 1978International Business Machines CorporationApparatus for sorting records in overlap relation with record loading and extraction
US4210961 *19 Sep 19781 Jul 1980Whitlow Computer Services, Inc.Sorting system
US4417321 *18 May 198122 Nov 1983International Business Machines Corp.Qualifying and sorting file record data
US4575798 *3 Jun 198311 Mar 1986International Business Machines CorporationExternal sorting using key value distribution and range formation
US4962451 *7 Nov 19859 Oct 1990International Business Machines CorporationCache-effective sort string generation method
US5175857 *28 Dec 198929 Dec 1992Kabushiki Kaisha ToshibaSystem for sorting records having sorted strings each having a plurality of linked elements each element storing next record address
US5179699 *13 Jan 198912 Jan 1993International Business Machines CorporationPartitioning of sorted lists for multiprocessors sort and merge
US5179717 *13 Nov 198912 Jan 1993Manco, Ltd.Sorting circuit using first and last buffer memories addressed by reference axis data and chain buffer memory addressed by datum number of the first and last buffer memories
US5210870 *27 Mar 199011 May 1993International Business MachinesDatabase sort and merge apparatus with multiple memory arrays having alternating access
US5224217 *3 Aug 199229 Jun 1993Saied ZangenehpourComputer system which uses a least-recently-used algorithm for manipulating data tags when performing cache replacement
US5274805 *5 Jun 199228 Dec 1993Amalgamated Software Of North America, Inc.Method of sorting and compressing data
US5287494 *18 Oct 199015 Feb 1994International Business Machines CorporationSorting/merging tree for determining a next tournament champion in each cycle by simultaneously comparing records in a path of the previous tournament champion
Non-Patent Citations
Reference
1Knuth, Donald E., "The Art of Computer Programming," vol. 3/Sorting and Searching, 1973, pp. 247-266, Addison-Wesley Publishing Company, Inc.
2 *Knuth, Donald E., The Art of Computer Programming, vol. 3/Sorting and Searching, 1973, pp. 247 266, Addison Wesley Publishing Company, Inc.
3 *Tremblay, Jean Paul et al, An Introduction to Data Structures with Applications, 1984 by McGraw Hill, Inc., pp. 678 696.
4Tremblay, Jean-Paul et al, "An Introduction to Data Structures with Applications," 1984 by McGraw-Hill, Inc., pp. 678-696.
Referenced by
Citing PatentFiling datePublication dateApplicantTitle
US5487166 *19 Sep 199423 Jan 1996Amdahl CorporationComputer with two-dimensional merge tournament sort using offset-value coding
US5544342 *10 Jul 19956 Aug 1996International Business Machines CorporationSystem and method for prefetching information in a processing system
US5619693 *2 May 19948 Apr 1997Tandem Computers IncorporatedMethod for sorting and storing data employing dynamic sort tree reconfiguration in volatile memory
US5649153 *19 Jun 199515 Jul 1997International Business Machines CorporationAggressive adaption algorithm for selective record caching
US5713008 *8 Jun 199527 Jan 1998Sun MicrosystemsDetermination of working sets by logging and simulating filesystem operations
US5745679 *6 Mar 199628 Apr 1998Micron Technology, Inc.Method and device for file transfer by cascade release
US5781924 *7 Mar 199714 Jul 1998Sun Microsystems, Inc.Computer caching methods and apparatus
US6385612 *11 Oct 19967 May 2002Compaq Computer CorporationMethod for sorting and storing data employing dynamic sort tree reconfiguration in volatile memory
US64271489 Nov 199830 Jul 2002Compaq Computer CorporationMethod and apparatus for parallel sorting using parallel selection/partitioning
US673876911 Jan 200118 May 2004International Business Machines CorporationSorting multiple-typed data
US6772179 *28 Dec 20013 Aug 2004Lucent Technologies Inc.System and method for improving index performance through prefetching
US7472133 *30 Jul 200430 Dec 2008Microsoft CorporationSystem and method for improved prefetching
US8332595 *19 Feb 200811 Dec 2012Microsoft CorporationTechniques for improving parallel scan operations
US8478775 *30 Jan 20092 Jul 2013Microsoft CorporationEfficient large-scale filtering and/or sorting for querying of column based data encoded structures
US8826107 *28 Dec 20122 Sep 2014Intel CorporationEfficient cache search and error detection
US92512187 Aug 20132 Feb 2016International Business Machines CorporationTunable hardware sort engine for performing composite sorting algorithms
US92512195 Sep 20132 Feb 2016International Business Machines CorporationTunable hardware sort engine for performing composite sorting algorithms
US20060026386 *30 Jul 20042 Feb 2006Microsoft CorporationSystem and method for improved prefetching
US20080010415 *5 Jul 200610 Jan 2008International Business Machines CorporationA pseudo lru tree-based priority cache
US20080235228 *21 Mar 200725 Sep 2008Carmel Gerda KentEfficient string sorting
US20090207521 *19 Feb 200820 Aug 2009Microsoft CorporationTechniques for improving parallel scan operations
US20100088315 *30 Jan 20098 Apr 2010Microsoft CorporationEfficient large-scale filtering and/or sorting for querying of column based data encoded structures
US20120050289 *22 Jun 20111 Mar 2012Industry-Academic Cooperation Foundation, Yonsei UniverstiyImage processing apparatus and method
US20150046475 *5 Sep 201312 Feb 2015International Business Machines CorporationHardware implementation of a tournament tree sort algorithm
US20150046478 *7 Aug 201312 Feb 2015International Business Machines CorporationHardware implementation of a tournament tree sort algorithm
WO1996009580A1 *18 Sep 199528 Mar 1996Amdahl CorpComputer with two-dimensional merge tournament sort using caching
Classifications
U.S. Classification1/1, 711/137, 711/126, 707/999.007
International ClassificationG06F7/24
Cooperative ClassificationY10S707/99937, G06F2207/222, G06F7/24, G06F2207/224
European ClassificationG06F7/24
Legal Events
DateCodeEventDescription
24 Feb 1992ASAssignment
Owner name: INTERNATIONAL BUSINESS MACHINES CORPORATION, NEW Y
Free format text: ASSIGNMENT OF ASSIGNORS INTEREST.;ASSIGNORS:BRADY, JAMES T.;IYER, BALAKRISHNA R.;REEL/FRAME:006021/0836;SIGNING DATES FROM 19911220 TO 19920213
12 Aug 1998REMIMaintenance fee reminder mailed
11 Oct 1998LAPSLapse for failure to pay maintenance fees
22 Dec 1998FPExpired due to failure to pay maintenance fee
Effective date: 19981011 | __label__pos | 0.631869 |
bruno
código apresenta erro
09 de January de 2018 às 01:07PM
tenho um sistema que anteriormente no mysql não apresentava erro, porém ao migrar para mysqli apresenta erro, segue o codigo do cadastro
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>NPJ - PUC Rio</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- CSS code from Bootply.com editor -->
<style type="text/css">
html
{
background: url(assets/img/pilotis.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
h4, h5
{
font-weight:bold;
}
.modal-footer { border-top: 0px; }
#loginModal { margin-top: 0px;}
</style>
</head>
<body >
<!--login modal-->
<div id="loginModal" class="modal show" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="text-center">Núcleo de Prática Jurídica</h1><br>
<h4 class="text-center">Eventos cadastrados pela Professora</h4>
</div>
<div class="modal-body">
<form class="form col-md-12 center-block" action='confirmacao.php' method="post">
<?php
include('conexao.php');
$matricula = $_POST['matricula'];
echo "<input type='hidden' name='matricula' value='$matricula'/>";
$senha = $_POST['senha'];
echo "<input type='hidden' name='senha' value='$senha'/>";
//$sqlMatricula = "SELECT * FROM `INSIRANOMEDOBDAQUI` WHERE matricula = $matricula";
$sqlMatricula = "SELECT * FROM `alunossenha` WHERE matricula = $matricula";
$queryMatricula = mysqli_query($conexao,$sqlMatricula);
if($queryMatricula == true)
{
$rowsMatricula = mysqli_num_rows($queryMatricula);
}
//$sqlProfessor = "SELECT * FROM `INSIRANOMEDOBDPROFESSORAQUI` WHERE 1"
$sqlProfessor = "SELECT * FROM `professores` WHERE 1";
$queryProfessor = mysqli_query($conexao,$sqlProfessor);
if($queryProfessor == true)
{
$rowsProfessor = mysqli_num_rows($queryProfessor);
}
if($rowsMatricula>0)
{
$nome = mysqli_result($queryMatricula,0,'nome');
echo "<input type='hidden' name='nome' value='$nome'/>";
$tel = mysqli_result($queryMatricula,0,'telefone');
$email = mysqli_result($queryMatricula,0,'email');
if(strcmp(mysqli_result($queryMatricula,0,'senha'),$senha) != 0)
{
echo "Senha invalida, tente novamente<br>";
echo '<a href=javascript:history.go(-1) class="btn btn-primary btn-lg btn-block">Voltar</a>';
}
else
{
echo '
<table class="table table-bordered table-striped table-hover">
<tbody>';
echo "
<tr>
<td width='30%'><strong>Matricula</strong></td>
<td width='70%'>$matricula</td>
</tr>
";
echo "
<tr>
<td width='30%'><strong>Nome</strong></td>
<td width='70%'>$nome</td>
</tr>
";
echo "
<tr>
<td width='30%'><strong>Telefone</strong></td>
<td width='70%'><input type=\"text\" name=\"tel\" class=\"form-control input-lg\" value=\"$tel\"></td>
</tr>
";
echo "
<tr>
<td width='30%'><strong>Email</strong></td>
<td width='70%'><input type=\"email\" name=\"email\" class=\"form-control input-lg\" value=\"$email\"></td>
</tr>
";
echo "
<tr>
<td width='30%'><strong>Endereço</strong></td>
<td width='70%'><input type=\"text\" name=\"endereco\" class=\"form-control input-lg\" placeholder=\"R. Marquês de São Vicente, 225\"></td>
</tr>
";
echo "
<tr>
<td width='30%'><strong>Titulo da Monografia</strong></td>
<td width='70%'><input type=\"text\" name=\"titulo\" class=\"form-control input-lg\" placeholder=\"Titulo\"></td>
</tr>
";
echo "
<tr>
<td width='30%'><strong>Professor</strong></td>
<td width='70%'>";
echo '<select class="form-control" id="professor" name="professor">';
for($i=0;$i<$rowsProfessor;$i++)
{
$prof = mysqli_real_escape_string(mysqli_free_result($queryProfessor,$i,'nome'));
echo '<option name="'.$prof.'">'.$prof.'</option>;';
}
echo '</select>';
echo "
<tr>
<td width='30%'><strong>Previsão de Formatura</strong></td>
<td width='70%'>";
echo '<select class="form-control" id="formatura" name="formatura">';
$year = date("Y");
$mes = 6;
for($i=0;$i<8;$i++)
{
if($mes == 6)
$data = "0$mes/$year";
else
$data = "$mes/$year";
echo '<option name="'.$data.'">'.$data.'</option>;';
if($i%2==0)
{
$mes = 12;
}
else
{
$mes=6;
$year++;
}
}
echo '</select>';
echo "
</td>
</tr>
";
echo' </tbody>
</table>';
}
}
?>
</br>
<div class=\"form-group\">
<button type="submit" class="btn btn-primary btn-lg btn-block">Cadastrar</button>
</div>
</form>
</div>
<div class="modal-footer"></div>
</div>
</div>
</div>
<script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<!-- JavaScript jQuery code from Bootply.com editor -->
<script type='text/javascript'>
$(document).ready(function() {
});
</script>
</body>
</html>
essa é a linha do erro
Fatal error: Uncaught Error: Call to undefined function mysqli_result() in C:\xampp\htdocs\side\cadastro.php:79 Stack trace: #0 {main} thrown in C:\xampp\htdocs\side\cadastro.php on line 79
alguém já passou por isso e sabe a solucção
Você precisa estar logado no PHPBrasil.com para poder enviar mensagens para os nossos fóruns.
Faça o login aqui. | __label__pos | 0.945544 |
#!/bin/bash
#
fdir="/tmp/first"sdir="/tmp/second"tdir="/tmp/third"fodir="/tmp/forth"ColLogs() {
echo"收集原始系统日志:"[-d $fdir ] && rm -rf $fdir && mkdir $fdir ||mkdir $fdir
#weblist=`salt "主机名" test.ping | grep -v "True" | awk -F ‘:‘ ‘{print $1}‘`
#list="`salt"主机名"test.ping | grep -v"True"| awk -F ‘:‘ ‘{print $1}‘ | xargs echo`"list="`salt"主机名"test.ping | grep -v"True"| xargs echo | sed"s/://g"`"
for i in $list; dosalt"$i" state.sls zhouz.copydir &> $fdir/$i
echo"$i is ok"done
}
TreatLogsA() {
echo"整理初始化日志(为对比天、小时、分钟、秒钟等字符串是否一致做准备):"[-d $tdir ] && rm -rf $tdir && mkdir $tdir ||mkdir $tdir
cd $fdirfor i in $(ls BX*); dogrep-A 1 ReplacementStrings $i | xargs echo >$tdir/$i
cd $tdir
sed-i ‘s/--/&\n/g‘$i
sed-i ‘s/--\|{\|}\|[[:space:]]//g‘$i
#sed-i ‘s/,/ /g‘$i
sed-i ‘s/,/\./g‘$i
sed-i ‘s/Z//g‘$i
#sed-i ‘s/\./:/g‘$i
sed-i ‘s/ReplacementStrings://g‘$i
#sed-i ‘s/T/:/g‘$i
#sed-i ‘s/2019-07-[0-9][0-9]T//g‘$i
#sed-i ‘s/\.[0-9]\{4,10\}Z//g‘$i
echo"$i is ok"cd $fdir
done
}
TreatLogsB() {
echo"对收集的初始系统日志进行整理(为对比 毫秒差值 做准备):"[-d $sdir ] && rm -rf $sdir && mkdir $sdir ||mkdir $sdir
cd $fdirfor i in $(ls BX*); dogrep-A 1 "ReplacementStrings" $i | xargs echo >$sdir/$i
cd $sdir
sed-i ‘s/--/&\n/g‘$i
sed-i ‘s/--\|{\|}\|[[:space:]]\|Z//g‘$i
sed-i ‘s/,/:/g‘$i
sed-i ‘s/\,\ 1//g‘$i
# sed-i ‘s/\./:/g‘$i 此处将 . 去掉
sed-i ‘s/\.//g‘$i
sed-i ‘s/ReplacementStrings://g‘$i
sed-i ‘s/T/:/g‘$i
# sed-i ‘s/2019-07-[0-9][0-9]T//g‘$i
echo"$i is ok"cd $fdir
done
}
TreatLogsC() {
echo"对收集的初始系统日志进行整理(为对比 秒差值 做准备):"[-d $fodir ] && rm -rf $fodir && mkdir $fodir ||mkdir $fodir
cd $fdirfor i in $(ls BX*); dogrep-A 1 ReplacementStrings $i | xargs echo >$fodir/$i
cd $fodir
sed-i ‘s/--/&\n/g‘$i
sed-i ‘s/--\|{\|}\|[[:space:]]\|Z//g‘$i
sed-i ‘s/,/:/g‘$i
sed-i ‘s/\./:/g‘$i
#sed-i ‘s/\.//g‘$i
sed-i ‘s/ReplacementStrings://g‘$i
sed-i ‘s/T/:/g‘$i
#sed-i ‘s/2019-07-[0-9][0-9]T//g‘$i
echo"$i is ok"cd $fdir
done
}
LogsDay() {
echo"对比两列数据中秒钟是否一致:"cd $fodir
mkdir $fodir/dtime &>/dev/null
for i in $(ls BX*); do#cat $i| awk -F ":" ‘{print $1,":"$2,":"$3,($4-$9)}‘ >$fodir/dtime/$i
cat $i| awk -F ":" ‘{print ($4-$9)}‘ >$fodir/dtime/$i
cd $fodir/dtime
#count=`grep -E -v "0|1" $i | wc -l`
count=`grep -E -v "0" $i | wc -l`if [ $count -ge 1]; then
echo"$i have problem"grep-v ‘0‘$ielseecho"$i is ok"fi
cd $fodir
done
}
DisTimePeriodA() {
echo"对比天、小时、分钟、秒钟等字符串是否一致(批量)"cd $tdir
mkdir $tdir/dtime &>/dev/nullread_file=‘BX*‘
for file in ${read_file}; doecho"$file"
for ((i=1;i<=$(cat $file| wc -l);i++)); do#first="$(sed -n ${i}p $file| awk ‘{print $1}‘)"first="$(sed -n ${i}p $file| awk -F"."‘{print $1}‘)"#second="$(sed -n ${i}p $file | awk ‘{print $2}‘)"second="$(sed -n ${i}p $file | awk -F"."‘{print $3}‘)"#echo"${first}"#echo"${second}"
if [ "${first}" == "${second}"]; then
echo"${first} = ${second}" &>/dev/null
elseA="$(grep $first $file)"#B="$(grep $second $file)"#echo"${first} != ${second}"echo"${A}"fi
done
echo" "done
}
DisTimePeriodB() {
echo"对比天、小时、分钟、秒钟等字符串是否一致(只查询有问题的主机)"cd $tdir
mkdir $tdir/dtime &>/dev/null#read_file=‘BX*‘#for file in ${read_file}; doread-p "请输入有问题的主机名:"file
echo"$file" >>$tdir/dtime/$filefor ((i=1;i<=$(cat $file| wc -l);i++)); do#first="$(sed -n ${i}p $file| awk ‘{print $1}‘)"first="$(sed -n ${i}p $file| awk -F"."‘{print $1}‘)"#second="$(sed -n ${i}p $file | awk ‘{print $2}‘)"second="$(sed -n ${i}p $file | awk -F"."‘{print $3}‘)"
if [ "${first}" == "${second}"]; then
echo"${first} = ${second}" &>/dev/null
else#echo"${first} != ${second}" >>$tdir/dtime/$file
A="$(grep $first $file)"echo"${A}"fi
# echo" " >>$tdir/dtime/$file
done
#done
}
LogsMillisecond() {
echo"对比两列数据中 毫秒 是否一致:"cd $sdir
mkdir $sdir/mtime &>/dev/null
for i in $(ls BX*); docat $i| awk -F ":" ‘{print $1,":"$2,":"$3,($4-$8)}‘ | sort -t $‘ ‘ -k4 -n >$sdir/mtime/$i
cd $sdir/mtime
echo"=================================================="echo"$i 两列毫秒为正数的数值最高的10个"cat $i|tail
#echo"=================================================="#echo"$i 两列毫秒为正数的数值最小的10个"#cat $i|grep -v ‘\-[0-9][0-9][0-9][0-9][0-9]‘ |head -15echo"=================================================="echo"$i 两列毫秒为负数的数值最大的10个"cat $i|grep ‘\-[0-9][0-9][0-9][0-9]‘ |head
#echo"=================================================="#echo"$i 两列毫秒为负数的数值最小的10个"#cat $i|grep ‘\-[0-9][0-9][0-9][0-9]‘ |tail
cd $sdir
done
}
#ColLogs
a="ColLogs"b="TreatLogsA"c="TreatLogsB"d="TreatLogsC"e="LogsDay"f="DisTimePeriodA"g="DisTimePeriodB"h="LogsMillisecond"echo"请选择你想要执行的功能:
a: ColLog
收集windows server初始日志;
b: TreatLogsA
整理初始化日志(为对比天、小时、分钟、秒钟等字符串是否一致做准备);
c: TreatLogsB
整理初始化日志(为对比 毫秒 差值做准备);
d: TreatLogsC
整理初始化日志(为对比 秒 差值做准备);
e: LogsDay
对比两列数据中<< 秒 >>是否一致;
f: DisTimePeriodA 对比天、小时、分钟、秒钟等字符串是否一致(批量显示);
g: DisTimePeriodB 对比天、小时、分钟、秒钟等字符串是否一致(只查询有问题的主机);
h: LogsMillisecond 对比两列数据中<< 毫秒 >>是否一致."read-n3 -p "请输入:"optcase $opt ina)
$a ;;
b)
$b ;;
c)
$c ;;
d)
$d ;;
e)
$e ;;
f)
$f ;;
g)
$g ;;
h)
$h ;;*)
echo"No opt"exit1esac
本文参考链接:https://blog.csdn.net/weixin_42525428/article/details/119589587
评论关闭
IT序号网
微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加! | __label__pos | 0.568821 |
What’s an IP Address and how does it work?
IP Address
What is an IP Address?
An IP address may be a unique identifier for each machine using the web. This identifier is written as a series of numbers separated by intervals, known as the “internet protocol address.”
If you would like to travel a touch deeper, we could mention the 2 different standards for IP addresses. Internet Protocol Version 6 (IPv6) is that the most up-to-date version of IP, while Internet Protocol Version 4 (IPv4) was the primary IP address employed by the general public. Most addresses are IPv4. It’s the foremost widely-deployed IP that won’t too connected devices to the web.
We see that IPv4’s 32-bit address allows for around 4 billion addresses as we crunch the numbers. While that seems like tons, we will safely assume that we have already got 4 billion devices that want to attach to the web.
IPv6 uses eight blocks of 4 hexadecimal digits; it had been designed as an upgrade that also satisfies the necessity for more addresses. In classical logic, there are 340 IPv6 addresses undecillion. That’s more addresses than atoms on the surface of the world.
How Do IP Addresses Work?
When you jump online to send an email, you’re accessing a network that’s connected to the web itself or one that provides you access to the web. Perhaps that’s connecting to whatever internet service provider (ISP) you’ve got reception or employing a company network within the office.
To do this successfully, your computer uses internet protocol, and your IP address is employed as a virtual address to determine a connection.
The blocks of hexadecimal digits that structure an address are called octets.
IP addresses are broken into two parts: a network address and host address (host = the precise device on the network).
This is where it all comes together. The first few bytes in the IP address would identify the network. The exact amount of octets depends on the category of the network. For instance, during a Class A address, the network component is located within the primary byte, while the rest of the address is used to indicate subnets and hosts. In a Class B address, the primary two octets are the network portion, while the remainder is for subnets and hosts, etc.
How Are IP Addresses Assigned?
All of those addresses are allocated by the web Assigned Numbers Authority. This nonprofit U.S. corporation coordinates global IP addresses, which you’ll read all about here.
In fact, IANA assigns blocks of IP addresses to the territorial Internet registries. These regional registries, in turn, assign addresses to ISPs, businesses, schools, and similar institutions within their area.
This means that your IP address would actually come from your organization network or ISP, which has obtained the address from the area Internet register, which has been assigned a block of IANA addresses. (It’s a process.)
Where Does a Router Fit in?
Yes. Routers matter. That box filled with ports collecting dust in your front room is translating data to attach you to the web, also as keeping you safe via the firewall.
In its simplest form, routing is what we call the method of forwarding IP packets from network to network. You probably know a router because of the device you found out to get internet access. To do that, your router is really joining networks and routing traffic between them sort of a switchboard.
To join networks, a router uses network cards, all physically connected to a network and communicating with each other across the IP system to make sure data is moved to and from the correct endpoints.
This means that when you visit the Bloggywissenhomepage, a packet of data comes from your computer and another packet is received by it, which loads your request. This communication bounces between two endpoints, all because this information has been transmitted and directed by routers.
Does This Relate to VPNs?
Yes, IP addresses are related.
In short? A VPN maybe a private network that shares data through a public network just like the internet. When employing a VPN, a user’s IP address will actually get replaced by their VPN provider, but that’s an entirely separate blog post.
Jahid Al Azom
Follow me
Latest posts by Jahid Al Azom (see all)
1 thought on “What’s an IP Address and how does it work?”
1. Pingback: What is Jio Meet? What is different from other meeting app - Blogywissen
Leave a Reply
Your email address will not be published. | __label__pos | 0.988456 |
How do I use headphones and speakers at the same time Windows 7?
How do I use two audio outputs in Windows 7?
It is very possible to have multiple audio outputs in win7.
Multiple simultaneous audio outputs in windows 7
1. open windows media player.
2. right click, click tools, then options.
3. click devices tab.
4. click speakers, then properties.
5. select audio device (select HDMI output)
6. click ok, then ok again.
How can I use headphones and speakers at the same time PC?
Adjust your Windows settings
1. Connect your headphones and speakers to your PC. …
2. Right-click on the volume icon in the taskbar and click Sounds. …
3. Under the Playback tab, right-click Speakers and choose “Set as Default Device”. …
4. Under the Recording tab, right-click Stereo Mix and click Properties.
How do you split audio between headphones and speakers?
How to swap between headphones and speakers
1. Click the small speaker icon next to the clock on your Windows taskbar.
2. Select the small up arrow to the right of your current audio output device.
3. Select your output of choice from the list that appears.
IT IS IMPORTANT: Does Windows 7 have a PDF printer?
How can I play two audio sources at the same time on my computer?
Select the Listen tab on the Stereo Mix window. Then click the Listen to this device checkbox. Select the second playback device listed on the Playback this device drop-down menu. Click the Apply and OK buttons on both the Stereo Mix Properties and Sound window.
How do you use 2 headphones at the same time?
Buy a headphone splitter
Simply plug the splitter into your PC and plug the headphones into the splitter. The most common splitter is the Y splitter, so named because it’s Y-shaped. The Y splitter splits the headphone jack into two audio outputs so you can use two headphones at the same time.
Why does my laptop play sound through headphones and speakers?
When left malfunctioning or outdated, sound card drivers can cause PC audio troubles. If after setting your headphones as your default audio device, your “headphones plugged in but sound coming from speakers” issue still persists, try updating your PC’s sound card driver.
Can you listen to headphones and Bluetooth at the same time?
Most devices won’t let you use the auxiliary output and Bluetooth simultaneously, however, if you add an auxiliary splitter and Bluetooth adapter you can listen to the same music through both channels.
How do I make sound come out of my headphones only?
how to make sound play in headphones only
1. Click on Start.
2. Go to Control Panel and select Hardware and Sound.
3. Click on Sound, it will open a Window with All the sound devices listed in it.
4. Disable the Speaker by right clicking on the Speaker icon and select Disable option.
IT IS IMPORTANT: Question: What are the five main folder in Windows 10? | __label__pos | 0.999989 |
Building Distributed Node.js Apps with Azure Service Bus Queue
Azure Service Bus Queues provides, a queue based, brokered messaging communication between apps, which lets developers build distributed apps on the Cloud and also for hybrid Cloud environments. Azure Service Bus Queue provides First In, First Out (FIFO) messaging infrastructure. Service Bus Queues can be leveraged for communicating between apps, whether the apps are hosted on the cloud or on-premises servers.
windows-azure-c3634
Service Bus Queues are primarily used for distributing application logic into multiple apps. For an example, let’s say, we are building an order processing app where we are building a frontend web app for receiving orders from customers and want to move order processing logic into a backend service where we can implement the order processing logic in an asynchronous manner. In this sample scenario, we can use Azure Service Bus Queue, where we can create an order processing message into Service Bus Queue from frontend app for processing the request. From the backend order processing app, we can receives the message from Queue and can process the request in an efficient manner. This approach also enables better scalability as we can separately scale-up frontend app and backend app.
For this sample scenario, we can deploy the frontend app onto Azure Web Role and backend app onto Azure Worker Role and can separately scale-up both Web Role and Worker Role apps. We can also use Service Bus Queues for hybrid Cloud scenarios where we can communicate between apps hosted on Cloud and On-premises servers.
Using Azure Service Bus Queues in Node.js Apps
In order to working with Azure Service Bus, we need to create a Service Bus namespace from Azure portal.
image
We can take the connection information of Service Bus namespace from the Connection Information tab in the bottom section, after choosing the Service Bus namespace.
image
Creating the Service Bus Client
Firstly, we need to install npm module azure to working with Azure services from Node.js app.
npm install azure
The code block below creates a Service Bus client object using the Node.js module azure.
var azure = require('azure');
var config=require('./config');
var serviceBusClient = azure.createServiceBusService(config.sbConnection);
We create the Service Bus client object by using createServiceBusService method of azure. In the above code block, we pass the Service Bus connection info from a config file. The azure module can also read the environment variables AZURE_SERVICEBUS_NAMESPACE and AZURE_SERVICEBUS_ACCESS_KEY for information required to connect with Azure Service Bus where we can call createServiceBusService method without specifying the connection information.
Creating a Services Bus Queue
The createQueueIfNotExists method of Service Bus client object, returns the queue if it is already exists, or create a new Queue if it is not exists.
var azure = require('azure');
var config=require('./config');
var queue = 'ordersqueue';
var serviceBusClient = azure.createServiceBusService(config.sbConnection);
function createQueue() {
serviceBusClient.createQueueIfNotExists(queue,
function(error){
if(error){
console.log(error);
}
else
{
console.log('Queue ' + queue+ ' exists');
}
});
}
Sending Messages to Services Bus Queue
The below function sendMessage sends a given message to Service Bus Queue
function sendMessage(message) {
serviceBusClient.sendQueueMessage(queue,message,
function(error) {
if (error) {
console.log(error);
}
else
{
console.log('Message sent to queue');
}
});
}
The following code create the queue and sending a message to Queue by calling the methods createQueue and sendMessage which we have created in the previous steps.
createQueue();
var orderMessage={
"OrderId":101,
"OrderDate": new Date().toDateString()
};
sendMessage(JSON.stringify(orderMessage));
We create a JSON object with properties OrderId and OrderDate and send this to the Service Bus Queue. We can send these messages to Queue for communicating with other apps where the receiver apps can read the messages from Queue and perform the application logic based on the messages we have provided.
Receiving Messages from Services Bus Queue
Typically, we will be receive the Service Bus Queue messages from a backend app. The code block below receives the messages from Service Bus Queue and extracting information from the JSON data.
var azure = require('azure');
var config=require('./config');
var queue = 'ordersqueue';
var serviceBusClient = azure.createServiceBusService(config.sbConnection);
function receiveMessages() {
serviceBusClient.receiveQueueMessage(queue,
function (error, message) {
if (error) {
console.log(error);
} else {
var message = JSON.parse(message.body);
console.log('Processing Order# ' + message.OrderId
+ ' placed on ' + message.OrderDate);
}
});
}
By default, the messages will be deleted from Service Bus Queue after reading the messages. This behaviour can be changed by specifying the optional parameter isPeekLock as true as sown in the below code block.
function receiveMessages() {
serviceBusClient.receiveQueueMessage(queue,{ isPeekLock: true },
function (error, message) {
if (error) {
console.log(error);
} else {
var message = JSON.parse(message.body);
console.log('Processing Order# ' + message.OrderId
+ ' placed on ' + message.OrderDate);
serviceBusService.deleteMessage(message,
function (deleteError){
if(!deleteError){
console.delete('Message deleted from Queue');
}
}
});
}
});
}
Here the message will not be automatically deleted from Queue and we can explicitly delete the messages from Queue after reading and successfully implementing the application logic.
Advertisements
Leave a Reply
Fill in your details below or click an icon to log in:
WordPress.com Logo
You are commenting using your WordPress.com account. Log Out / Change )
Google+ photo
You are commenting using your Google+ account. Log Out / Change )
Twitter picture
You are commenting using your Twitter account. Log Out / Change )
Facebook photo
You are commenting using your Facebook account. Log Out / Change )
Connecting to %s | __label__pos | 0.947194 |
1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!
Homework Help: Logarithmic differentiation
1. Apr 21, 2008 #1
1. The problem statement, all variables and given/known data
if g(t)=(10^t)(log....t) then evaluate g'(10)
........................10 <---------(my attempt at a log base 10)
2. Relevant equations
im completely lost...i dont know if i should take the ln of both sides...or what to do really.
3. The attempt at a solution
2. jcsd
3. Apr 22, 2008 #2
[tex]g(t)=10^t\log t[/tex]
Naw don't take log of both sides, just differentiate from the get go :)
[tex]\frac{d}{dx}a^x=a^x\log a[/tex]
Don't forget the Product rule.
Last edited: Apr 22, 2008
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook | __label__pos | 0.692561 |
what is the best way to add music?
0 favourites
• 2 posts
From the Asset Store
Best car suspension with spring effect and very cool terrain generation.
• I added a music file and its huge on the system.
and on the loading it takes ages.
what is the best way to integrate 5mb mp3 file to construct 2?
Thanks
• Try Construct 3
Develop games in your browser. Powerful, performant & highly capable.
Try Now Construct 3 users don't see these ads
• Not really sure there is a best way to integrate music files. You could try to reduce the bitrate on import. If its because you don't want to wait for the loading. You can use Audacity and cut out a section that you can use for testing while making your game and when you are done copy over the correct audio file. At least that way you can add the music and test that it works etc.
Another solution is to make a variable containing the audio file name and just change that around from the test file to the correct file when you are done. Obviously you would have to add the variable name instead of the audio filename the places where you used it with the audio object.
Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests) | __label__pos | 0.753146 |
Home > Bad Code > Closing Output Stream in JSP tag
Closing Output Stream in JSP tag
Here is a code snippet from a custom JSP tag I ran into today:
try
{
out.write(hoursSelectHTML.toString());
out.flush();
}
catch (IOException e)
{
logger.error("Exception writing to the output stream... ", e);
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
// Simply ignore this exception
}
}return SKIP_BODY;
If you are still wondering what is wrong with it, pay attention to the part where the stream is being closed ;)
Categories: Bad Code Tags:
1. No comments yet.
1. No trackbacks yet. | __label__pos | 0.998194 |
-1
$\begingroup$
I have a very fundamental problem, please help me out. I am little confused with the derivation for the close form solution for the Geometric Brownian Motion, from the very fundamental stock model: $$\begin{equation} dS(t)=\mu S(t)dt+\sigma S(t)dW(t) \end{equation} $$ The close form of the above model is following: $$ \begin{equation} S(T)=S(t)\exp((\mu-\frac1 2\sigma^2)(T-t)+\sigma(W(T)-W(t))) \end{equation} $$
I believe this is quite straightforward for most of you guys, but I really dont know how did you get the $(\mu-\frac 1 2 \sigma^2)$ term. It is clear for me the other way round (from bottom to top), but I fail to derive directly from the top to bottom. I checked some material online, it was saying something with the drift term, which some terms are artificially added during the derivation.
Your answer and detailed explanation will be greatly appreciated.
Thanks in advance!
$\endgroup$
• 1
$\begingroup$ Consider $d\ln S(t)$, and see what you can have. Should $r-\frac{1}{2}\sigma^2$ be $\mu-\frac{1}{2}\sigma^2$? $\endgroup$ – Gordon Jul 25 '16 at 19:44
• 4
$\begingroup$ @Donkey_JOHN Let $f(t,x)\in C^{1,2}([0,\infty)\times\mathbb{R}) $ then $$df(t,W_t)=\frac{\partial f}{\partial t}(t,W_t)dt+\frac{\partial f}{\partial x}(t,W_t)dW_t+\frac{1}{2}\frac{\partial ^2f}{\partial x^2}(t,W_t)d[W_t,W_t]$$ $\endgroup$ – user16651 Jul 25 '16 at 20:44
• 4
$\begingroup$ @Donkey_JOHN Also $d[W_t,W_t]=dt$ and $d[t,W_t]=0$ and $d[t,t]=0$ $\endgroup$ – user16651 Jul 25 '16 at 20:45
• 2
$\begingroup$ Let $f(s)\in C^{2}(\mathbb{R}) $ then $$df(S_t)=f'(S_t)dS_t+\frac{1}{2}f''(S_t)d[S_t,S_t]$$ $\endgroup$ – user16651 Jul 25 '16 at 21:03
• 2
$\begingroup$ Set $f(s)=\ln s\in C(\mathbb{R} ^+) $ we have $f'(S_t)=\frac{1}{S_t}$ and $f''(S_t)=-\frac{1}{S_t^2}$ and $d[S_t,S_t]=\sigma^2S_t^2 dt$ $\endgroup$ – user16651 Jul 25 '16 at 21:09
0
$\begingroup$
To get this term you need to take the log of S and to use Ito’s lemma, you can find a detailed explanation in this answer.
$\endgroup$
-1
$\begingroup$
Have you come across Ito lemma / Ito calculus?. As Gordon suggests: divide the top equation by St, so you get $\frac{dS_t}{S_t}$ and we look at 'by intuition' what does $dln(S_t)$ look like in the Ito world.
Ito states: $df(W,t)=\frac{\partial{f}}{\partial{W}}dW+\frac{\partial{f}}{\partial{t}}dt+\frac{1}{2}\frac{\partial^{2}f}{\partial{W^{2}}}dW^{2}$
Now from Ito: $d ln(S_t)=\frac{1}{S_t}dS_t - \frac{1}{2}\cdot \frac{1}{S_t^{2}}\cdot dS_t^{2} = \mu dt+\sigma dW_t-\frac{\sigma^2}{2}dt=(\mu-\frac{\sigma^2}{2})dt+\sigma dW_t$
We use in the second equality that $dS_t^{2}=\mu^{2}S_t^{2}d_t^{2}+2\mu\sigma dt\cdot dW_t+\sigma^{2}dW^{2}_t=\sigma^{2}dW^{2}_t=\sigma^{2}dt$ and substitute the original equation for $dS_t$.
From that it follows that
$ln(S_T)-ln(S_t)=ln(\frac{S_T}{S_t})=(\mu-\frac{\sigma^2}{2})(T-t)+\sigma(W_T-W_t)$ Then by taking $exp(x)$ of both sides of the last equality and multiply by $S_t$ you get the final formula.
$\endgroup$
• 1
$\begingroup$ Nice answer is actually here by @SRKX as well. quant.stackexchange.com/questions/1330/… $\endgroup$ – Jan Sila Jul 25 '16 at 20:19
• 2
$\begingroup$ The claim $d\ln S_t =\frac{dS_t}{S_t}$ and $dln(S_t,t)=\frac{1}{S_t}\times dS_t+\frac{1}{S_t}\times dt - \frac{1}{2}\times\frac{1}{S_t^{2}}\times dS_t^{2} $ do not appear correct to me. $\endgroup$ – Gordon Jul 25 '16 at 20:23
• 2
$\begingroup$ Thanks for correction, but why do you still say that "$dln(St)=\frac{dSt}{St}$ by chain rule"? $\endgroup$ – Gordon Jul 25 '16 at 20:31
• 1
$\begingroup$ Also $\frac{df^2}{dW_t^2}?$ $\endgroup$ – user16651 Jul 25 '16 at 20:35
• 1
$\begingroup$ Thanks @BehrouzMaleki ! Funny how sometimes you think you understand stuff, but you find out you dont only if you try to explain to someone else. Thanks a lot for the comments! $\endgroup$ – Jan Sila Jul 26 '16 at 17:22
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.976353 |
Programación lineal en R
1. Ciclo de vida
2. Tipología
3. Ámbito de aplicación
4. Lenguaje de programación
Descripción
La programación lineal consiste en maximizar o minimizar una función objetivo sujeta a unas restricciones impuestas sobre las variables que forman parte de la misma, ya sea en forma de inecuaciones o bien otras restricciones, como el hecho de que sean enteras.
R proporciona una gran cantidad de paquetes para resolver problemas mediante programación lineal. Uno de los más sencillos es linprog, que usa el algoritmo Simplex para resolver el problema propuesto mediante una notación matricial para la función objetivo y las restricciones. También permite leer y escribir ficheros en formato MPS, el estándar de facto para problemas de programación lineal.
Otra opción es el paquete Rglpk, que es una interfaz R para usar la librería de GNU para resolver problemas mediante programación lineal, la cual debe estar ya instalada previamente. Este paquete solo proporciona dos funciones, una para leer un fichero que contenga la descripción del problema por resolver (incluyendo, entre otros, el formato MPS) y otra para resolver el problema.
Enlace al recurso
https://cran.r-project.org/web/views/Optimization.html
Ejemplo de uso
Usando Rglpk podemos resolver fácilmente problemas como el siguiente:
Simple linear program.
maximize: 2 x_1 + 4 x_2 + 3 x_3
## subject to: 3 x_1 + 4 x_2 + 2 x_3 <= 60
## 2 x_1 + x_2 + 2 x_3 <= 40
## x_1 + 3 x_2 + 2 x_3 <= 80
## x_1, x_2, x_3 are non-negative real numbers
obj <- c(2, 4, 3)
mat <- matrix(c(3, 2, 1, 4, 1, 3, 2, 2, 2), nrow = 3)
dir <- c("<=", "<=", "<=")
rhs <- c(60, 40, 80)
max <- TRUE
Rglpk_solve_LP(obj, mat, dir, rhs, max = max)
En este orden, se define la función objetivo mediante un vector (obj) que contiene los pesos de cada variable; después se define la matriz (mat) que contiene la parte izquierda de las inecuaciones que describen las restricciones; seguidamente, se describe la dirección (dir) de cada inecuación; a continuación, la parte derecha de las inecuaciones (rhs), y, finalmente, se indica que se trata de un problema de maximización (max). Para acabar, se llama a la función que hace de interfaz para resolver el problema mediante la librería GNU para programación lineal.
Enlaces relacionados
Programación lineal: https://es.wikipedia.org/wiki/Programación_lineal
Algoritmo simplex: https://es.wikipedia.org/wiki/Símplex
Formato MPS: https://en.wikipedia.org/wiki/MPS_(format)
Package linprog: https://cran.r-project.org/web/packages/linprog/
Package Rglpk: https://cran.r-project.org/web/packages/Rglpk/index.html
GLPK: https://www.gnu.org/software/glpk/ | __label__pos | 0.521064 |
SQL Extensions «Prev Next»
Lesson 8Saving output to a File with SPOOL
ObjectiveDescribe what gets saved in a file when using SPOOL.
Saving Output to File with SPOOL
You have already discovered and practiced how to save a query into a file. This lesson shows you how to save the results of executing your query into a file by using the SPOOL command. Keep in mind that once the spooling has begun, everything displayed on your screen is saved to the file. The syntax of the command is:
SPO[OL] [filename[.ext]|OFF|OUT]
If you leave off the .ext portion of the filename, SQL*Plus uses .lst. After starting spooling, there are two ways to stop it:
SPOOL OFF
(stop spooling) and
SPOOL OUT
(stop spooling and print the file to the default printer).
Here is an example. Let us say you have prepared a file named CUST_BUY.sql with a query and some SQL*Plus environment commands. You want to write the report to a file and print it.
The first step is to type this command while logged into SQL*Plus:
SPOOL CUST_RPT
Next, you execute the SQL script file:
START CUST_BUY
SQL*Plus executes the file, displaying the results on the screen and writing them to the spool file:
Customer Purchasing
Pg. 1
LASTNAME SALES_DAT TOTAL_SALE
------------------------- --------- ----------
Black 12-DEC-99 61.9
01-MAR-00 108.03
************************* ----------
sum 169.93
After completing the report, you stop the spooling and print the file:
SPOOL OUT
Use SET TERMOUT OFF to suppress output displayed on the screen. This does not affect the output that you spool.
The next lesson concludes this module. | __label__pos | 0.728646 |
0
When I am trying to create shipment for an order, the page throws this error:
Request Timeout
This request takes too long to process, it is timed out by the server. If it should not be timed out, please contact administrator of this web site to increase 'Connection Timeout'."
When I Investigate the problem by exploring the code by creating log, Its stops on random code lines. I am stuck now, what to do, how to know what is the error and which operation is creating the problem. This problem only appears for amazon orders.
1
Timeout means, something needs to long :-)
1. Is there an API call against amazon?
2. Do you have any actions which fire only for amazon orders?
Check the HTTP response, is there any? This error messages looks like generated by the browser, so the question is, what happend on HTTP level.
| improve this answer | |
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.579047 |
Longhorn PHP 2019 Schedule
debug_print_backtrace
(PHP 5, PHP 7)
debug_print_backtrace Affiche la pile d'exécution PHP
Description
debug_print_backtrace ([ int $options = 0 [, int $limit = 0 ]] ) : void
debug_print_backtrace() affiche la pile d'exécution de PHP. Elle affiche les appels aux fonctions, aux fichiers inclus / requis ainsi que les appels à eval().
Liste de paramètres
options
Depuis 5.3.6, ce paramètre est un masque d'options suivantes :
Options pour debug_print_backtrace()
DEBUG_BACKTRACE_IGNORE_ARGS Si l'on doit omettre l'index "args" et ainsi, tous les arguments de la méthode/fonction pour préserver la mémoire.
limit
Depuis 5.4.0, ce paramètre peut être utilisé pour limiter le nombre de trames de la pile à afficher. Par défaut (limit=0), toutes les trames de la pile seront affichées.
Valeurs de retour
Aucune valeur n'est retournée.
Historique
Version Description
5.4.0 Ajout du paramètre optionnel limit.
5.3.6 Ajout du paramètre optionnel options.
Exemples
Exemple #1 Exemple avec debug_print_backtrace()
<?php
// fichier include.php
function a() {
b();
}
function
b() {
c();
}
function
c(){
debug_print_backtrace();
}
a();
?>
<?php
// fichier test.php
// C'est le fichier que vous devez exécuter
include 'include.php';
?>
L'exemple ci-dessus va afficher quelque chose de similaire à :
#0 c() called at [/tmp/include.php:10]
#1 b() called at [/tmp/include.php:6]
#2 a() called at [/tmp/include.php:17]
#3 include(/tmp/include.php) called at [/tmp/test.php:3]
Voir aussi
add a note add a note
User Contributed Notes 7 notes
up
49
bishop
9 years ago
Another way to manipulate and print a backtrace, without using output buffering:
<?php
// print backtrace, getting rid of repeated absolute path on each file
$e = new Exception();
print_r(str_replace('/path/to/code/', '', $e->getTraceAsString()));
?>
up
19
dany dot dylan at gmail dot com
10 years ago
I like the output of debug_print_backtrace() but I sometimes want it as a string.
bortuzar's solution to use output buffering is great, but I'd like to factorize that into a function. Doing that however always results in whatever function name I use appearing at the top of the stack which is redundant.
Below is my noddy (simple) solution. If you don't care for renumbering the call stack, omit the second preg_replace().
<?php
function debug_string_backtrace() {
ob_start();
debug_print_backtrace();
$trace = ob_get_contents();
ob_end_clean();
// Remove first item from backtrace as it's this function which
// is redundant.
$trace = preg_replace ('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1);
// Renumber backtrace items.
$trace = preg_replace ('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);
return
$trace;
}
?>
up
-1
aidan at php dot net
13 years ago
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
http://pear.php.net/package/PHP_Compat
up
-7
AB
3 years ago
This code will give you a simple horizontal stack trace to assist debugging:
<?php
class A {
public function
testA() {
echo
"<LI>Class A.testA ----??";
echo
"<LI>".$this->whoDidThat();
}
public function
whoDidThat() {
$who=debug_backtrace();
$result="";
$count = 0;
$last=count($who);
foreach(
$who as $k=>$v) {
if (
$count++ > 0) {
$x="";
if (
$count>2) {
$x=">";
}
$result="[line".$who[$k]['line']."]".$who[$k]['class'].".".$who[$k]['function'].$x.$result;
}
}
return
$result;
}
}
class
B extends A {
public function
testB() {
echo
"<LI>Class B.testB";
echo
"<LI>".$this->whoDidThat();
}
public function
testA() {
echo
"<LI>Class testB.testA ---- Y";
echo
"<LI>".$this->whoDidThat();
}
}
class
C {
public function
test() {
echo
"<HR>";
$b=new B();
echo
"<HR>Class C calling B.testA";
$b->testA();
}
}
$c=new C();
$c->test();
echo
debug_print_backtrace();
?>
When run you get
Class C calling B.testA
*Class testB.testA ---- Y
*[line45]C.test>[line40]B.testA
up
-8
chris dot kistner at gmail dot com
8 years ago
Here's a function that returns a string with the same information shown in debug_print_backtrace(), with the option to exclude a certain amount of traces (by altering the $traces_to_ignore argument).
I've done a couple of tests to ensure that it prints exactly the same information, but I might have missed something.
This solution is a nice workaround to get the debug_print_backtrace() information if you're already using ob_start() in your PHP code.
<?php
function get_debug_print_backtrace($traces_to_ignore = 1){
$traces = debug_backtrace();
$ret = array();
foreach(
$traces as $i => $call){
if (
$i < $traces_to_ignore ) {
continue;
}
$object = '';
if (isset(
$call['class'])) {
$object = $call['class'].$call['type'];
if (
is_array($call['args'])) {
foreach (
$call['args'] as &$arg) {
get_arg($arg);
}
}
}
$ret[] = '#'.str_pad($i - $traces_to_ignore, 3, ' ')
.
$object.$call['function'].'('.implode(', ', $call['args'])
.
') called at ['.$call['file'].':'.$call['line'].']';
}
return
implode("\n",$ret);
}
function
get_arg(&$arg) {
if (
is_object($arg)) {
$arr = (array)$arg;
$args = array();
foreach(
$arr as $key => $value) {
if (
strpos($key, chr(0)) !== false) {
$key = ''; // Private variable found
}
$args[] = '['.$key.'] => '.get_arg($value);
}
$arg = get_class($arg) . ' Object ('.implode(',', $args).')';
}
}
?>
up
-11
bortuzar at gmail dot com
11 years ago
If you want to get the trace into a variable or DB, I suggest to do the following:
<?php
ob_start
();
debug_print_backtrace();
$trace = ob_get_contents();
ob_end_clean();
$query = sprintf("INSERT INTO EventLog (Trace) VALUES ('%s')",
mysql_real_escape_string($trace));
mysql_query($query);
?>
up
-14
taner
11 years ago
bortuzar: a simpler version, w/o output buffering:
<?php
$query
= sprintf("INSERT INTO EventLog (Trace) VALUES ('%s')",
mysql_real_escape_string(join("\n", debug_backtrace())) );
mysql_query($query);
?>
To Top | __label__pos | 0.823039 |
Sign up ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.
Let $C$ be a compact convex subset of a finite-dimensional real vector space $V$ with non-empty interior (where $V$ is equipped with the unique Hausdorff linear topology, i.e. with the standard topology on $\mathbb{R}^n \cong V$). Is the boundary of $C$ given by the union of all proper faces of $C$?
Recall that a convex subset $F$ of $C$ is a face of $C$ if $\lambda x + (1-\lambda) y \in F$ for some $x, y \in C$ and for some $0 < \lambda < 1$ implies $x, y \in F$. A face $F$ of $C$ is a proper face if $F \neq C$.
If the above is true, I'd like to know how to prove it. Moreover, I wonder whether the statement is still true if the set is only closed and what one can say about the more general case of any (not necessarily finite-dimensional) locally convex space $V$.
share|cite|improve this question
How do you define proper face? – leo Apr 15 '12 at 5:33
I have edited the question, now the definition of a proper face is included. – Tom Jonathan Apr 15 '12 at 5:39
Let $C$ a convex subset of such a space $V$. For each $x,y\in V$ define $S(x,y)=\{\lambda x + (1-\lambda) y \in F:\lambda\in[0,1]\}$ the segment that join $x$ with $y$. So, given $x,y\in C$ any $S(x,y)$ satisfies your definition of Proper Face, however $\bigcup_{x,y\in C} S(x,y)=C$ and $C$ might be different of what one have in mind by union of Proper Faces. For example consider a closed cube $C$ in $\mathbb{R}^3$. One think that the union of proper faces of $C$ must be a "box" $B$, but with that definition, it is all $C$ – leo Apr 15 '12 at 6:04
@leo: No, $S(x,y)$ is not a face of $C$ in general. – Robert Israel Apr 15 '12 at 6:07
1
@leo For all $x, y \in C$ and all $\lambda \in (0, 1)$: If $\lambda x + (1-\lambda) y \in F$ then $x, y \in F$. – WimC Apr 15 '12 at 6:32
1 Answer 1
up vote 3 down vote accepted
A convex set $C$ in ${\mathbb R}^n$ has a supporting hyperplane at each boundary point, and the intersection of a supporting hyperplane with $C$ is a proper face of $C$.
share|cite|improve this answer
Yeah, that's an easy and sufficient argument, thanks! – Tom Jonathan Apr 15 '12 at 7:12
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.55104 |
koul koul - 11 months ago 363
JSON Question
How to send a POST with a JSON in a WebRequest() call using MQL4?
I would like to send a
POST
from
MQL4
-script, using a JSON-format to a Node-server.
I've tried the
webRequest()
standard function in
MQL4
, based on the following documentation, but it did NOT success.
From MQL4 Documentation:
Sending simple requests of type "key=value" using the header `Content-Type: application/x-www-form-urlencoded`.
int WebRequest( const string method, // HTTP method
const string url, // URL
const string cookie, // cookie
const string referer, // referer
int timeout, // timeout
const char &data[], // the array of the HTTP message body
int data_size, // data[] array size in bytes
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
and
Sending a request of any type specifying the custom set of headers for a more flexible interaction with various Web services.
int WebRequest( const string method, // HTTP method
const string url, // URL
const string headers, // headers
int timeout, // timeout
const char &data[], // the array of the HTTP message body
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
Parameters
method [in] HTTP method.
url [in] URL.
headers [in] Request headers of type "key: value", separated by a line break "\r\n".
cookie [in] Cookie value.
referer [in] Value of the Referer header of the HTTP request.
timeout [in] Timeout in milliseconds.
data[] [in] Data array of the HTTP message body.
data_size [in] Size of the data[] array.
result[] [out] An array containing server response data.
result_headers [out] Server response headers.
Returned value:
HTTP server response code or -1 for an error.
Does anyone know how to perfom it?
UPDATE:
Here is the code on the
MQL4
-script side :
#include <Json\hash.mqh>
#include <Json\KoulJSONMgmt.mqh>
void OnStart()
{
string strParam = StringConcatenate("{","\"currency\"",":","\"",Symbol(),"\"",",","\"timeframe\"",":","\"",IntegerToString(Period()),"\"",",","\"ticktime\"",":","\"",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\"",",","\"bid\"",":",DoubleToString(MarketInfo(Symbol(),MODE_BID),4),",","\"ask\"",":",DoubleToString(MarketInfo(Symbol(),MODE_ASK),4),",","\"spread\"",":",DoubleToString(MarketInfo(Symbol(),MODE_SPREAD),0),"}");
JSONParser *parser = new JSONParser();
JSONValue *jv = parser.parse(strParam);
string strJson = jv.toString();
if (jv == NULL) {
Print("error:"+(string)parser.getErrorCode()+parser.getErrorMessage());
} else {
Print("PARSED:"+strJson);
//Example of json String :
//EURUSD,M15: PARSED:{"bid" : 1.1152,"ask" : 1.1154,"spread" : 13,"ticktime" : "2016.10.10 16:24:01","currency" : "EURUSD","timeframe" : "15"}
}
string cookie=NULL,headers;
char post[],result[];
int res;
string strResult,result_header;
headers = "application/json";
prmUrl=StringConcatenate("http://localhost/api"+"/"+"ticks");
//--- Reset the last error code
ResetLastError();
int timeout=1000; //--- Timeout below 1000 (1 sec.) is not enough for slow Internet connection
int intHostNameLength=StringLen(prmParameter);
StringToCharArray(prmParameter,post,0,intHostNameLength);
res=WebRequest("POST",prmUrl,headers,timeout,post,result,result_header);
//--- Checking errors
if(res==-1)
{
Print("Error in WebRequest. Error code =",GetLastError());
//--- Perhaps the URL is not listed, display a message about the necessity to add the address
Print("Add the address '"+prmUrl+"' in the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
}
else
{
for(int i=0;i<ArraySize(result);i++)
{
if( (result[i] == 10) || (result[i] == 13)) {
continue;
} else {
strResult += CharToStr(result[i]);
}
}
ArrayCopy(strResult,result,0,0,WHOLE_ARRAY);
}
Print(strResult);
}
And the Node side is :
server.js
//Create new Tick
app.post('/api/ticks', function(req, res) {
console.log('Inserting New Tick');
var tick = req.body;
console.log('>'+JSON.stringify(tick,null,4));
Tick.addTick(tick, function(err, tick){
if(err) res.json(err);
res.json(tick);
});
});
and in model ticks.js
var mongoose = require('mongoose');
// User Schema
var TickSchema = mongoose.Schema({
currency:{
type: String
},
timeframe: {
type: String
},
ticktime: {
type: Date
},
bid: {
type: Number
},
ask: {
type: Number
},
spread: {
type: Number
},
createddate :{
type: Date,
default: Date.now
}
}, {collection : 'fxTicks'});
var Tick = module.exports = mongoose.model('Tick', TickSchema);
//Create New Tick
module.exports.addTick = function(tick, callback){
Tick.create(tick, callback);
};
// Get Ticks
module.exports.getTicks = function(callback, limit){
Tick.find(callback).limit(limit);
};
Answer Source
So, back to the square No.1:
In the last-year's post, there was a step by step methodology to proceed with a MCVE-based approach to the problem isolation.
Repeating the same steps here, inside MQL4-code,
adding a python-based mock-up WebSERVER, to diagnose the actual working client/server http-protocol exchange & handshaking, ( not the WebSERVER-side interpretation of the delivered POST-request, which is the same, as if one have launched the URL from a WebBROWSER, for all related details ref: BaseHTTPServer.BaseHTTPRequestHandler )
>>> import BaseHTTPServer
>>> server_class = BaseHTTPServer.HTTPServer
>>> handler_class = BaseHTTPServer.BaseHTTPRequestHandler
>>> httpd = server_class( ( '', 8765 ), handler_class )
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 09:46:45] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 09:46:45] "GET /?test=123_from_Chrome HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 09:47:23] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 09:47:23] "GET /favicon.ico HTTP/1.1" 501 -
>>>
>>>
>>>
>>> httpd = server_class( ( '', 80 ), handler_class )
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 10:22:05] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 10:22:05] "GET /?test=123_from_Chrome_on_port_80 HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 10:22:31] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 10:22:31] "GET /?test=123_from_Chrome_on_port_80_again HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 10:22:34] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 10:22:34] "GET /favicon.ico HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 11:25:56] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 11:26:12] "GET /?test=123_from_Chrome_on_port_80_another_call HTTP/1.1" 501 -
>>>
>>>
127.0.0.1 - - [10/Oct/2016 12:03:03] code 501, message Unsupported method ('POST')
127.0.0.1 - - [10/Oct/2016 12:03:03] "POST / HTTP/1.1" 501 -
>>>
the output is
providing an evidence that the last pair of rows were produced by an MQL4-side WebRequest() that was setup correctly and works fine there and back
[ MetaTrader Terminal 4 ]-Log reads:
2016.10.10 12:03:03.921 ___StackOverflow_WebRequest_DEMO XAUUSD,H1:
DATA:: <head><title>Error response</title></head>
<body>
<h1>Error response</h1><p>Error code 501.<p>
Message: Unsupported method ('POST').<p>
Error code explanation: 501 = Server does not support this operation.
</body>
2016.10.10 12:03:03.921 ___StackOverflow_WebRequest_DEMO XAUUSD,H1:
HDRs:: HTTP/1.0 501 Unsupported method ('POST')
Server: BaseHTTP/0.3 Python/2.7.6
Date: Mon, 10 Oct 2016 20:03:03 GMT
Content-Type: text/html
Connection: close
A raw MQL4-snippet BUT use at one's own risk!
( strongly encourage NOT to use any BLOCKING WebRequest() calls
in any Production-grade code...for NON-BLOCKING tools see my other posts and how to or read into internal details on high-performance, low-latency, non-blocking integration tools for distributed heterogeneous systems processing alike ZeroMQ or nanomsg )
All have been warned, so:
Last years setup picture is still valid: enter image description here
The mock-up WebSERVER had inside the dotted form-field input of:
http://localhost/
The simplest MQL4-script OnStart() demonstrator looks this way:
//+------------------------------------------------------------------+
//| ___StackOverflow_WebRequest_DEMO.mq4 |
//| Copyright © 1987-2016 [MS] |
//| nowhere.no |
//+------------------------------------------------------------------+ >>> http://stackoverflow.com/questions/39954177/how-to-send-a-post-with-a-json-in-a-webrequest-call-using-mql4
#property copyright "Copyright © 1987-2016 [MS]"
#property link "nowhere.no"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart(){
/* A BRIGHTER WAY:
string JSON_string = StringFormat( "{\"currency\": \"%s\", \"timeframe\": \"%d\", \"ticktime\": \"%s\", \"bid\": %f, \"ask\": %f, \"spread\": %s }", _Symbol,
Period(),
TimeToString( TimeLocal(), TIME_DATE | TIME_SECONDS ),
MarketInfo( _Symbol, MODE_BID ),
MarketInfo( _Symbol, MODE_ASK ),
MarketInfo( _Symbol, MODE_SPREAD )
);
// A SMARTER WAY & THE FASTEST PROCESSING TIMES:
// --------------
#define MQL4_COMPILE_TIME_JSON_TEMPLATE "{\"currency\": \"%s\", \"timeframe\": \"%d\", \"ticktime\": \"%s\", \"bid\": %f, \"ask\": %f, \"spread\": %s }" // CONSTANT TEMPLATE TO FILL-IN AD-HOC VALUES:
// +
string JSON_string = StringFormat( MQL4_COMPILE_TIME_JSON_TEMPLATE", _Symbol,
Period(),
TimeToString( TimeLocal(), TIME_DATE | TIME_SECONDS ),
MarketInfo( _Symbol, MODE_BID ),
MarketInfo( _Symbol, MODE_ASK ),
MarketInfo( _Symbol, MODE_SPREAD )
);
*/
string JSON_string = StringConcatenate( "{", // **** MQL4 can concat max 63 items
"\"currency\"",
":",
"\"",
Symbol(),
"\"",
",",
"\"timeframe\"",
":",
"\"",
IntegerToString( Period() ),
"\"",
",",
"\"ticktime\"",
":",
"\"",
TimeToString( TimeLocal(), TIME_DATE | TIME_SECONDS ),
"\"",
",",
"\"bid\"",
":",
DoubleToString( MarketInfo( Symbol(), MODE_BID ), 4 ),
",",
"\"ask\"",
":",
DoubleToString( MarketInfo( Symbol(), MODE_ASK ), 4 ),
",",
"\"spread\"",
":",
DoubleToString( MarketInfo( Symbol(), MODE_SPREAD ), 0 ),
"}"
);
// */
/* off-topic: a JSON-string VALIDATOR -----------------------------------------------------------------------------------------------------------------------------------
#include <Json\hash.mqh>
#include <Json\KoulJSONMgmt.mqh>
JSONParser *parser = new JSONParser();
JSONValue *jv = parser.parse(strParam);
string strJson = jv.toString();
if ( jv == NULL ) Print( "ERROR:" + (string) parser.getErrorCode()
+ parser.getErrorMessage()
);
else Print( "PARSED:" + strJson );
// Example of a journalled Print() for an above setup JSON String :
// EURUSD,M15: PARSED:{"bid" : 1.1152,"ask" : 1.1154,"spread" : 13,"ticktime" : "2016.10.10 16:24:01","currency" : "EURUSD","timeframe" : "15"}
*/ // off-topic: a JSON-string VALIDATOR -----------------------------------------------------------------------------------------------------------------------------------
// string ReqSERVER_URL = "http://localhost:8765/", // **** MQL4 WebRequest CANNOT use other port but either of { 80 | 443 } given by protocol pragma stated in URL: { http: | https: }
string ReqSERVER_URL = "http://localhost/", // ---- MQL4 WebRequst
ReqCOOKIE = NULL,
// ReqHEADERs = "application/json"; // **** MQL4 WebRequest MUST use [in] Request headers of type "key: value", separated by a line break "\r\n".
ReqHEADERs = "Content-Type: application/json\r\n";
int ReqTIMEOUT = 5000; // ---- MQL4 WebRequest SHALL use [in] Timeouts below 1000 (1 sec.) are not enough for slow Internet connection;
// ================================================= // ~~~~ MQL4 WebRequest SHALL be AVOIDED as an un-control-able BLOCKING-SHOW-STOPPER, any professional need shall use NON-BLOCKING tools
char POSTed_DATA[],
result_RECVed_DATA_FromSERVER[];
int result_RetCODE;
string result_DecodedFromSERVER,
result_RECVed_HDRs_FromSERVER;
// int intHostNameLength = StringLen( ReqSERVER_URL );
// StringToCharArray( ReqSERVER_URL, POSTed_DATA, 0, StringLen( ReqSERVER_URL ) );
// StringToCharArray( prmParameter, post, 0, intHostNameLength );
StringToCharArray( JSON_string, POSTed_DATA, 0, StringLen( JSON_string ) );
ResetLastError();
result_RetCODE = WebRequest( "POST",
ReqSERVER_URL,
ReqHEADERs,
ReqTIMEOUT,
POSTed_DATA,
result_RECVed_DATA_FromSERVER,
result_RECVed_HDRs_FromSERVER
);
if ( result_RetCODE == -1 ) Print( "Error in WebRequest. Error code =", GetLastError() ); // returns error 4060 – "Function is not allowed for call" unless permitted -- ref. Picture in >>> http://stackoverflow.com/questions/39954177/how-to-send-a-post-with-a-json-in-a-webrequest-call-using-mql4
else {
for ( int i = 0; i < ArraySize( result_RECVed_DATA_FromSERVER ); i++ ) {
if ( ( result_RECVed_DATA_FromSERVER[i] == 10 ) // == '\n' // <LF>
|| ( result_RECVed_DATA_FromSERVER[i] == 13 ) // == '\r' // <CR>
)
continue;
else result_DecodedFromSERVER += CharToStr( result_RECVed_DATA_FromSERVER[i] );
}
Print( "DATA:: ", result_DecodedFromSERVER );
Print( "HDRs:: ", result_RECVed_HDRs_FromSERVER );
}
}
//+------------------------------------------------------------------+
Deviations from documented steps are easily visible in the source and were left for clarity.
Epilogue:
If documentation says something, it is worth keeping that advice ( with some tests, sure ).
If a sponsored Community advice says something, it is worth giving it at least a try, before asking for more. | __label__pos | 0.520891 |
Ansible Part 1: J'ansible, Tu ansibles, il...
Ansible Part 1: J'ansible, Tu ansibles, il...
Published May 15, 2015 in Deployment, System administration - Last update on July 6, 2015.
Ansible is my favourite deployment and configuration management tools. After tested direct concurrency, Puppet and Chef, my choice naturally went to Ansible.
• 1st it is in Python
• 2nd it has a clear YAML syntax
• 3rd it is simple.
What's the stack
My blog uses a classical Django webstack: Nginx + uWSGI + Django + MySQL. Because I'm not billionnaire, I gathers all services in 1 host, but my playbook allow to split into serveral hosts and an app cluster.
I run my playbook with ansible version 1.7.2 and this work is entirely avaiable at Github.com under commit #44994117ee9c8d2e96cea109038e3e09f25d305b. There will be change for future ansible's versions, experiments in my weblog.
Main file
---
- hosts: all
roles:
- {role: common, tags: common}
- {role: database, tags: database}
- {role: cache, tags: cache}
- {role: middleware, tags: middleware}
- {role: frontend, tags: frontend}
I don't think there is more simple, it defines roles and assign them a tag with the same name. It allows me to choice parts to launch.
My playbooks tree - roles for each services
As describe in doc, roles are useful magic tools for auto-include. So my playbook gathers "sub-playbooks" for each services:
• Common: System settings common to all hosts
• Database: MariaDB install and application's database and user creation
• Cache: Redis setup
• Middleware: Django app configuration with uWSGI
• Frontend: Nginx configuration as frontend for uWSGI
~/myblog/extras/ansible $ tree
.
├── hosts
├── main.yml
├── vars.yml └── roles ├── cache │ ├── handlers │ │ └── main.yml │ └── tasks │ └── main.yml ├── common │ ├── handlers │ │ └── main.yml │ ├── tasks │ │ └── main.yml │ └── vars │ └── main.yml ├── database │ ├── handlers │ │ └── main.yml │ ├── tasks │ │ └── main.yml │ ├── templates │ │ └── my.cnf.j2 │ └── vars │ └── main.yml ├── frontend │ ├── files │ │ └── robots.txt │ ├── handlers │ │ └── main.yml │ ├── tasks │ │ └── main.yml │ ├── templates │ │ └── nginx-site.conf.j2 │ └── vars │ └── main.yml └── middleware ├── handlers │ └── main.yml ├── tasks │ └── main.yml ├── templates │ ├── myblog.cfg.j2 │ └── uwsgi.ini.j2 └── vars └── main.yml
Variables
I made my playbook as flexible as possible. It must support a single-host install or splitted architecture with serveral workers. There are several types of variables:
• Constants made for DRY writing, users mustn't edit them
• Inventory variables coupled in ./hosts
• User-defined variables in ./vars.yml
Inventory
My inventory file gathers hosts classed by section where each section matches with a role. Every host must be defined with a its settings which are generaly the adress where to bind the service.
For a single-host I use the following file:
[all]
192.168.0.1 mysql_bind_addr=127.0.0.1 uwsgi_bind_addr=127.0.0.1 redis_bind_addr=127.0.0.1
A splitted service configuration could be like below:
[database]
192.168.0.1 mysql_bind_addr=192.168.0.1
[cache]
192.168.0.2 redis_bind_addr=192.168.0.2
[middleware]
192.168.0.3 uwsgi_bind_addr=192.168.0.3
[frontend]
192.168.0.3
The binded addresses is mandatory for configure how nodes will interact with its backend, example where is my database for Django or where are my middlewares for Nginx.
How did I ...
Deal with single or multiple hosts architecture
I design my blog as a cloud native application and it's supposed to be easily scalable. So I let me the possibility to scale up or down with ansible. Ansible allow to list hosts by categories with the global variable group, a dictionnary of hosts by roles, for example groups['middleware'] returns a list of IP/hostnames. And if I use a single host, there is groups['all'].
My playbook support both methods with the following trick:
(groups.get('all', []) + groups.get('middleware', []))
Simply sum groups['all'] and groups['middleware'] together and if one doesn't exists, replace by an empty list.
Share static files between middleware and frontend
Django has manage.py collectstatic for create a single directory with all static files. The trouble is, data aren't shared from middleware but from frontend. There is Ansible synchronize but it can't make operations between 2 remote hosts, so a manual rsync is the solution.
- name: Update static files
command: rsync -e "ssh -o StrictHostKeyChecking=no" -acogtvz --modify-window=3600 --delete-after --force --no-motd --chown=www-data:www-data root@{{ item }}:{{ static_root }} /var/www/
with_items: (groups.get('all', []) + groups.get('middleware', []))[0]
register: update_static
changed_when: "update_static.stdout.count('\n') > 4"
Protect my private data
All sensitive data are referenced by variables. User must set it in ./vars.yml.
References
Comments
No comments yet.
Post your comment
Comment as . Log out. | __label__pos | 0.526029 |
XSS简单理解之AntiSamy
categories:资料 author:
AntiSamy介绍
OWASP是一个开源的、非盈利的全球性安全组织,致力于应用软件的安全研究。我们的使命是使应用软件更加安全,使企业和组织能够对应用安全风险作出更清晰的决策。目前OWASP全球拥有140个分会近四万名会员,共同推动了安全标准、安全测试工具、安全指导手册等应用安全技术的发展。
OWASP AntiSamy项目可以有好几种定义。从技术角度看,它是一个可确保用户输入的HTML/CSS符合应用规范的API。也可以这么说,它是个确保用户无法在HTML中提交恶意代码的API,而这些恶意代码通常被输入到个人资料、评论等会被服务端存储的数据中。在Web应用程序中,“恶意代码”通常是指 Javascript。同时层叠样式表(CSS)在调用Javascript引擎的时候也会被认为是恶意代码。当然在很多情况下,一些“正常”的HTML 和CSS也会被用于恶意的目的,所以我们也会对此予以处理。
AnitiSamy下载
官方网站:https://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project
项目地址:https://code.google.com/p/owaspantisamy/downloads/list
我们看到Downloads,下载WhereToGet.txt就可以看到下载地址
标准策略文件说明
antisamy-slashdot.xml
Slashdot ( http://www.slashdot.org/ ) 是一个提供技术新闻的网站,它允许用户用有限 的 HTML 格式的内容匿名回帖。 Slashdot 不仅仅是目前同类中最酷的网站之一,而 且同时也曾是最容易被成功攻击的网站之一。更不幸的是,导致大部分用户遭受攻 击的原由是臭名昭着的 goatse.cx 图片 ( 请你不要刻意去看 ) 。 Slashdot 的安全策略非 常严格:用户只能提交下列的 html 标签: <b>, <u>, <i>,
<a>,<blockquote> ,并且 还不支持 CSS.
因此我们创建了这样的策略文件来实现类似的功能。它允许所有文本格式的标签来 直接修饰字体、颜色或者强调作用。
antisamy-ebay.xml
众所周知, eBay ( http://www.ebay.com/ ) 是当下最流行的在线拍卖网站之一。它是一 个面向公众的站点,因此它允许任何人发布一系列富 HTML 的内容。 我们对 eBay 成为一些复杂 XSS 攻击的目标,并对攻击者充满吸引力丝毫不感到奇怪。由于 eBay 允许 输入的内容列表包含了比 Slashdot 更多的富文本内容,所以它的受攻击面也要大得多。下 面的标签看起来是 eBay 允许的( eBay 没有公开标签的验证规则) :
<a>,..
antisamy-myspace.xml
MySpace ( http://www.myspace.com/ ) 是最流行的一个社交网站之一。用户允许提交 几乎所有的他们想用的 HTML 和 CSS ,只要不包含 JavaScript 。 MySpace 现在用一 个黑名单来验证用户输入的 HTML ,这就是为什么它曾受到 Samy 蠕虫攻击 ( http://namb.la/) 的原因。 Samy 蠕虫攻击利用了一个本应该列入黑名单的单词 (eval) 来进行组合碎片攻击的,其实这也是 AntiSamy 立项的原因。
antisamy-anythinggoes.xml
也很难说出一个用这个策略文件的用例。如果你想允许所有有效的 HTML 和 CSS 元素输入(但能拒绝 JavaScript 或跟 CSS 相关的网络钓鱼攻击),你可以使用 这个策略文件。其实即使 MySpace 也没有这么疯狂。然而,它确实提供了一个很 好的参考,因为它包含了对于每个元素的基本规则,所以你在裁剪其它策略文件的 时候可以把它作为一个知识库。
策略文件定制
http://www.owasp.org/index.php/AntiSamy_Directives
AntiSamy.JAVA的使用
首先,老规矩,我们需要一个jar包
使用Maven的,在pom.xml的dependencies中添加如下代码
<dependency>
<groupId>org.owasp.antisamy</groupId>
<artifactId>antisamy</artifactId>
<version>1.5.3</version>
</dependency>
配置web.xml
<!-- XSS -->
<filter>
<filter-name>XSS</filter-name>
<filter-class>com.william.XssFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XSS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
其中XssFilter为自定义的class,该类必须实现Filter类,在XssFilter类中实现doFilter函数。将策略文件放到和pom.xml平级目录下,然后我们就开始编写XssFilter类。
public class XssFilter implements Filter {
@SuppressWarnings("unused")
private FilterConfig filterConfig;
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
}
OK,我们需要重写request,新建一个类RequestWrapper,继承HttpServletRequestWrapper,我们需要重写getParameterMap()方法,以及过滤非法html的方法xssClean()
public class RequestWrapper extends HttpServletRequestWrapper {
public RequestWrapper(HttpServletRequest request) {
super(request);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map<String,String[]> getParameterMap(){
Map<String,String[]> request_map = super.getParameterMap();
Iterator iterator = request_map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry me = (Map.Entry)iterator.next();
//System.out.println(me.getKey()+":");
String[] values = (String[])me.getValue();
for(int i = 0 ; i < values.length ; i++){
System.out.println(values[i]);
values[i] = xssClean(values[i]);
}
}
return request_map;
}
private String xssClean(String value) {
AntiSamy antiSamy = new AntiSamy();
try {
Policy policy = Policy.getInstance("antisamy-myspace-1.4.4.xml");
//CleanResults cr = antiSamy.scan(dirtyInput, policyFilePath);
final CleanResults cr = antiSamy.scan(value, policy);
//安全的HTML输出
return cr.getCleanHTML();
} catch (ScanException e) {
e.printStackTrace();
} catch (PolicyException e) {
e.printStackTrace();
}
return value;
}
}
好了,到此为止,我们的AntiSamy就成功添加到项目了。
CSRF 防御方案总结下,无外乎三种:
1. 用户操作限制,比如验证码;
2. 请求来源限制,比如限制 HTTP Referer 才能完成操作;
3. token 验证机制,比如请求数据字段中添加一个 token,响应请求时校验其有效性;
第一种方案明显严重影响了用户体验,而且还有额外的开发成本;第二种方案成本最低,但是并不能保证 100% 安全,而且很有可能会埋坑;第三种方案,可取!
https://www.cnblogs.com/wangdaijun/p/5652864.html
————————
1 前言
Antisamy是OWASP(open web application security project)的一个开源项目,其能够对用户输入的html/css/javascript 脚本进行过滤,确保输入满足规范,无法提交恶意脚本。Antisamy被应用在web服务中对存储型和反射性的xss防御,尤其是在存在富文本输入的场景,antisamy能够很好的解决用户输入体验和安全要求之间的冲突。
• Antisamy的对包含非法字符的用户输入的过滤依赖于策略文件,策略文件规定了antisamy对各个标签、属性的处理方法。策略文件定义的严格与否,决定了antisamy对xss漏洞的防御效果。
• OWASP中antisamy有java和.net两个项目,这篇文档中仅对java项目进行介绍。从安装、使用及策略文件的定制几个方面讲解如何将antisamy应用到实际项目当中。
2 工具安装
• Antisamy的官方下载路径:++https://code.google.com/archive/p/owaspantisamy/downloads++。下载列表中包含antisamy的jar包,同时也包含了几个常用的策略文件。官方下载的链接需要翻墙,为方便使用,将最新版本的antisamy和策略文件放到文档的附件中(见附件1)。
• Antisamy直接导入到java的工程即可,但是其运行依赖另外三个库:
xercesImpl.jar http://xerces.apache.org/mirrors.cgi#binary
batik.jar http://xmlgraphics.apache.org/batik/download.cgi
nekohtml.jar http://sourceforge.net/projects/nekohtml/
• 可以通过链接下载,也可以从marven中直接下载。测试过程中使用的是从marven中下载,使用的版本信息如下:
<orderEntry type=”library” name=”xerces:xercesImpl:2.11.0″ level=”project” />
<orderEntry type=”library” name=”com.nrinaudo:kantan.xpath-nekohtml_2.12:0.1.9″ level=”project” />
<orderEntry type=”library” name=”org.apache.xmlgraphics:batik-script:1.8″ level=”project” />
• 在导入完成后,在java工程中新建一个类,输入如下代码进行测试,确认安装是否正确。
1. public class AntiSamyApplication {
2. public static void main(String[] args)
3. {
4. AntiSamy as = new AntiSamy();
5. try{
6. Policy policy = Policy.getInstance(“\\antisamy\\antisamy-tinymce-1.4.4.xml”);
7. CleanResults cr = as.scan(“<div>wwwww<script>alert(1)</script></div>”, policy);
8. System.out.print(cr.getCleanHTML());
9. }
10. catch(Exception ex) {
11. } ;
12. }
13. }
如果输出结果如下结果,说明安装正确,可以正常使用antisamy了。
1. “C:\Program Files (x86)\Java\jdk1.8.0_121\bin\java”
2. <div>wwwwwdddd</div>
3. Process finished with exit code 0
3 使用方法
Antisamy存在两种使用方法,一种是从系统层面,重写request处理相关的功能函数,对用户输入的每一个参数均作过滤验证;另外一种是仅对富文本使用过滤验证;
4 策略文件
4.1 策略文件结构
一个简易的Antisamy的策略文件主体结构如所示:
Antisamy的策略文件为xml格式的,除去xml文件头外,可以为7个部分,下面对各个部分的功能做简单的介绍。
1. <directives>
2. <directive name=“omitXmlDeclaration” value=“true” />
3. <directive name=“omitDoctypeDeclaration” value=“true” />
4. </directives>
对应上图中标注为1的部分,主要为全局性配置,对antisamy的过滤验证规则、输入及输出的格式进行全局性的控制。具体字段的意义在后面继续文档中详细介绍。
1. <common-regexps>
2. <regexp name=“htmlTitle” value=“[a-zA-Z0-9\s\-_’,:\[\]!\./\\\(\)&]*” />
3. <regexp name=“onsiteURL” value=“([\p{L}\p{N}\p{Zs}/\.\?=&\-~])+” />
4. <regexp name=“offsiteURL” value=“(\s)*((ht|f)tp(s?)://|mailto:)[A-Za-z0-9]+[~a-zA-Z0-9-_\.@\#\$%&;:,\?=/\+!\(\)]*(\s)*” />
5. </common-regexps>
对应上图中标注为2的部分,将规则文件中需要使用到的正则表达式相同的部分归总到这,会在后续中需要正则的时候通过name直接引用;
1. <common-attributes>
2. <attribute name=“title” description=“The ‘title’ attribute provides text that shows up in a ‘tooltip’ when a user hovers their mouse over the element”>
3. <regexp-list>
4. <regexp name=“htmlTitle” />
5. </regexp-list>
6. </attribute>
7. </common-attributes>
对应上图中标注为3的部分,这部分定义了通用的属性需要满足的输入规则,其中包括了标签和css的属性;在后续的tag和css的处理规则中会引用到上述定义的属性。
1. <global-tag-attributes>
2. <attribute name=“title” />
3. </global-tag-attributes>
对应上图中标注为4的部分,这部分定义了所有标签的默认属性需要遵守的规则;需要验证如果标签中为validate,有属性但是不全的场景
1. <tags-to-encode>
2. <tag>g</tag>
3. <tag>grin</tag>
4. </tags-to-encode>
对应上图中标注为5的部分,这部分定义了需要进行编码处理的标签;
1. <tag-rules>
2. <!– Remove –>
3. <tag name=“script” action=“remove” />
4. <!– Truncate –>
5. <tag name=“br” action=“truncate” />
6. <!– Validate –>
7. <tag name=“p” action=“validate”>
8. <attribute name=“align” />
9. </tag>
10. </tag-rules>
对应上图中标注为6的部分,这部分定义了tag的处理规则,共有三种处理方式:
remove:对应的标签直接删除如script标签处理规则为删除,当输入为:
<div><script>alert(1);</script></div>
输出为:
<div>ddd</div>
truncate:对应的标签进行缩短处理,直接删除所有属性,只保留标签和值;如标签dd处理规则为truncate,当输入为:
<dd id='dd00001' align='left'>test</test>
validate:对应的标签的属性进行验证,如果tag中定义了属性的验证规则,按照tag中的规则执行;如果标签中未定义属性,则按照 \<global-tag-attributes\> 中定义的处理;
1. <css-rules>
2. <property name=“text-decoration” default=“none” description=“”>
3. <category-list>
4. <category value=“visual” />
5. </category-list>
6. <literal-list>
7. <literal value=“underline” />
8. <literal value=“overline” />
9. <literal value=“line-through” />
10. </literal-list>
11. </property>
12. </css-rules>
对应上图中中标注为7的部分,这部分定义了css的处理规则;
4.2 策略文件详解
4.2.1 策略文件指令[<directives></directives>]
策略文件指令包含13个参数,下面对其参数的意义逐一介绍。
1. <directives>
2. <directive name=“useXHTML” value=“false”/>
3. <directive name=“omitXMLDeclaration” value=“true”/>
4. <directive name=“omitDoctypeDeclaration” value=“true”/>
5. <directive name=“formatOutput” value=“false”/>
6. <directive name=“maxInputSize” value=“100000”/>
7. <directive name=“embedStyleSheets” value=“false”/>
8. <directive name=“maxStyleSheetImports” value=“1”/>
9. <directive name=“connectionTimeout” value=“1000”/>
10. <directive name=“preserveComments” value=“false”/>
11. <directive name=“nofollowAnchors” value=“false”/>
12. <directive name=“validateParamAsEmbed” value=“false”/>
13. <directive name=“preserveSpace” value=“false”/>
14. <directive name=“onUnknownTag” value=“remove”/>
15. </directives>
下面的介绍中使用到的样例均以antisamy-myspace-1.4.4.xml为基础进行修改
useXHML>
类型:boolean
默认值: false
功能:开启后,antisamy的结果将按照XHTML的格式输出;默认使用HTML;
注:XHTML和HTML的主要区别在于XHMTL格式更加严格,元素必须正确的嵌套,必须闭合,标签名要小写,必须要有根元素;
在测试过程中,发现该参数实际上对输出的结果没什么影响。
omitXMLDeclaration>
类型:boolean
默认值:true
功能:按照文档描述,在开启时antisamy自动添加xml的头
测试时发现该参数对输出没啥影响。
omitDoctypeDeclaration>
类型: boolean
默认值:true
功能:在值为false时,antisamy在输出结果中自动添加html头
当输入为:
<div class='navWrapper'><p>sec_test<script>alert(1);</script></p></div>
输出结果为:
1. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
2. “http://www.w3.org/TR/html4/strict.dtd”>
3. <div class=“navWrapper”>
4. <p>sec_test</p>
5. </div>
formatOutput>
类型:boolean
默认值:true
功能:开启后,antisamy会将输出结果格式化,使可读性更好;
默认是开启的,在关闭后,当输入为:
<div class='navWrapper'><p>sec_test<script>alert(1);</script></p></div>
输出结果为:
<div class="navWrapper"><p>sec_test</p></div>
注:可以和omitDoctypeDeclaration的结果对比着看。
maxInputSize>
类型:int
默认值:100000
功能:用于验证的最长字符串长度,单位bytes;
embedStyleSheets>
类型:boolean
默认值:false
功能:在开启css过滤功能后,该指令确认是否将引用的css文件下载下来并导入到用户输入一起作为检查的输入;
maxStyleSheetImports>
类型:int
默认值:1
功能:配合embedStyleSheets使用,指定在输入中可以下载css文件的个数;
connecttionTimeout>
类型:int
默认值:1000
功能:配合embedStyleSheets使用,指定在下载css文件时的超时时长,单位为毫秒;
preserveComments>
类型:boolean
默认值:false
功能:开启后,保留输入中的注释行;
nofollowAnchors>
类型:boolean
默认值:falsle
功能:开启后,在锚点标签(<a>)后添加rel=“nofollow”属性,防止跳转到其他页面
开启后当输入为:
<div><a href='www.baid.com'>click</a></div>
输出结果为:
1. <div>
2. <a href=“www.baid.com” rel=“nofollow”>click</a></div>
validateParamAsEmbed>
类型:booblean
默认值:false
功能:开启后,antisamy将<embed>标签的属性和嵌入到embed标签内的<param>标签的属性相同的规则处理,主要用于在需要用户输入的视频站点。
preserveSpace>
类型:boolean
默认值:false
功能:开启后,保留输入中的空格;
onUnknowTag>
类型:String
默认值:remove
功能:对未知tag的处理规则,默认为删除,可以修改为encode;
4.2.2 通用正则表达式 [<common-regexps> </common-regexps>]
其定义的格式为:
<regexp name="htmlId" value="[a-zA-Z0-9\:\-_\.]+"/>
htmlId为正则的名称,通过名称被引用
value后面是具体的正则表达式的内容 该部分可以参考antisamy中样例规则文件编写;
如有特殊需要,正则表达式可以参考网上其他资料进行编写。
4.2.3 通用属性 [<common-attributes> </common-attributes>]
通用属性义如下:
1. <attribute name=“media”>
2. <regexp-list>
3. <regexp value=“[a-zA-Z0-9,\-\s]+”/>
4. <regexp name=“htmlId”/>
5. </regexp-list>
6. <literal-list>
7. <literal value=“screen”/>
8. <literal value=“tty”/>
9. <literal value=“tv”/>
10. </literal-list>
11. </attribute>
“attribute name”为标签的名称,与html的tag名称保持一致;
“regexp name”为标签需要满足的正则表达式的名称,其在<common-regexps>中定义;
“regexp value”为标签需要满足的正则表达式;
可以通过literal直接指定属性的值;如media的值可以满足上面两个的正则表达式外,也可以为screen、tty、tv中的一个
注:<regexp-list><literal-list>中的值均可以为多个
4.2.4 全局tag属性<global-tag-attributes>
其定义和4.2.3中通用属性的定义无区别,只能功能不同;
具体功能在后面tag的规则介绍(4.2.7)中展示;
4.2.5 编码处理tag<tag-to-encode>
此处标识的tag将在输出中进行编码;
其定义的格式为:
1. <tags-to-encode>
2. <tag>g</tag>
3. <tag>grin</tag>
4. </tags-to-encode>
但是实际测试的时候,并未生效。
4.2.6 tag处理规则<tag-rules>
tag-rules的定义规则如下:
1. <tag name=“button” action=“validate”>
2. <attribute name=“name”/>
3. <attribute name=“value”>
4. <regexp-list>
5. <regexp name=“anything”/>
6. </regexp-list>
7. </attribute>
8. <attribute name=“type”>
9. <literal-list>
10. <literal value=“submit”/>
11. <literal value=“reset”/>
12. <literal value=“button”/>
13. </literal-list>
14. </attribute>
15. </tag>
tagc-rule的action有三种:remove、validate、truncate,各个动作的功能在4.1中介绍过,不再赘述.
其中有一种场景需要注意:
<tag name="h1" action="validate"/>
这种标签中action是validate,但是标签的属性需要遵守的正则却没有标识出来;在这个时候,4.2.4中全局tag属性中定义的属性就起作用了。上面这种类型的标签就需要遵守4.2.4中定义的全局属性;
如:h1标签处理规则如下:
<tag name="h1" action="validate"/>
输入为:
<div><h1 id='h111' align='center'>h1 title</h1></div>
输出为:
1. <div>
2. <h1 id=“h111″>h1 title</h1></div>
global-tag-attribute中有”id”, “style”,”title”,”class”,”lang”这5个标签,不包括align,所以在输出中就被过滤掉了。
4.2.7 css处理规则<css-rules>
css-rules定义如下:
1. <property name=“background-color” description=“This property sets the background color of an element, either a <color> value or the keyword ‘transparent’, to make the underlying colors shine through.”>
2. <literal-list>
3. <literal value=“transparent”/>
4. <literal value=“inherit”/>
5. </literal-list>
6. <regexp-list>
7. <regexp name=“colorName”/>
8. <regexp name=“colorCode”/>
9. <regexp name=“rgbCode”/>
10. <regexp name=“systemColor”/>
11. </regexp-list>
12. </property>
从上面可以看出,css过滤规格的定义和tag的基本相同;但是css有一些特殊的字段,如:
1. <property name=“background” description=“The ‘background’ property is a shorthand property for setting the individual background properties (i.e., ‘background-color’, ‘background-image’, ‘background-repeat’, ‘background-attachment’ and ‘background-position’) at the same place in the style sheet.”>
2. <literal-list>
3. <literal value=“inherit”/>
4. </literal-list>
5. <shorthand-list>
6. <shorthand name=“background-color”/>
7. <shorthand name=“background-image”/>
8. <shorthand name=“background-repeat”/>
9. <shorthand name=“background-attachment”/>
10. <shorthand name=“background-position”/>
11. </shorthand-list>
12. </property>
相比tag的过滤规则,css增加了shorthand-list,为css的自有语法。意味着如果background有多个值,说明使用了css的缩写,同时需要满足shorthand中规定的属性的过滤规则。
4.3 通用策略文件
5 Antisamy代码简介
antisamy对html进行扫描的主要流程如下:
其中
recursiveValidateTag(tmp, currentStackDepth);
为antisamy最终执行扫描的函数,其通过递归调用对html中每一个标签根据规则文件的定义进行处理
https://blog.csdn.net/raychiu757374816/article/details/79016101
快乐成长 每天进步一点点 京ICP备18032580号-1 | __label__pos | 0.955283 |
Skip to navigation
Elite on the BBC Micro
Dashboard: SCAN
[BBC Micro cassette version]
Name: SCAN [Show more] Type: Subroutine Category: Dashboard Summary: Display the current ship on the scanner Deep dive: The 3D scanner
Context: See this subroutine in context in the source code Variations: See code variations for this subroutine in the different versions References: This subroutine is called as follows: * ESCAPE calls SCAN * MVEIT (Part 2 of 9) calls SCAN * MVEIT (Part 9 of 9) calls SCAN * WPSHPS calls SCAN
This is used both to display a ship on the scanner, and to erase it again. Arguments: INWK The ship's data block
.SCAN LDA INWK+31 \ Fetch the ship's scanner flag from byte #31 AND #%00010000 \ If bit 4 is clear then the ship should not be shown BEQ SC5 \ on the scanner, so return from the subroutine (as SC5 \ contains an RTS) LDA TYPE \ Fetch the ship's type from TYPE into A BMI SC5 \ If this is the planet or the sun, then the type will \ have bit 7 set and we don't want to display it on the \ scanner, so return from the subroutine (as SC5 \ contains an RTS) LDX #&FF \ Set X to the default scanner colour of green/cyan \ (a 4-pixel mode 5 byte in colour 3) \CMP #TGL \ These instructions are commented out in the original \BEQ SC49 \ source. Along with the block just below, they would \ set X to colour 1 (red) for asteroids, cargo canisters \ and escape pods, rather than green/cyan. Presumably \ they decided it didn't work that well against the red \ ellipse and took this code out for release CMP #MSL \ If this is not a missile, skip the following BNE P%+4 \ instruction LDX #&F0 \ This is a missile, so set X to colour 2 (yellow/white) \CMP #AST \ These instructions are commented out in the original \BCC P%+4 \ source. See above for an explanation of what they do \LDX #&0F \.SC49 STX COL \ Store X, the colour of this ship on the scanner, in \ COL LDA INWK+1 \ If any of x_hi, y_hi and z_hi have a 1 in bit 6 or 7, ORA INWK+4 \ then the ship is too far away to be shown on the ORA INWK+7 \ scanner, so return from the subroutine (as SC5 AND #%11000000 \ contains an RTS) BNE SC5 \ If we get here, we know x_hi, y_hi and z_hi are all \ 63 (%00111111) or less \ Now, we convert the x_hi coordinate of the ship into \ the screen x-coordinate of the dot on the scanner, \ using the following (see the deep dive on "The 3D \ scanner" for an explanation): \ \ X1 = 123 + (x_sign x_hi) LDA INWK+1 \ Set x_hi CLC \ Clear the C flag so we can do addition below LDX INWK+2 \ Set X = x_sign BPL SC2 \ If x_sign is positive, skip the following EOR #%11111111 \ x_sign is negative, so flip the bits in A and subtract ADC #1 \ 1 to make it a negative number (bit 7 will now be set \ as we confirmed above that bits 6 and 7 are clear). So \ this gives A the sign of x_sign and gives it a value \ range of -63 (%11000001) to 0 .SC2 ADC #123 \ Set X1 = 123 + x_hi STA X1 \ Next, we convert the z_hi coordinate of the ship into \ the y-coordinate of the base of the ship's stick, \ like this (see the deep dive on "The 3D scanner" for \ an explanation): \ \ SC = 220 - (z_sign z_hi) / 4 \ \ though the following code actually does it like this: \ \ SC = 255 - (35 + z_hi / 4) LDA INWK+7 \ Set A = z_hi / 4 LSR A \ LSR A \ So A is in the range 0-15 CLC \ Clear the C flag LDX INWK+8 \ Set X = z_sign BPL SC3 \ If z_sign is positive, skip the following EOR #%11111111 \ z_sign is negative, so flip the bits in A and set the SEC \ C flag. As above, this makes A negative, this time \ with a range of -16 (%11110000) to -1 (%11111111). And \ as we are about to do an ADC, the SEC effectively adds \ another 1 to that value, giving a range of -15 to 0 .SC3 ADC #35 \ Set A = 35 + A to give a number in the range 20 to 50 EOR #%11111111 \ Flip all the bits and store in SC, so SC is in the STA SC \ range 205 to 235, with a higher z_hi giving a lower SC \ Now for the stick height, which we calculate using the \ following (see the deep dive on "The 3D scanner" for \ an explanation): \ \ A = - (y_sign y_hi) / 2 LDA INWK+4 \ Set A = y_hi / 2 LSR A CLC \ Clear the C flag LDX INWK+5 \ Set X = y_sign BMI SCD6 \ If y_sign is negative, skip the following, as we \ already have a positive value in A EOR #%11111111 \ y_sign is positive, so flip the bits in A and set the SEC \ C flag. This makes A negative, and as we are about to \ do an ADC below, the SEC effectively adds another 1 to \ that value to implement two's complement negation, so \ we don't need to add another 1 here .SCD6 \ We now have all the information we need to draw this \ ship on the scanner, namely: \ \ X1 = the screen x-coordinate of the ship's dot \ \ SC = the screen y-coordinate of the base of the \ stick \ \ A = the screen height of the ship's stick, with the \ correct sign for adding to the base of the stick \ to get the dot's y-coordinate \ \ First, though, we have to make sure the dot is inside \ the dashboard, by moving it if necessary ADC SC \ Set A = SC + A, so A now contains the y-coordinate of \ the end of the stick, plus the length of the stick, to \ give us the screen y-coordinate of the dot BPL ld246 \ If the result has bit 0 clear, then the result has \ overflowed and is bigger than 256, so jump to ld246 to \ set A to the maximum allowed value of 246 (this \ instruction isn't required as we test both the maximum \ and minimum below, but it might save a few cycles) CMP #194 \ If A >= 194, skip the following instruction, as 194 is BCS P%+4 \ the minimum allowed value of A LDA #194 \ A < 194, so set A to 194, the minimum allowed value \ for the y-coordinate of our ship's dot CMP #247 \ If A < 247, skip the following instruction, as 246 is BCC P%+4 \ the maximum allowed value of A .ld246 LDA #246 \ A >= 247, so set A to 246, the maximum allowed value \ for the y-coordinate of our ship's dot STA Y1 \ Store A in Y1, as it now contains the screen \ y-coordinate for the ship's dot, clipped so that it \ fits within the dashboard SEC \ Set A = A - SC to get the stick length, by reversing SBC SC \ the ADC SC we did above. This clears the C flag if the \ result is negative (i.e. the stick length is negative) \ and sets it if the result is positive (i.e. the stick \ length is negative) \ So now we have the following: \ \ X1 = the screen x-coordinate of the ship's dot, \ clipped to fit into the dashboard \ \ Y1 = the screen y-coordinate of the ship's dot, \ clipped to fit into the dashboard \ \ SC = the screen y-coordinate of the base of the \ stick \ \ A = the screen height of the ship's stick, with the \ correct sign for adding to the base of the stick \ to get the dot's y-coordinate \ \ C = 0 if A is negative, 1 if A is positive \ \ and we can get on with drawing the dot and stick PHP \ Store the flags (specifically the C flag) from the \ above subtraction \BCS SC48 \ These instructions are commented out in the original \EOR #&FF \ source. They would negate A if the C flag were set, \ADC #1 \ which would reverse the direction of all the sticks, \ so you could turn your joystick around. Perhaps one of \ the authors' test sticks was easier to use upside \ down? Who knows... .SC48 PHA \ Store the stick height in A on the stack JSR CPIX4 \ Draw a double-height dot at (X1, Y1). This also leaves \ the following variables set up for the dot's top-right \ pixel, the last pixel to be drawn (as the dot gets \ drawn from the bottom up): \ \ SC(1 0) = screen address of the pixel's character \ block \ \ Y = number of the character row containing the pixel \ \ X = the pixel's number (0-3) in that row \ \ We can use there as the starting point for drawing the \ stick, if there is one LDA CTWOS+1,X \ Load the same mode 5 1-pixel byte that we just used AND COL \ for the top-right pixel, and mask it with the same STA X1 \ colour, storing the result in X1, so we can use it as \ the character row byte for the stick PLA \ Restore the stick height from the stack into A PLP \ Restore the flags from above, so the C flag once again \ reflects the sign of the stick height TAX \ Copy the stick height into X BEQ RTS \ If the stick height is zero, then there is no stick to \ draw, so return from the subroutine (as RTS contains \ an RTS) BCC RTS+1 \ If the C flag is clear then the stick height in A is \ negative, so jump down to RTS+1 .VLL1 \ If we get here then the stick length is positive (so \ the dot is below the ellipse and the stick is above \ the dot, and we need to draw the stick upwards from \ the dot) DEY \ We want to draw the stick upwards, so decrement the \ pixel row in Y BPL VL1 \ If Y is still positive then it correctly points at the \ line above, so jump to VL1 to skip the following LDY #7 \ We just decremented Y up through the top of the \ character block, so we need to move it to the last row \ in the character above, so set Y to 7, the number of \ the last row DEC SC+1 \ Decrement the high byte of the screen address to move \ to the character block above .VL1 LDA X1 \ Set A to the character row byte for the stick, which \ we stored in X1 above, and which has the same pixel \ pattern as the bottom-right pixel of the dot (so the \ stick comes out of the right side of the dot) EOR (SC),Y \ Draw the stick on row Y of the character block using STA (SC),Y \ EOR logic DEX \ Decrement the (positive) stick height in X BNE VLL1 \ If we still have more stick to draw, jump up to VLL1 \ to draw the next pixel .RTS RTS \ Return from the subroutine \ If we get here then the stick length is negative (so \ the dot is above the ellipse and the stick is below \ the dot, and we need to draw the stick downwards from \ the dot) INY \ We want to draw the stick downwards, so we first \ increment the row counter so that it's pointing to the \ bottom-right pixel in the dot (as opposed to the top- \ right pixel that the call to CPIX4 finished on) CPY #8 \ If the row number in Y is less than 8, then it BNE P%+6 \ correctly points at the next line down, so jump to \ VLL2 to skip the following LDY #0 \ We just incremented Y down through the bottom of the \ character block, so we need to move it to the first \ row in the character below, so set Y to 0, the number \ of the first row INC SC+1 \ Increment the high byte of the screen address to move \ to the character block above .VLL2 INY \ We want to draw the stick itself, heading downwards, \ so increment the pixel row in Y CPY #8 \ If the row number in Y is less than 8, then it BNE VL2 \ correctly points at the next line down, so jump to \ VL2 to skip the following LDY #0 \ We just incremented Y down through the bottom of the \ character block, so we need to move it to the first \ row in the character below, so set Y to 0, the number \ of the first row INC SC+1 \ Increment the high byte of the screen address to move \ to the character block above .VL2 LDA X1 \ Set A to the character row byte for the stick, which \ we stored in X1 above, and which has the same pixel \ pattern as the bottom-right pixel of the dot (so the \ stick comes out of the right side of the dot) EOR (SC),Y \ Draw the stick on row Y of the character block using STA (SC),Y \ EOR logic INX \ Increment the (negative) stick height in X BNE VLL2 \ If we still have more stick to draw, jump up to VLL2 \ to draw the next pixel RTS \ Return from the subroutine | __label__pos | 0.988492 |
Answers
2014-03-18T22:54:37-04:00
This Is a Certified Answer
×
Certified answers contain reliable, trustworthy information vouched for by a hand-picked team of experts. Brainly has millions of high quality answers, all of them carefully moderated by our most trusted community members, but certified answers are the finest of the finest.
Basically, you isolate one of the variables, and then plug it in to the other equation... for example
x-y=4
2x+3y=18
so you isolate the variable x in the first equation by adding y to both sidesand get
x=4+y
and then plug it in to the other equation
2(4+y)+3y=18
8+2y+3y=18
subtract 8 from both sides and combine like terms
5y=10
divide by 5
y=2
x-2=4
x=6
(6,2) is the solution set :)
0 | __label__pos | 0.612628 |
Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.
Often one gets warnings of the form (example)
LaTeX Font Warning: Font shape `T1/qcs/m/sl' in size <10.95> not available
(Font) Font shape `T1/qcs/m/it' tried instead on input line 7.
when some font/size combinations are not available. But what exactly do the things like
T1/qcs/m/sl
mean?
What do the four "letter combinations" separated by a / mean?
(The given warning and shape combination is just an example to have something to work with, the question is meant in the most general way.)
share|improve this question
2
someone else can give the complete story. what's important here is that the part that is different -- "sl" vs. "it" -- means that the slanted (oblique roman) is not available, and true italic has been substituted. instead of the two-story shape for "a", you will get the one-story shape instead. in most cases, this particular substitution won't matter, but if it does, you may need to find a different font. – barbara beeton Apr 19 '13 at 20:00
2 Answers 2
up vote 22 down vote accepted
Fonts in LaTeX are characterized by four independent attributes:
1. Encoding
2. Family
3. Series
4. Shape
The encoding refers to the "output encoding"; commonly used ones are OT1 (classical TeX fonts) and T1 (Cork encoding for European languages), but also TS1 is found (Text Symbols); other encodings are T2A T2B T2C (for cyrillic), T3 (IPA glyphs), T4 (African languages) and T5 (Vietnamese).
The family attribute identifies a font family: cmr is the default Computer Modern, ptm is "Adobe Times New Roman", qcs is "TeX Gyre Schola" (cs is the two letter combination that refers to New Century Schoolbook or clones thereof).
The series is the "weight" of the font; it refers to both the thickness of the strokes and their width, so the letters can be m (for medium), bx (bold extended), b (bold), but also other series are found. Typical scalable fonts from the Postscript world have m and b weights (and bx is remapped to b).
The shape can be upright (n), italic (it), slanted (sl) or small capitals (sc). Some font families have also an "unslanted italic" variant (ui).
When LaTeX finds a new encoding+family combination it tries to read a font description file (for instance t1ptm.fd or t1qcs.fd) that contains in a convenient format the instructions for associating a "real font" to combinations of attributes. If the font description file doesn't exist, it's also possible to give explicitly these associations in the LaTeX document.
In some cases the combination of attributes doesn't point to an existent font. This is the case, for instance, of "T1/cmtt/bx/n" (Computer Modern Typewriter bold extended upright in T1 encoding). LaTeX can act differently in these cases:
• if the .fd file defines a substitution rule, LaTeX follows the rule
• if the .fd file doesn't tell anything useful, LaTeX uses some built-in rules
It would be quite long to describe the built-in rules (they are found in source2e.pdf). Let's examine two cases.
In the t1cmtt.fd file we find the line
\DeclareFontShape{T1}{cmtt}{bx}{n}{<->ssub*cmtt/m/n}{}
which means
if the T1/cmtt/bx/n combination is requested, silently change it into T1/cmtt/m/n.
In the t1qcs.fd file there is instead
\DeclareFontShape{T1}{qcs}{m}{sl}{<->sub * qcs/m/it}{}
which means
if the T1/qcs/m/sl combination is requested, change it into T1/qcs/m/it and warn the user (once).
Note that the encoding is never changed, because this might end up in printing unexpected characters.
The difference between the two cases is just an "s": ssub means "silently substitute", while sub means "substitute and warn" (the warning about this particular substitution is issued only once).
It's a developer's choice: the TeX Gyre people thought it best to warn a user about this substitution; there is no TeX Gyre Schola slanted font, so another one must be chosen.
For the most common attributes LaTeX has commands for setting them: \bfseries chooses the bx series attribute (actually it uses the macro \bfdefault); similarly \itshape chooses the shape attribute it (again, the reality is that \itdefault is used) and so on. Font developers can use arbitrarily many series and shape attributes. Some fonts have tens of possible choices.
share|improve this answer
T1/qcs/m/sl:
T1 --- \fontencoding T1 (european, ``Cork''),
qcs --- \fontfamily: TeX Gyre Schola,
m --- \fontseries: medium,
sl --- \fontshape: slanted.
Edit: According to Kurt's wish, families and packages of \TeX Gyre
\TeX Gyre Termes qtm tgtermes
\TeX Gyre Pagella qpl tgpagella
\TeX Gyre Bonum qbk tgbonum
\TeX Gyre Schola qcs tgschola
\TeX Gyre Chorus qzc tgchorus
\TeX Gyre Adventor qag tgadventor
\TeX Gyre Heros qhv tgheros
\TeX Gyre Cursor qcr tgcursor
share|improve this answer
1
I think here is a more general answer needed, for example were can I find qcs to know the font, ... – Kurt Apr 19 '13 at 20:15
@Kurt given T1 and qgcs you can use kpesehich t1qcs.sty which will lead you to /latex/tex-gyre/t1qcs.fd and the font ec-qcsri – David Carlisle Apr 19 '13 at 20:24
@DavidCarlisle I thought a hint to fontname.pdf and an explanation of the LaTeX name schema would be helpful ... – Kurt Apr 19 '13 at 20:26
@Kurt I was going to mention fontname but my copy doesn't seem to mention qcs so I thought I'd better not:-) – David Carlisle Apr 19 '13 at 20:29
Oh, the qcs was just an example in my question. I didn't want to ask without an example, but my question is meant in the most general way. :) – Foo Bar Apr 19 '13 at 20:52
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.702781 |
0
$\begingroup$
I want to solve these equations but Mathematica gives no answer.
X :=
3/2 x (-((γ y (1 - z)^3 (-x^2 - y^2 + 1)^2)/z^3) + x^2 - y^2 - 1) -
(λ y z)/(1 - z);
Y :=
-((3 γ (y^2 - 1) (1 - z)^3 (-x^2 - y^2 + 1)^2)/(2 z^3)) + 3/2 y (x^2 - y^2 + 1) +
(λ x z)/(1 - z);
Z :=
3/2 ((1 - z) z (x^2 - y^2 + 1) - (γ y (1 - z)^4 (-x^2 - y^2 + 1)^2)/z^2);
Solve[X == Y == Z == 0, {x, y, z}]
{}
What do I do?
$\endgroup$
5
• 3
$\begingroup$ Reduce[{X == Y == Z == 0}, {x, y, z}] $\endgroup$
– user36273
Jun 25 '16 at 10:25
• 1
$\begingroup$ As a side note, it is considered bad form to use capital letters as declared variables. Or to use multi-letter variables that start with capital letters. $\endgroup$
– Feyre
Jun 25 '16 at 11:41
• $\begingroup$ This system cannot be solved with the methods available to Solve. (or Reduce) $\endgroup$
– Young
Jun 26 '16 at 3:03
• $\begingroup$ @Young Do you Know another method? $\endgroup$
– milad
Jun 26 '16 at 7:32
• $\begingroup$ @milad , @Young This system can be solved with Reduce! $\endgroup$
– user36273
Jun 26 '16 at 12:35
1
$\begingroup$
Please check the documentation on Solve.
Under Details:
enter image description here
{} means that your system has no solutions in general.
Reduce does give a solution, but notice that it comes with the specific condition that λ == 0. For general λ there is no solution.
Solve gives generic solutions only. Another excerpt from the documentation:
Solve gives generic solutions only. Solutions that are valid only when continuous parameters satisfy equations are removed. Other solutions that are only conditionally valid are expressed as ConditionalExpression objects.
$\endgroup$
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.653939 |
Skip to content
Arcana Auth: Release Notes
Release Date: Oct 12, 2023
Version: Oct12-23-gasless
The Arcana Auth product consists of the following components:
What's New?
New iconNew icon
Gasless Transactions
Developers can make it easier for Web3 app users to get started and encourage more people to use their apps by removing the Web3 gas fee obstacle with the Arcana Auth gasless feature. Discover how gasless transactions work, how to configure gasless and set up gas tanks for an app. If you have any other queries regarding the gasless feature, refer to the gasless FAQ.
Debugging gasless issues
Apps that enable the gasless feature may sometimes find cryptic errors returned in case of the transaction failure. Refer to the error handling section on how to debug gasless issues and pinpoint the exact cause and fix it using Tenderly.
Gasless Usage Changes
App Users
Gasless enabled apps will not require to pay any gas fees for any of the whitelisted blockchain operations. Besides zero gas fees, the app users will see a change in their wallet address when gasless is enabled for an app.
Earlier, there was only a single EoA wallet address associated with each authenticated app user. Apps with gasless feature will require to configure gas tank for one or more blockchain networks. For such apps the app user account will be associated with two types of wallet addresses: an EoA address and a SCW address. By default, all gasless transactions happen via the SCW account. Users can switch between EoA and SCW accounts using the wallet UI.
Developers
In addition to configuring the social provider and customizing wallet experience, chains, etc., developers must set up gas tanks for the blockchain network, deposit gas in the tanks and ensure that all the requisite app operations that are supposed to be gasless get whitelisted in the gasless configuration settings. Also, developers must ensure that they use the SCW wallet address when issuing blockchain transactions that must be gasless. EoA address should be used for getPublicKey() call or to personal sign messages. The user's public/private key is associated with EoA address and not with the SCW address.
Get Started
Ready to dive in?
Use Arcana Auth Quick Start Guide to start using Arcana Auth.
See integration examples for various dApp types, wallet connectors and frameworks.
Arcana Auth SDK: No Changes
If you already using the previous version of the Arcana Auth SDK v1.0.8, you can continue to use the latest release of the product vOct12-23-gasless. There are no updates to the Arcana Auth SDK package.
Please note, in case are using an older version of the Arcana Auth SDK prior to v1.0.7 then refer to the appropriate Migration Guides and upgrade to the latest version.
Previous Releases
See the release notes archive for details.
Questions?
Refer to the Arcana Auth FAQ, Troubleshooting Guide, and other developer resources, or contact Arcana Support.
Last update: October 27, 2023 by shaloo, shalz | __label__pos | 0.595604 |
V
V
Vadimqa2020-04-05 11:31:01
Angular
Vadimqa, 2020-04-05 11:31:01
Angular subscribe(): Cannot read property 'subscribe' of undefined?
The service sends data to the subscription in the wrong format, help bring it to the desired form.
Service
getStats() {
let statsLS = localStorage.getItem('stats');
let slt = +localStorage.getItem('slt');
let date = new Date();
let time = date.getTime();
if(statsLS === null || slt < time) {
this.http.get('/server/api/statsService').subscribe((data: any) => {
this.stats = data;
let date = new Date();
let time = date.getTime()+60000+'';
localStorage.setItem('stats',JSON.stringify(this.stats));
localStorage.setItem('slt',time);
return this.stats;
});
} else {
return JSON.parse(statsLS);
}
}
}
Component
ngOnInit() {
this.statsService.getStats().subscribe((data: any) => console.log(data));
}
Answer the question
In order to leave comments, you need to log in
1 answer(s)
A
Anton, 2020-04-05
@Vadimqa
You don't return anything at all in the getStats() code.
You are returning data from a function that is your http.get subscriber.
As far as I remember, you need to declare an object of type Observable() inside getStats() and return it. Something like this in general:
getStats()
{
return new Observable<any>((observer) => {
let statsLS = localStorage.getItem('stats');
let slt = +localStorage.getItem('slt');
let date = new Date();
let time = date.getTime();
if (statsLS === null || slt < time) {
this.http.get('/server/api/statsService').subscribe((data: any) => {
this.stats = data;
let date = new Date();
let time = date.getTime() + 60000 + '';
localStorage.setItem('stats', JSON.stringify(this.stats));
localStorage.setItem('slt', time);
observer.next(this.stats);
});
} else {
observer.next(JSON.parse(statsLS));
}
});
}
Didn't find what you were looking for?
Ask your question
Ask a Question
731 491 924 answers to any question | __label__pos | 0.994145 |
Subscript In Google Docs Equation
Insert Tab
1. Select the element on which you are going to apply Subscript.
2. Then go to Insert Tab.
3. And then select Special Character option.
Format Tab
1. Select the element which will be Subscript
2. Then go to Format Tab
3. And click on Text after that select the Subscript
Key Combination
As usual select the element which will be Subscript then press CTRL +,
To remove subscript press CTRL +, again.
To use Superscript in google docs, follow the same process but when you use Key Combination then press CTRL +.
Equation
To use the equation editor, open a Google Docs document. In the document, select the Insert menu and select EquationThis opens the equation editor.
Edit and Delete an Equation
Once we have inserted the equation, it appears in the document as an image. To edit or delete it, you just have to click on it with the mouse to select it and the labels to edit or delete appear. As it is an image, we can also pull the corners to increase or reduce its size. The document can be exported to other formats such as Word or Open Office but the equation cannot be edited outside of Google Docs.
Leave a Comment
Your email address will not be published. Required fields are marked * | __label__pos | 0.999629 |
0
I want to have equal spaces between my caption number and caption text on the list of figures and list of tables. I tried modifying the lines as given Here But the list of figures have less space in the table of contents compared to the List of tables. Here is my MWE
\documentclass{report}
\usepackage{etoolbox}
\usepackage{lipsum}
\usepackage{tocloft}
\makeatletter
\patchcmd{\@caption}{\csname the#1\endcsname}{\textbf{\csnamefnum@#1\endcsname:}}{}{}
\renewcommand*\l@figure{\@dottedtocline{1}{1.5em}{5.6em}}
\let\l@table\l@figure
\makeatother
\begin{document}
\listoffigures
\listoftables
\begin{figure}[h]
\caption{A figure}
\centering xyz
\end{figure}
\lipsum[1-1]
\begin{table}[h]
\caption{Some table}
\centering abc
\end{table}
\end{document}
Is it possible to have equal spacing on both tables and figures?
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Browse other questions tagged or ask your own question. | __label__pos | 0.999997 |
Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.
The point of this question is not to debate the merits of this over any other sorting algorithm - certainly there are many other questions that do this. This question is about the name. Why is Quicksort called "Quicksort"? Sure, it's "quick", most of the time, but not always. The possibility of degenerating to O(N^2) is well known. There are various modifications to Quicksort that mitigate this problem, but the ones which bring the worst case down to a guaranteed O(n log n) aren't generally called Quicksort anymore. (e.g. Introsort).
I just wonder why of all the well-known sorting algorithms, this is the only one deserving of the name "quick", which describes not how the algorithm works, but how fast it (usually) is. Mergesort is called that because it merges the data. Heapsort is called that because it uses a heap. Introsort gets its name from "Introspective", since it monitors its own performance to decide when to switch from Quicksort to Heapsort. Similarly for all the slower ones - Bubblesort, Insertion sort, Selection sort, etc. They're all named for how they work. The only other exception I can think of is "Bogosort", which is really just a joke that nobody ever actually uses in practice. Why isn't Quicksort called something more descriptive, like "Partition sort" or "Pivot sort", which describe what it actually does? It's not even a case of "got here first". Mergesort was developed 15 years before Quicksort. (1945 and 1960 respectively according to Wikipedia)
I guess this is really more of a history question than a programming one. I'm just curious how it got the name - was it just good marketing?
share|improve this question
1
Timsort, which is improved quicksort, does not take name after how it works, but rather from it's inventor. Names like flashsort or introsort don't tell you much about algorithm either. – vartec Jun 28 '13 at 14:23
What's in a name? that which we call a rose By any other name would smell as sweet; That or be just as fast. Besides, the possibility of degenerating to O(N^2) has a small chance of happening, and N LogN is pretty good for an algorithm, despite the fact that we have faster algorithms today. Besides, by the time something faster came up, it was too late, everyone already called it Quicksort! – Ampt Jun 28 '13 at 14:33
1
@vartec Timsort is actually derived from Mergesort, not Quicksort, but I'll agree, that's another exception. Introsort doesn't give you the whole algorithm, but it at least describes something of how it works - it's "introspective". Flashsort I'm not very familiar with, but I guess it's called that because it "flashes" each element into its best guess of where it should be? – Darrel Hoffman Jun 28 '13 at 14:37
1
@Ampt Actually, in Quicksort's most basic form, the O(N^2) case is quite likely in the common case where the data is already sorted or nearly so. Admittedly, later developments such as Median-of-3 or random pivot make it far more rare, but the name is still used for implementations which lack such improvements. – Darrel Hoffman Jun 28 '13 at 14:42
Apparently, it's better than Quickest ? – JeffO Jun 28 '13 at 18:42
add comment
3 Answers
up vote 10 down vote accepted
In 1962 research on sorting algorithms wasn't as far advanced as today and the computer scientist Tony Hoare found a new algorithm which was quicker than the other so he published a paper called Quicksort and as the paper was quoted the title stayed.
Quoting the abstract:
A description is given of a new method of sorting in the random-access store of a computer. The method compares very favourably with other known methods in speed, in economy of storage, and in ease of programming. Certain refinements of the method, which may be useful in the optimization of inner loops, are described in the second part of the paper.
share|improve this answer
Footnote on page 11 in the linked PDF suggests there was an earlier paper on Quicksort published in 1961. That paper is also mentioned in the References section at the end of the paper. – FrustratedWithFormsDesigner Jun 28 '13 at 14:37
1961, Algorythm 64 : Quicksort – Pieter B Jun 28 '13 at 14:40
I guess this is as close to the correct answer as I'm likely to get. It explains who named it, but not why it's still using that name, when more recent and potentially quicker alternatives exist. Good read - it's interesting to see how much stuff from back in the 60's still applies to modern technology. – Darrel Hoffman Jun 30 '13 at 1:46
@DarrelHoffman Why would the name change? At what point would the drawbacks of calling the algorithm Quicksort outweigh the cost of trying to get everyone to call it PartitionSort or whatever? – prosfilaes Feb 4 at 3:36
add comment
I believe it's because, at the time it was invented, it was very much quicker than all (or, rather, most, as speed also depends heavily on the kind of data and in some cases other algorithm become much faster than quicksort) of the algorithms out there.
So yes, it's historical (I don't know precisely that history, however...)
But I agree that its name should instead contain a hint of the algorithm...
share|improve this answer
add comment
I believe that it was originally called Hoare Sort after the inventor but the name got changed fairly early due to Hoare sounding a little to close to whore in English. As to why they chose "quick" instead of something else, I'm not sure.
share|improve this answer
add comment
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.854493 |
Easy Steps To Add Seconds To Iphone Clock – Master Your Time
Quick Answer: To add seconds to your iPhone clock, you can enable the “Show seconds” option in the Clock settings.
Have you ever wished you could see the seconds ticking away on your iPhone clock? Whether you’re timing something important or simply want to have a more precise understanding of time, adding seconds to your iPhone clock can be a useful feature. While the default clock display on iPhones only shows hours and minutes, there is a simple way to enable seconds visibility. In this article, we will guide you through the steps to add seconds to your iPhone clock in just a few easy taps. So, without further ado, let’s dive in and unlock this hidden feature on your device.
Easy Steps to Add Seconds to iPhone Clock - Master Your Time
How to Add Seconds to iPhone Clock: A Comprehensive Guide
Have you ever wondered why the iPhone clock doesn’t display seconds? It’s a common frustration for many iPhone users who rely on their devices to keep track of time accurately. Fortunately, there are solutions available to add seconds to your iPhone clock, allowing you to have a more precise understanding of time. In this article, we will explore different methods to achieve this and help you unlock the hidden potential of your iPhone clock.
Why Doesn’t the iPhone Clock Show Seconds?
Before we dive into the solutions, let’s take a moment to understand why Apple decided not to display seconds on the iPhone clock by default. While Apple has always been known for its sleek and minimalistic design, the exclusion of seconds from the clock may have been a deliberate choice to create a clutter-free interface. Additionally, displaying seconds continuously can consume more battery life, which might not be ideal for every user.
Read also Simple Guide: Adding Subtitles To Iphone Videos
However, if you find yourself needing or simply wanting to see the seconds on your iPhone clock, don’t worry. We have some simple methods to help you achieve this.
Method 1: Use a Third-Party Clock App
One of the easiest ways to add seconds to your iPhone clock is by using a third-party clock app. There are numerous clock apps available on the App Store that offer customizable options, including the ability to display seconds. Here’s how you can find and install a third-party clock app:
1. Open the App Store on your iPhone.
2. Tap on the search icon and type “clock app” in the search bar.
3. Browse through the results and choose a clock app that suits your preferences.
4. Tap on “Get” or the price button to download and install the app.
5. Once installed, open the clock app and customize it to display seconds on your iPhone.
Using a third-party clock app not only allows you to add seconds to your iPhone clock but also provides additional features such as different clock faces, alarms, and timers.
Method 2: Enable the World Clock Widget
Another method to add seconds to your iPhone clock is by enabling the World Clock widget. This widget can be accessed from the Today View, which is accessible by swiping right on your iPhone’s home screen or lock screen. Follow these steps to enable the World Clock widget:
1. Swipe right on your iPhone’s home screen or lock screen to access the Today View.
2. Scroll down to the bottom and tap on the “Edit” button.
3. Locate the “World Clock” widget and tap on the green “+” icon next to it.
4. Tap “Done” to save the changes.
5. Now, swipe back to the Today View, and you will see the World Clock widget displaying the time in different cities, including the seconds.
Read also How To Block Temu Ads On Iphone: Step-By-Step Guide
Enabling the World Clock widget provides a convenient way to access the time with seconds on your iPhone without the need to open a separate app.
Method 3: Jailbreak Your iPhone
For advanced users who want complete control over their iPhone’s interface, jailbreaking is an option worth considering. Jailbreaking your iPhone allows you to bypass Apple’s restrictions and customize various aspects of your device, including the clock display. However, please note that jailbreaking your iPhone can void its warranty and may have security implications. Proceed with caution and understand the risks involved before deciding to jailbreak your device.
If you are comfortable with the concept of jailbreaking and have already done so, you can find tweaks and modifications in the Cydia app store that enable you to add seconds to your iPhone clock. These tweaks often provide extensive customization options, allowing you to personalize your iPhone clock according to your preferences.
While the default iPhone clock doesn’t display seconds, there are several methods available to add this feature to your device. Whether you choose to use a third-party clock app, enable the World Clock widget, or venture into jailbreaking, you can now have the precision of seconds on your iPhone clock. Remember to consider the pros and cons of each method and choose the one that best suits your needs.
With these simple techniques, you can transform your iPhone clock into a valuable tool that not only keeps you punctual but also provides accurate time down to the seconds. Enhance your timekeeping experience and make the most out of your iPhone’s capabilities by adding seconds to your clock today. Explore the options, experiment with different methods, and find the one that elevates your iPhone clock to a new level of accuracy and convenience.
Remember, time is precious, and now you have the power to master it with your iPhone clock!
How to Show Analog Clock on iPhone and Edit it
Frequently Asked Questions
How can I add seconds to my iPhone clock?
To add seconds to your iPhone clock, follow these steps:
1. Can I add seconds to the clock on the iPhone home screen?
No, unfortunately, the clock on the iPhone home screen does not display seconds. It only shows the hour and minute.
Read also Master The Art: How To View Sd Card On Iphone
2. Is there a way to view seconds on the iPhone clock?
Yes, if you open the Clock app on your iPhone, you can see the current time with seconds displayed. Simply tap on the Clock app icon on your home screen to access it.
3. Are there any third-party apps available to add seconds to the iPhone clock?
Yes, there are several third-party clock apps available on the App Store that can display seconds on your iPhone’s clock. You can search for “clock with seconds” in the App Store and choose from the various options available.
4. Can I customize the clock face and include seconds?
No, Apple does not currently offer customizable clock faces on the iPhone that include seconds. The clock face is standardized across all iPhones and does not allow for seconds to be displayed.
5. Does adding seconds to the iPhone clock affect battery life?
No, adding seconds to the iPhone clock does not significantly affect battery life. The clock function itself is minimal in terms of power consumption, and displaying seconds on the clock does not have a noticeable impact on battery performance.
6. Can I add seconds to the Lock screen clock?
No, the Lock screen clock on the iPhone also does not display seconds. It only shows the hour and minute, similar to the clock on the home screen. To view the seconds, you need to open the Clock app on your iPhone.
Final Thoughts
To add seconds to your iPhone clock, follow these steps. Open the Settings app and tap on “General.” Scroll down and select “Date & Time.” Toggle off the “Set Automatically” option and tap on “Time Zone.” Adjust the time by scrolling through the numbers or typing the specific time you desire, ensuring to add the seconds as well. Once done, exit the Settings app, and your iPhone clock will display seconds alongside the time. Now, you can easily keep track of the seconds on your iPhone clock.
Leave a Comment | __label__pos | 0.879689 |
Can anyone provide me math homework help service?
In this article, you will learn about essential tools by which you can easily solve mathematical problems like fractions and factors.
Math is one of the hardest subjects that often give students a hard time in their course years. It has been seen that almost every students who are studying math in the esteemed universities also require a helping hand. This helps them by reducing their stress and also ensuring that the work provided by them earns them high marks. The main reason behind students asking math homework help from experts is because solving mathematical problems require a wide number of analytical knowledge, in depth understanding of the subjects as well as gaining knowledge about the methods by which problems are solved. Expert help is also required as they help the students to learn proper time management skills so that they can complete the problems within time and also submit the work within stringent deadlines. Solving fractions and converting them ino decimas is also quite hard while doing the homework.
Often it is seen that students have to attend regular classes in order to listen to the lectures provided by professors. They also have to meet all academic obligations like completing the homework, attend seminars, workshops and many discussion forums. After all these, it becomes difficult for the students to give time for completing their assignments given by the universities where they have to solve intricate mathematical problems. Therefore experts are present who provide math homework help to the students so that they cannot only submit the work on time but at the same time also provide them the chance to gain good marks due to its higher quality. With our fraction calculator tool, you can solve the difficult fractions and convert them into decimals easily and quickly.
Students who are pursuing an academic degree in mathematics always have to be on his toes as they have to deal with a huge burden of assignment tasks. It is found that it becomes quite challenging for the students to handle this huge pressure and at the same time aim for getting excellent results in the assignments. Such pressures and tension may make the students lose his enthusiasm from the subject and his confidence level may fall down. They also face quite difficult time while solving their factoring queries. Hence, in such situations, experts provide great help to the student helping them to deal with mathematical assignment problems. We offer a Quadratic Factoring Calculator by which you can easily factorize any algebric equation and submit your assignments before the due date. This factoring calculator is the perfect solution to factorize any mahematical algebric equations quickly. Experts are also very careful about the requirement of the math assignment which are provide to students by the universities. They only start helping the students when they are confident about what the universities want from the students. Experts help the students by customizing the steps of the problems following the academic requirements which are provided by professors and universities. Therefore from the experts should expect tailor made solutions which reflect the capability of the student to fulfill stringent academic requirements. They also make sure that the work gets completed within assigned deadlines so that penalties are never imposed on the student’s works.
Different types of math assignment may be provided by the universities which are quite difficult for the students. The assignments may be based on important domains which may include abstract algebra, analytic geometry, algorithms, calculus, and linear algebra topology, trigonometry, real analysis, set theory and many others. Different experts are of different backgrounds and hence, they are able to provide the best quality assignments to the students. They also deliver their work within time which in turn helps the students to submit the work in time of the deadlines. With this, it becomes possible for the student to gain high marks in the assignment thereby ensuring good opportunities for future. If you also need to write articles or blogs in your assignments then you can use our plagiarism checker tool to ensure that the content is fresh and doesn’t contain any plagiarism.
You can also rephrase your written blogs and articles to use them again with our accurate paraphrasing tool.
Time management had been one of the most important concerns of the students. They have to attend classes, lectures, do homework, attend seminars, participate in conferences, and attend discussion forums and others. All these are making them not only stressed by draining energy but also providing them with very few amount of time in hands. Therefore, they cannot complete their work on time and have to take the help of the experts. Experts are highly responsible. They not only help the student by providing him strategies for time management but also help them to learn about how to structure the assignments, the extra initiatives that that he could take to make the professors happier and similar others. The work which is provided by the experts is free from plagiarism and also at the same time high in quality.
Summary
Completing assignments are an integral part of contemporary education system. But majority of the students become reluctant when it comes to completing any assignment provided by the university. They can take help from experts. Reasons why they should consult online tutors are discussed in this article. With the advanced tools like fraction calculator, factoring calculator, plagiarism checker, paraphrasing tool, the students can easily solve their assignment problems and can submist the assignments before the deadline.
Ref: https://www.opinionstage.com/ethan-taylor/can-anyone-provide-me-math-homework-help-service
Ethan Taylor
6 Blog posts
Comments | __label__pos | 0.748996 |
v0.34:Z-axis
From Dwarf Fortress Wiki
Jump to: navigation, search
This article is about an older version of DF.
(If you're looking for information on the z key, see Status screen)
The third axis is known in math as the z-axis. It measures "up and down" distances. A z-level is one layer of the map that can be viewed at a time. Changing z-levels is done with the < (up) and > (down) keys.
Contents
[edit] 3 dimensions
It's easy to think of a graph with an x-axis and a y-axis, right?
In the Dwarf Fortress map view, traveling east or west moves you along the x-axis, and traveling north or south moves you along the y-axis. Traveling higher or deeper moves you along the z-axis.
3 dimensions.png
The z-axis, as you can see, is perpendicular to both the x-axis and the y-axis to create a 3D coordinate system, which is what Dwarf Fortress is based in.
Thus, objects described with only two axes are two-dimensional, whilst objects with depth measured along the z-axis are three-dimensional.
The z-axis is believed to be in part of the game engine that calculates accuracy of weapons based on where dwarves are, how missiles fly, and other similar considerations.Verify
To move up and down, use < and > (which are shift, and shift. in most keyboard layouts). You can also move up and down using the numpad with shift5 and ctrl5, which is especially convenient for players who use the numpad for horizontal navigation.
[edit] Keeping track of where you are
In fortress mode, the right-hand margin shows your location on the z-axis. Blue is above ground, brown is below ground, and the bright spot in the middle (yellow or cyan) shows the current level. This reflects the elevation profile for the spot the cursor is currently over. Moving up or down will not change the position of the bright marker, but will instead shift the whole bar under it. The number at the top shows how many levels above or below the surface the spot currently is. The number at the bottom is the elevation of the current level relative to the world's lowest ocean depth.
The top number (red or green) represents the number of z-levels away from ground level at the center of the screen. If there are mountains, or any form of uneven terrain on your map, these numbers will vary in the same z-level. There isn't a currently a way around this. To view the z-level at a certain point, look often works (although it can be a bit unreliable with hills). This is useful for viewing the z-level near the map edge, which can't be centered on.
[edit] Boundaries between layers
There are effectively two parts to z-layers - the layer itself (the z-level where stuff happens, things exist and dwarfs work), and the boundary* between those layers/levels. These "boundaries" are just that - boundaries - they have no thickness, dwarfs and items are never found there, and nothing ever happens there - but they act as barriers between adjacent layers. Boundaries are also referred to as "floor tiles" (not to be confused with floors).
(* The word "boundary" is not an in-game term. You will never see a boundary, only see the effects when one is pierced, giving access, desired or undesired, between levels. You can think of the "boundary" as the "floor", but that's not perfectly accurate in all situations - but close enough to start.)
So you have something like this...
Level 0
__________
LEVEL-1 __________
LEVEL-2 __________
LEVEL-3 __________
(etc...)
...where each line is the boundary between the level above and below it.
The barrier is invisible - you only see the different layers. But once pierced, creatures and items can move/fall through a boundary, and miasma and fluids can pass through as well. With some actions, you remove just a layer, and with some you also pierce the boundary.
Mining is simply tunneling - you dig out the stuff of the level itself, and never touch the upper or lower boundary. Tunnels, rooms, and even up stairs exist on single z-levels. (Downstairs or up/down stairs pierce the lower boundary.)
When you dig a ramp, you pierce the barrier above you into the z-level above the level you are on. (The ramp is on the lower level only, but is also visible from the upper.)
When you dig a down-stair or a channel, you pierce the barrier below the level you are on. (Note that an upstairs does not (usually) pierce the layer above it, but requires a down-stair to pierce the boundary above it to provide a path between levels.
Boundaries also act as "support" for building, constructions, and natural formations above them. If you completely channel out around something, and there is no "layer" supporting it either from above or below, it will collapse.
In open space, the boundaries have already been removed. Constructions, such as floors or walls can replace boundaries between levels, re-sealing them.
See also:
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
Advertisement | __label__pos | 0.854338 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.