Need help changing a reserved word boolean into a HashSet - hashset

I have this code in a reserved word boolean format:
private boolean isIdent(String t) {
if (equals(t, "final") || equals(t, "int") || equals(t, "while")
|| equals(t, "if") || equals(t, "else") || equals(t, "print")) return false;
if (t!=null && t.length() > 0 && Character.isLetter(t.charAt(0))) return true;
else return false;
}
I need to turn this into a HashSet format but unsure how to approach this. Any help would be most appreciated.

You mean by putting the reserved words in a Set?
private Set<String> keywords;
private void initKeywords() {
keywords = new HashSet<String>();
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}
private boolean isIdent(String t) {
if (keywords.contains(t)) {
return false;
}
else if (t != null && t.length() > 0 && Character.isLetter(t.charAt(0))) {
return true;
}
else {
return false;
}
}

Related

How do I repeat an action in c# to fix the jumping mechanism

I'm creating a basic 2D platformer game however the jumping mechanism will only run once and land directly afterwards. How do I loop this?
I tried detection collisions (from tag: Terrain) and this does help a lot however it's still not working correctly.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
private Rigidbody2D rb2D;
private Vector2 velocity;
Vector2 xvelocity = new Vector2(10, 0);
Vector2 yvelocity = new Vector2(0, 10);
public float jumptime;
bool grounded = true;
bool jump = false;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetButton("Jump"))
{
jump = true;
}
}
private void FixedUpdate()
{
//Debug.Log(Input.GetAxisRaw("Vertical"));
if (left == true)
{
//Debug.Log("Left");
rb2D.MovePosition(rb2D.position + -xvelocity * Time.fixedDeltaTime);
}
if (right == true)
{
//Debug.Log("Right");
rb2D.MovePosition(rb2D.position + xvelocity * Time.fixedDeltaTime);
}
//if (jump == true && grounded == true)
//{
// jumptime -= Time.fixedDeltaTime;
// if (jumptime > 0)
// {
// rb2D.MovePosition(rb2D.position + yvelocity * Time.fixedDeltaTime);
// }
// if (jumptime <= 0)
// {
// jump = false;
// jumptime = 2;
// }
if (jump == true && grounded == true && jumptime > 0)
{
jumptime -= Time.fixedDeltaTime;
rb2D.MovePosition(rb2D.position + yvelocity * Time.fixedDeltaTime);
} else if (jumptime <= 0)
{
jump = false;
jumptime = 2f;
}
//if (Time.fixedDeltaTime >= 2)
//{
// jump = false;
// rb2D.MovePosition(rb2D.position + -yvelocity * Time.fixedDeltaTime);
//}
}
void OnCollisionExit2D(Collision2D other)
{
Debug.Log("No longer in contact with " + other.transform.name);
jump = true;
grounded = false;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Terrain")
{
Debug.Log("Landed");
jump = false;
grounded = true;
}
}
}
The expected outcome is that the action 'jump' will loop for ~1/1.5 seconds with a good height (vector2 yvelocity) so it will jump higher and will come down afterwards (thanks to the gravity from the Rigidbody (2D))
As stated in the comments I think the main issue is coming from this line of code.
if (jump == true && grounded == true && jumptime > 0)
It is much likely that one of those bool is not what you expect it to be. Anyway I suggest you to convert the line like so:
if (jump && grounded && jumptime > 0)
You do not need == true for booleans.
Anyway, to solve your question in an easier way, I would suggest you to use AddForce instead of move (because you're using a rigibody2d anyway).
rb2D.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
A small note about horizontal velocity. If you're using a rigibody it would be better to move it with the same rigidbody and not with the transform:
rb2D.MovePosition(rb2D.position + Vector2.left * xspeed * Time.fixedDeltaTime);
Your code will become:
public class PlayerController2D : MonoBehaviour
{
private Rigidbody2D rb2D;
private Vector2 velocity;
public float jumpForce = 5;
bool grounded = true;
void Start() { rb2D = GetComponent<Rigidbody2D>(); }
void Update()
{
if (Input.GetButton("Jump") && grounded)
rb2D.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
//calculate horizontal speed here
xspeed = ...;
}
private void FixedUpdate()
{
rb2D.MovePosition(rb2D.position + Vector2.left * xspeed * Time.fixedDeltaTime);
}
void OnCollisionExit2D(Collision2D other)
{
Debug.Log("No longer in contact with " + other.transform.name);
grounded = false;
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Terrain")
{
Debug.Log("Landed");
grounded = true;
}
}
}

Equivalent of angular.equals in angular2

I am working on migration of angular 1 project to angular 2 . In angular 1 project I was using angular.equals for object comparison angular.equals($ctrl.obj1, $ctrl.newObj); , I searched online for equivalent method in angular 2 but could not find any matching result.
#Günter Yes you are right there is no equivalent in angular2 . While searching more I found third party library lodash which will do same job as angular.equals and syntax is same as angular one and this library solves my problem
Code example from lodash documentation
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
I rewrote Ariels answer (thank you!) to be TSLINT-friendly. You can also save some continues by using else if, but I think this is more clear. Maybe someone else needs it too:
export function deepEquals(x, y) {
if (x === y) {
return true; // if both x and y are null or undefined and exactly the same
} else if (!(x instanceof Object) || !(y instanceof Object)) {
return false; // if they are not strictly equal, they both need to be Objects
} else if (x.constructor !== y.constructor) {
// they must have the exact same prototype chain, the closest we can do is
// test their constructor.
return false;
} else {
for (const p in x) {
if (!x.hasOwnProperty(p)) {
continue; // other properties were tested using x.constructor === y.constructor
}
if (!y.hasOwnProperty(p)) {
return false; // allows to compare x[ p ] and y[ p ] when set to undefined
}
if (x[p] === y[p]) {
continue; // if they have the same strict value or identity then they are equal
}
if (typeof (x[p]) !== 'object') {
return false; // Numbers, Strings, Functions, Booleans must be strictly equal
}
if (!deepEquals(x[p], y[p])) {
return false;
}
}
for (const p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
return false;
}
}
return true;
}
}
Instead of writing a function to iterate through the objects, you could just use JSON.stringify and compare the two strings?
Example:
var obj1 = {
title: 'title1',
tags: []
}
var obj2 = {
title: 'title1',
tags: ['r']
}
console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));
console.log(JSON.stringify(obj1) === JSON.stringify(obj2));
In Angular 2 you should use pure JavaScript/TypeScript for that so you can add this method to some service
private static equals(x, y) {
if (x === y)
return true;
// if both x and y are null or undefined and exactly the same
if (!(x instanceof Object) || !(y instanceof Object))
return false;
// if they are not strictly equal, they both need to be Objects
if (x.constructor !== y.constructor)
return false;
// they must have the exact same prototype chain, the closest we can do is
// test there constructor.
let p;
for (p in x) {
if (!x.hasOwnProperty(p))
continue;
// other properties were tested using x.constructor === y.constructor
if (!y.hasOwnProperty(p))
return false;
// allows to compare x[ p ] and y[ p ] when set to undefined
if (x[p] === y[p])
continue;
// if they have the same strict value or identity then they are equal
if (typeof (x[p]) !== "object")
return false;
// Numbers, Strings, Functions, Booleans must be strictly equal
if (!RXBox.equals(x[p], y[p]))
return false;
}
for (p in y) {
if (y.hasOwnProperty(p) && !x.hasOwnProperty(p))
return false;
}
return true;
}
You could just copy the original source code from angularjs for the angular.equals function. Usage: equals(obj1, obj2);
var toString = Object.prototype.toString;
function isDefined(value) {return typeof value !== 'undefined';}
function isFunction(value) {return typeof value === 'function';}
function createMap() {
return Object.create(null);
}
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
function isDate(value) {
return toString.call(value) === '[object Date]';
}
function isArray(arr) {
return Array.isArray(arr) || arr instanceof Array;
}
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
// eslint-disable-next-line no-self-compare
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 === t2 && t1 === 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) === o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return simpleCompare(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
if (!isRegExp(o2)) return false;
return o1.toString() === o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
isDefined(o2[key]) &&
!isFunction(o2[key])) return false;
}
return true;
}
}
return false;
}
a = { name: 'me' }
b = { name: 'me' }
a == b // false
a === b // false
JSON.stringify(a) == JSON.stringify(b) // true
JSON.stringify(a) === JSON.stringify(b) // true

BigInteger parsing on Silverlight

I'm actually working on a IBAN key verification function.
To get the key i do something like :
string theKey = (98 - ((int64.Parse(value)) % 97)).ToString();
The problem is that my value is something longer than 19. So i need to use BigInteger from System.Numerics.
This references doesn't include the Parse() method.
I need a solution that would allow me to use 23char integer on Silverlight.
Yep i dont think BigInteger.Parse() is available in silverlight.
You could use Decimal just without a decimal point, as a decimal value can go up to 79,228,162,514,264,337,593,543,950,335.
(29 chars) if i counted correctly..
*Edit - the reason i chose decimal over double is that decimal has more significant figures and can therefore be more precise.
Someone on MSDN gave me a class that comes with Parse/TryParse, it works really good and i hope it'll help. Thanks for the decimal solution though, but it appears that i need to use 30 digits int as well, so biginteger was a must have :
public static class BigIntegerHelper
{
public static BigInteger Parse(string s)
{
return Parse(s, CultureInfo.CurrentCulture);
}
public static BigInteger Parse(string s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, provider);
}
public static BigInteger Parse(string s, NumberStyles style)
{
return Parse(s, style, CultureInfo.CurrentCulture);
}
public static BigInteger Parse(string s, NumberStyles style, IFormatProvider provider)
{
BigInteger result;
if (TryParse(s, style, provider, out result))
{
return result;
}
throw new FormatException();
}
public static bool TryParse(string s, out BigInteger b)
{
return TryParse(s, NumberStyles.Integer, CultureInfo.CurrentCulture, out b);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider formatProvider, out BigInteger value)
{
if (formatProvider == null)
{
formatProvider = CultureInfo.CurrentCulture;
}
if ((style & ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowHexSpecifier)) != NumberStyles.None)
{
throw new NotSupportedException();
}
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)formatProvider.GetFormat(typeof(NumberFormatInfo));
uint num = ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None) ? 16u : 10u;
int num2 = 0;
bool flag = false;
if ((style & NumberStyles.AllowLeadingWhite) != NumberStyles.None)
{
while (num2 < s.Length && IsWhiteSpace(s[num2]))
{
num2++;
}
}
if ((style & NumberStyles.AllowLeadingSign) != NumberStyles.None)
{
int length = numberFormatInfo.NegativeSign.Length;
if (length + num2 < s.Length && string.Compare(s, num2, numberFormatInfo.NegativeSign, 0, length, CultureInfo.CurrentCulture, CompareOptions.None) == 0)
{
flag = true;
num2 += numberFormatInfo.NegativeSign.Length;
}
}
value = BigInteger.Zero;
BigInteger bigInteger = BigInteger.One;
if (num2 == s.Length)
{
return false;
}
for (int i = s.Length - 1; i >= num2; i--)
{
if ((style & NumberStyles.AllowTrailingWhite) != NumberStyles.None && IsWhiteSpace(s[i]))
{
int num3 = i;
while (num3 >= num2 && IsWhiteSpace(s[num3]))
{
num3--;
}
if (num3 < num2)
{
return false;
}
i = num3;
}
uint num4;
if (!ParseSingleDigit(s[i], (ulong)num, out num4))
{
return false;
}
if (num4 != 0u)
{
value += num4 * bigInteger;
}
bigInteger *= num;
}
if (value.Sign == 1 && flag)
{
value = -value;
}
return true;
}
private static bool IsWhiteSpace(char ch)
{
return ch == ' ' || (ch >= '\t' && ch <= '\r');
}
private static bool ParseSingleDigit(char c, ulong radix, out uint result)
{
result = 0;
if (c >= '0' && c <= '9')
{
result = (uint)(c - '0');
return true;
}
if (radix == 16uL)
{
c = (char)((int)c & -33);
if (c >= 'A' && c <= 'F')
{
result = (uint)(c - 'A' + '\n');
return true;
}
}
return false;
}
}

Silverlight4 deep copy visual element

I have a custom visual element and i want to make a deep copy in my silverlight application.
I've tried many things but i didn't find any solution...
Here the best solution that i found but the original DeviceControl and the copy are linked.
If i change a property of one of them, the second also changes. I want them to be independent!
Have you got an idea?
void CloneDevice()
{
DeviceControl control = this;
DeviceControl copy = CloneObject.DeepClone<DeviceControl>(control);
ExtensionMethods.DeepCopy(control, copy);
}
//[Obfuscation(Exclude = true)]
internal static class CloneObject
{
private static bool _firstTry = false;
private static List<FieldInfo> _attachedProperties = null;
// Extension for any class object
internal static TT DeepClone<TT>(this TT source, bool?cloneAttachedProperties = null)
{ // Jim McCurdy's DeepClone
if (cloneAttachedProperties == null)
cloneAttachedProperties = (source is DependencyObject);
// The first time this method is called, compute a list of all
// attached properties that exist in this XAP's assemblies
if (cloneAttachedProperties == true && _attachedProperties == null)
{
_attachedProperties = new List<FieldInfo>();
List<Assembly> assemblies = GetLoadedAssemblies();
foreach (Assembly assembly in assemblies)
GetAttachedProperties(_attachedProperties, assembly);
}
TT clone = CloneRecursive(source);
if (clone is FrameworkElement)
{
FrameworkElement cloneElement = (clone as FrameworkElement);
cloneElement.Arrange(new Rect(0, 0, cloneElement.ActualWidth, cloneElement.ActualHeight));
}
return clone;
}
private static TT CloneRecursive<TT>(TT source)
{
if (source == null || source.GetType().IsValueType)
return source;
// Common types that do not have parameterless constructors
if (source is string || source is Type || source is Uri || source is DependencyProperty)
return source;
TT clone = CloneCreate(source);
if (clone == null)
return source;
if (source is IList)
CloneList(source as IList, clone as IList);
//CloneProperties(source, clone);//ca plante si on prend les propriétées comme ca
return clone;
}
private static TT CloneCreate<TT>(TT source)
{
try
{
#if DEBUG_TRACE
string.Format("Clone create object Type={0}", SimpleType(source.GetType())).Trace();
#endif
Array sourceArray = (source as Array);
if (sourceArray == null)
return (TT)Activator.CreateInstance(source.GetType());
if (sourceArray.Rank == 1)
return (TT)(object)Array.CreateInstance(source.GetType().GetElementType(),
sourceArray.GetLength(0));
if (sourceArray.Rank == 2)
return (TT)(object)Array.CreateInstance(source.GetType().GetElementType(),
sourceArray.GetLength(0), sourceArray.GetLength(1));
}
catch (Exception ex)
{
if (ex.Message.Contains("No parameterless constructor"))
return default(TT);
//string.Format("Can't create object Type={0}", SimpleType(source.GetType())).Trace();
//ex.DebugOutput();
}
return default(TT);
}
private static void CloneProperties(object source, object clone)
{
// The binding flags indicate what properties we will clone
// Unfortunately, we cannot clone "internal" or "protected" properties
BindingFlags flags =
BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.Public;
if (source is DependencyObject)
{
DependencyObject sourcedp = source as DependencyObject;
DependencyObject clonedp = clone as DependencyObject;
// Clone attached properties
if (_attachedProperties != null && _attachedProperties.Count > 0)
foreach (FieldInfo field in _attachedProperties)
CloneDependencyProperty(sourcedp, clonedp, field, true);
// Clone dependency properties
FieldInfo[] fields = source.GetType().GetFields(flags | BindingFlags.Static);
foreach (FieldInfo field in fields)
CloneDependencyProperty(sourcedp, clonedp, field, false);
}
// Clone CLR properties
if (source is DeviceControl && _firstTry == false)
{
_firstTry = true;
PropertyInfo[] properties = source.GetType().GetProperties(flags);
foreach (PropertyInfo property in properties)
CloneProperty(source, clone, property);
}
}
private static void CloneDependencyProperty(DependencyObject sourceObject,
DependencyObject cloneObject, FieldInfo field, bool isAttached)
{
try
{
// Blacklisted properties that can't (or shouldn't) be set
if (field.Name == "NameProperty" && sourceObject is FrameworkElement) return;
DependencyProperty dp = field.GetValue(sourceObject) as DependencyProperty;
if (dp == null) // Event DependencyProperties will be null
return;
object sourceValue = null;
try
{
sourceValue = sourceObject.GetValue(dp);
}
catch (Exception)
{
}
if (sourceValue == null)
return;
// Don't set attached properties if we don't have to
if (isAttached)
{
Type sourceType = sourceValue.GetType();
if (sourceType.IsValueType && sourceValue.Equals(Activator.CreateInstance(sourceType)))
return;
}
#if DEBUG_TRACE
string.Format("Clone dependency property Name={0}, Value={2} for source Type={1}",
field.Name, SimpleType(sourceObject.GetType()), sourceValue).Trace();
#endif
// Blacklisted properties that can't (or don't need to be) cloned
bool doClone = true;
if (field.Name == "DataContextProperty") doClone = false;
//if (field.Name == "TargetPropertyProperty") doClone = false;
object cloneValue = (doClone ? CloneRecursive(sourceValue) : sourceValue);
cloneObject.SetValue(dp, cloneValue);
}
catch (Exception ex)
{
if (ex.Message.Contains("read-only"))
return;
if (ex.Message.Contains("read only"))
return;
if (ex.Message.Contains("does not fall within the expected range"))
return;
//string.Format("Can't clone dependency property Name={0}, for source Type={1}",
// field.Name, SimpleType(sourceObject.GetType())).Trace();
//ex.DebugOutput();
}
}
private static void CloneProperty(object source, object clone, PropertyInfo property)
{
try
{
if (!property.CanRead || !property.CanWrite || property.GetIndexParameters().Length != 0)
return;
// Blacklisted properties that can't (or shouldn't) be set
if (property.Name == "Name" && source is FrameworkElement) return;
if (property.Name == "InputScope" && source is TextBox) return; // Can't get
if (property.Name == "Watermark" && source is TextBox) return; // Can't get
if (property.Name == "Source" && source is ResourceDictionary) return; // Can't set
if (property.Name == "TargetType" && source is ControlTemplate) return; // Can't set
bool publicSetter = (source.GetType().GetMethod("set_" + property.Name) != null);
bool isList = (property.PropertyType.GetInterface("IList", true) != null);
if (!publicSetter && !isList)
return;
object sourceValue = property.GetValue(source, null);
if (sourceValue == null)
return;
if (!publicSetter && isList)
{
IList cloneList = property.GetValue(clone, null) as IList;
if (cloneList != null)
CloneList(sourceValue as IList, cloneList);
return;
}
#if DEBUG_TRACE
string.Format("Clone property Type={0}, Name={1}, Value={3} for source Type={2}",
SimpleType(property.PropertyType), property.Name, SimpleType(source.GetType()),
sourceValue).Trace();
#endif
// Blacklisted properties that can't (or don't need to be) cloned
bool doClone = true;
if (source is FrameworkElement && property.Name == "DataContext") doClone = false;
//if (property.Name == "TargetProperty") doClone = false;
object cloneValue = (doClone ? CloneRecursive(sourceValue) : sourceValue);
property.SetValue(clone, cloneValue, null); // possible MethodAccessException
}
catch (Exception ex)
{
//string.Format("Can't clone property Type={0}, Name={1}, for source Type={2}",
// SimpleType(property.PropertyType), property.Name, SimpleType(source.GetType())).Trace();
//ex.DebugOutput();
}
}
private static void CloneList(IList sourceList, IList cloneList)
{
try
{
IEnumerator sourceEnumerator = sourceList.GetEnumerator();
Array sourceArray = sourceList as Array;
Array cloneArray = cloneList as Array;
int dim0 = (sourceArray != null && sourceArray.Rank > 0 ? sourceArray.GetLowerBound(0) : 0);
int dim1 = (sourceArray != null && sourceArray.Rank > 1 ? sourceArray.GetLowerBound(1) : 0);
while (sourceEnumerator.MoveNext())
{
object sourceValue = sourceEnumerator.Current;
#if DEBUG_TRACE
string.Format("Clone IList item {0}", sourceValue).Trace();
#endif
object cloneValue = CloneRecursive(sourceValue);
if (sourceArray == null)
cloneList.Add(cloneValue);
else
if (sourceArray.Rank == 1)
cloneArray.SetValue(cloneValue, dim0++);
else
if (sourceArray.Rank == 2)
{
cloneArray.SetValue(cloneValue, dim0, dim1);
if (++dim1 > sourceArray.GetUpperBound(1))
{
dim1 = sourceArray.GetLowerBound(1);
if (++dim0 > sourceArray.GetUpperBound(0))
dim0 = sourceArray.GetLowerBound(0);
}
}
}
}
catch (Exception ex)
{
//string.Format("Can't clone IList item Type={0}", SimpleType(sourceList.GetType())).Trace();
//ex.DebugOutput();
}
}
private static string SimpleType(Type type)
{
string typeName = type.ToString();
int index = typeName.LastIndexOf('[');
if (index < 0)
return typeName.Substring(typeName.LastIndexOf('.') + 1);
string collectionName = typeName.Substring(index);
collectionName = collectionName.Substring(collectionName.LastIndexOf('.') + 1);
typeName = typeName.Substring(0, index);
typeName = typeName.Substring(typeName.LastIndexOf('.') + 1);
return typeName + '[' + collectionName;
}
private static List<Assembly> GetLoadedAssemblies()
{
List<Assembly> assemblies = new List<Assembly>();
foreach (AssemblyPart part in Deployment.Current.Parts)
{
StreamResourceInfo sri =
Application.GetResourceStream(new Uri(part.Source, UriKind.Relative));
if (sri == null)
continue;
Assembly assembly = new AssemblyPart().Load(sri.Stream);
if (assembly != null && !assemblies.Contains(assembly))
assemblies.Add(assembly);
}
// Additional assemblies that are not found when examining of Deployment.Current.Parts above
Type[] types =
{
typeof(System.Windows.Application), // System.Windows.dll,
#if INCLUDE_ASSEMBLIES_WITHOUT_ATTACHED_PROPERTIES
typeof(System.Action), // mscorlib.dll,
typeof(System.Uri), // System.dll,
typeof(System.Lazy<int>), // System.Core.dll,
typeof(System.Net.Cookie), // System.Net.dll,
typeof(System.Runtime.Serialization.StreamingContext), // System.Runtime.Serialization.dll,
typeof(System.ServiceModel.XmlSerializerFormatAttribute), // System.ServiceModel.dll,
typeof(System.Windows.Browser.BrowserInformation), // System.Windows.Browser.dll,
typeof(System.Xml.ConformanceLevel), // System.Xml.dll,
#endif
};
foreach (Type type in types)
{
Assembly assembly = type.Assembly;
if (assembly != null && !assemblies.Contains(assembly))
assemblies.Add(assembly);
}
return assemblies;
}
private static bool GetAttachedProperties(List<FieldInfo> attachedProperties, Assembly assembly)
{
BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static;
foreach (Type type in assembly.GetTypes())
{
FieldInfo[] fields = type.GetFields(flags);
MethodInfo[] methods = null;
foreach (FieldInfo field in fields)
{
if (field.FieldType==(typeof(DependencyProperty)))
continue;
if (!field.Name.EndsWith("Property"))
continue;
string fieldName = field.Name.Replace("Property", "");
string getName = "Get" + fieldName;
string setName = "Set" + fieldName;
bool foundGet = false;
bool foundSet = false;
if (methods == null)
methods = type.GetMethods(flags);
foreach (MethodInfo method in methods)
{
if (method.Name == getName && method.GetParameters().Length == 1 &&
method.GetParameters()[0].ParameterType== (typeof(DependencyObject)))
foundGet = true;
else
if (method.Name == setName && method.GetParameters().Length == 2 &&
method.GetParameters()[0].ParameterType==(typeof(DependencyObject)))
foundSet = true;
if (foundGet && foundSet)
break;
}
if (!(foundGet && foundSet))
continue;
try
{
DependencyProperty dp = field.GetValue(null) as DependencyProperty;
}
catch (Exception)
{
continue;
}
// Found an attached Dependency Property
attachedProperties.Add(field);
}
}
return true;
}
}
public static void DeepCopy(object source, object destination)
{
// Get properties
var propertyInfos = source.GetType().GetProperties();
// Evaluate
if (propertyInfos.Length > 0)
{
foreach (var propInfo in propertyInfos)
{
// Process only public properties
if (propInfo.CanWrite)
{
if (propInfo.Name == "IsSelected")
{
break;
}
else
{
object value = propInfo.GetValue(source, null);
propInfo.SetValue(destination, value, null);
// Evaluate
if (value != null)
{
var newPropInfo = value.GetType().GetProperties();
if (newPropInfo.Length > 0)
{
// Copy properties for each child where necessary
DeepCopy(
source.GetType().GetProperty(propInfo.Name),
destination.GetType().GetProperty(propInfo.Name));
}
}
}
}
}
}
}
I solved my issue. I finally used JSon.net library
void CloneDevice()
{
DeviceControl control = this;
string json = JsonConvert.SerializeObject(control, Formatting.Indented);
DeviceControl copy = (DeviceControl)JsonConvert.DeserializeObject(json, this.GetType());
}
Thanks to Olivier Dahan!

wpf richtextbox check if caret is in the last line or count how many lines it has

I am trying to find out in a richtext box whether the caret is position in the last line. Is this possible?
NOTE: At the end I also added: or count how many lines it has, this is because in the miscrosoft forum there is an example for detecting in which line the caret is.
thanks
Please verify the msdn link
http://social.msdn.microsoft.com/Forums/en/wpf/thread/667b5d2a-84c3-4bc0-a6c0-33f9933db07f
If you really wanted to know the line number of the caret, you could do something like the following (probably needs some tweaking):
TextPointer caretLineStart = rtb.CaretPosition.GetLineStartPosition(0);
TextPointer p = rtb.Document.ContentStart.GetLineStartPosition(0);
int caretLineNumber = 1;
while (true)
{
if (caretLineStart.CompareTo(p) < 0)
{
break;
}
int result;
p = p.GetLineStartPosition(1, out result);
if (result == 0)
{
break;
}
caretLineNumber++;
}
The code to get the number of lines:
Int32 CountDisplayedLines(RichTextBox rtb)
{
Int32 result = -1;
rtb.CaretPosition = rtb.Document.ContentStart;
while (rtb.CaretPosition.GetLineStartPosition(++result) != null)
{
}
return result;
}
I have found a solution. Maybe there is a simpler way, if so please let me know
private void OnHasRtbReachedEnd(System.Windows.Controls.RichTextBox rtb)
{
TextPointer pointer1 = rtb.CaretPosition;
int iCurrentLine = GetLineNumber(rtb);
rtb.CaretPosition = rtb.Document.ContentEnd;
int iLastLine = GetLineNumber(rtb);
if (iCurrentLine == iLastLine)
{
if (!_bIsRtbMovingUpDown)
MoveToNextDataGridRow();
_bIsRtbMovingUpDown= false;
}
else
{
_bIsRtbMovingUpDown= true;
}
rtb.CaretPosition = pointer1;
}
//This code comes from
//http://social.msdn.microsoft.com/Forums/en/wpf/thread/667b5d2a-84c3-4bc0-a6c0-33f9933db07f
private int GetLineNumber(System.Windows.Controls.RichTextBox rtb)
{
TextPointer caretLineStart = rtb.CaretPosition.GetLineStartPosition(0);
TextPointer p = rtb.Document.ContentStart.GetLineStartPosition(0);
int caretLineNumber = 1;
while (true)
{
if (caretLineStart.CompareTo(p) < 0)
{
break;
}
int result;
p = p.GetLineStartPosition(1, out result);
if (result == 0)
{
break;
}
caretLineNumber++;
}
return caretLineNumber;
}
I tried the code and is not giving correct results always.
One smart way to do it is this
int previousCursorPosition;
private void RichTarget_KeyDown_1(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up || e.Key == Key.Down)
{
Xceed.Wpf.Toolkit.RichTextBox rich = (Xceed.Wpf.Toolkit.RichTextBox)sender;
previousCursorPosition = rich.CaretPosition.GetOffsetToPosition(rich.CaretPosition.DocumentStart);
}
}
private void RichTextBox_KeyUp_1(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
{
Xceed.Wpf.Toolkit.RichTextBox rich = (Xceed.Wpf.Toolkit.RichTextBox)sender;
if (previousCursorPosition == rich.CaretPosition.GetOffsetToPosition(rich.CaretPosition.DocumentStart))
{
//do your staff
}
}
else if (e.Key == Key.Down)
{
Xceed.Wpf.Toolkit.RichTextBox rich = (Xceed.Wpf.Toolkit.RichTextBox)sender;
if (previousCursorPosition == rich.CaretPosition.GetOffsetToPosition(rich.CaretPosition.DocumentStart))
{
//do your staff
}
}
}

Resources