小编wes*_*ton的帖子

创建单元测试以确保不变性

我设计了一个不可变类,因为我希望它具有值语义.我在课堂的评论部分写了一个提示

// "This class is immutable, don't change this when adding new features to it."

但我知道,有时这些评论会被其他团队成员忽略,所以我想创建一个单元测试作为额外的保护措施.知道怎么做到这一点?可以通过反射检查一个类,以确保只有构造函数改变它的内部状态吗?

(使用C#2.0和NUnit,如果这对任何人都很重要).

c# nunit unit-testing immutability

6
推荐指数
2
解决办法
1032
查看次数

散列码非零初始值 - 注意:我不是在问素数

这是一个学术观点,但我觉得如果我不理解为什么这会被诸如Effective Java和许多SO问题这样的书推荐,我不完全理解哈希码.

假设:

public sealed class Point
{
    private readonly int x;
    private readonly int y;

    //constructor ommited

    //equals ommited

    public override int GetHashcode()
    {
       int hash = 17; //why should the initial value be non-zero?
       unchecked
       {
         hash = hash * 31 + x; //do not tell me why I should use primes - that is not the question
         hash = hash * 31 + y;
         return hash;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,据推测,初始值的原因是它减少了其中一个组件为零的冲突.

我很想找到任何有帮助的例子.

这是一个碰撞的例子,但是初始值没有任何可能性.

x   y   Hash Without initial …
Run Code Online (Sandbox Code Playgroud)

c# java algorithm hash gethashcode

5
推荐指数
1
解决办法
437
查看次数

android:required ="false"对于使用权限是什么意思?

我正在集成SDK,它需要我把它:

<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION"
    android:required="false" />
Run Code Online (Sandbox Code Playgroud)

我理解android:required="false"uses-feature,但我无法理解许可的含义.它未在文档中列为属性.

它是类似于requires一个uses-feature?如果权限意味着此处列出的功能,那么这些功能不是必需的吗?

android android-manifest

5
推荐指数
2
解决办法
2736
查看次数

如何从C#中的串口读取字节数组

我的 C# 串口编程有问题,
我的目标是将 ByteArray 发送到串口,而不是作为 ByteArray。但我无法从串口获取。我试过:

string gelen = port.ReadExisting();
   int asd = port.ReadByte();
   string qwe = port.ReadLine();
Run Code Online (Sandbox Code Playgroud)

谁能告诉我出了什么问题?谢谢

我的代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO.Ports;

    namespace serial_port_app
    {

        public partial class Form1 : Form
        {

            public Form1()
            {       
                InitializeComponent();

            }

            private void button1_Click(object sender, EventArgs e)
            {

                int text1, text2,text3,text4,text5, text6;

                Int32.TryParse(textBox1.Text, out text1);
                byte byteValue1 = Convert.ToByte(text1);

                Int32.TryParse(textBox2.Text, out text2);
                byte byteValue2 = Convert.ToByte(text2);

                Int32.TryParse(textBox3.Text, …
Run Code Online (Sandbox Code Playgroud)

c# serial-port bytearray

5
推荐指数
1
解决办法
3万
查看次数

如何计算给定高度和压力的海平面压力

我正在写一个显示高度的表盘。高度是用 计算的SensorManager.getAltitude(seaLevelPressure, currentPresure)

但是为了初始化它,我需要海平面的压力。不幸的是没有SensorManager.getSeaLevelPressure(currentPressure,currentAltitude)

为此,我找到了以下公式(参见http://rechneronline.de/barometer/

private float calcSeaPressure(float pressure, int altitude) {
  float temperature = 9 + 273.15f;
  float tempGradient = 0.0065f;

  float v3 = temperature + tempGradient * altitude;
  float sealevelPressure = (float) (pressure / Math.pow((1 - tempGradient * altitude / v3), .03416f / tempGradient));
  sealevelPressure = (float) Math.round(sealevelPressure * 100) / 100;
  return sealevelPressure;
}
Run Code Online (Sandbox Code Playgroud)

但是这个算法和 SensorManager.getAltitude 中使用的算法似乎不太适合。如果我做:

public void setCurrentAltitude(int currentAltitude) {
  sealLevelPressure = calcSealevel(currentAltitude,currentPresure);
  altitude = SensorManager.getAltitude(seaLevelPressure, currentPresure)
}
Run Code Online (Sandbox Code Playgroud)

计算出的高度与给定的 …

java android wear-os

5
推荐指数
1
解决办法
1855
查看次数

比较文化区域而不从 LCID 创建 RegionInfo

为了列出给定区域的适用文化,这是我当前的代码:

public IEnumerable<CultureInfo> ForRegion(RegionInfo regionInfo)
{
     return CultureInfo.GetCultures(CultureTypes.SpecificCultures)
          .Where(c => Equals(new RegionInfo(c.LCID), regionInfo));
}
Run Code Online (Sandbox Code Playgroud)

但我不喜欢必须RegionInfoWhere.

我真的很想做这样的事情:

public IEnumerable<CultureInfo> ForRegion(RegionInfo regionInfo)
{
     return CultureInfo.GetCultures(CultureTypes.SpecificCultures)
          .Where(c => c.LCID == regionInfo.LCID);
}
Run Code Online (Sandbox Code Playgroud)

但因为没有,LCID所以RegionInfo我不能。除了更好的解决方案之外,了解为什么 aRegionInfo没有LCID.

测试示例:

[TestMethod]
public void Can_find_all_by_region_ES_valencia()
{
    var regionInfo = new RegionInfo(new CultureInfo("ca-ES-valencia").LCID);
    List<CultureInfo> found = ForRegion(regionInfo).ToList();
    Assert.AreEqual(5, found.Count);
    CollectionAssert.AreEqual(
        new[]
        {
            new CultureInfo("ca-ES"),
            new CultureInfo("ca-ES-valencia"), //missing with Jon's solution
            new CultureInfo("es-ES"),
            new CultureInfo("eu-ES"),
            new CultureInfo("gl-ES")
        },
        found); …
Run Code Online (Sandbox Code Playgroud)

c# cultureinfo

5
推荐指数
1
解决办法
687
查看次数

gzipstream 内存流到文件

我正在尝试使用 Gzip 压缩来压缩 JSON 文件以发送到另一个位置。它每天需要处理 5,000 - 10,000 个文件,我不需要本地机器上的文件的压缩版本(它们实际上被传输到 AWS S3 进行长期存档)。

由于我不需要它们,我试图压缩到内存流,然后使用它写入 AWS,而不是将每个压缩到磁盘。每当我尝试这样做时,文件都会损坏(例如,当我在 7-Zip 中打开它们并尝试打开其中的 JSON 文件时,我收到“数据错误文件已损坏”)。

当我尝试将内存流写入本地文件时会发生同样的事情,所以我现在正在尝试解决这个问题。这是代码:

string[] files = Directory.GetFiles(@"C:\JSON_Logs");

foreach(string file in files)
{
    FileInfo fileToCompress = new FileInfo(file);
    using (FileStream originalFileStream = fileToCompress.OpenRead())
    {
        using (MemoryStream compressedMemStream = new MemoryStream())
        {
            using (GZipStream compressionStream = new GZipStream(compressedMemStream, CompressionMode.Compress))
            {
                originalFileStream.CopyTo(compressionStream);
                compressedMemStream.Seek(0, SeekOrigin.Begin);
                FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz");

                //Eventually this will be the AWS transfer, but that's not important here
                compressedMemStream.WriteTo(compressedFileStream); 
            }
        }
    }      
}
Run Code Online (Sandbox Code Playgroud)

c# memorystream filestream gzipstream

5
推荐指数
1
解决办法
4581
查看次数

发送没有转义字符的嵌套 JSON 对象

我正在尝试使用 JSONObjectRequest 将嵌套的 JSONObject 发送到服务器。服务器需要以下形式的 JSONObject:

{  
   "commit":"Sign In",
   "user":{  
      "login":"my username",
      "password":"mypassword"
   }
}
Run Code Online (Sandbox Code Playgroud)

但目前我的程序正在通过以下 ( jsonObject.tostring())

{  
   "commit":"Sign In",
   "user":"   {  
      \"login\”:\”myusername\”,
      \”password\”:\”mypassword\”
   }   ”
}
Run Code Online (Sandbox Code Playgroud)

JSONObjects 是由:

final JSONObject loginRequestJSONObject = new JSONObject();
final JSONObject userJSONObject = new JSONObject();
userJSONObject.put("login", "myuser");
userJSONObject.put("password", "mypass");

loginRequestJSONObject.put("user", userJSONObject);
loginRequestJSONObject.put("commit", "Sign In");
Map<String, String> paramsForJSON = new HashMap<String, String>();
paramsForJSON.put("user", userJSONObject.toString().replaceAll("\\\\", "");
paramsForJSON.put("commit", "Sign In");
JSONObject objectToSend =  new JSONObject(paramsForJSON);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, objectToSend,...)
Run Code Online (Sandbox Code Playgroud)

如何以上面的形式发送 JSONObject?

java android json android-volley

5
推荐指数
1
解决办法
3892
查看次数

Android Kotlin Extension超级调用

我是Java Android开发人员,我正在接近Kotlin

我已经定义了以下类:

open class Player : RealmObject() {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我定义了以下两个扩展,一个用于通用的RealmObject类,另一个用于特定的Player类:

fun RealmObject.store() {
    Realm.getDefaultInstance().use { realm ->
        realm.beginTransaction()
        realm.copyToRealmOrUpdate(this)
        realm.commitTransaction()
    }
}

fun Player.store(){
    this.loggedAt = Date()
    (this as RealmObject).store()
}
Run Code Online (Sandbox Code Playgroud)

我想要的是如果我调用.store()任何RealmObject对象,RelamObject.store()扩展名将被调用但是如果我.store()在一个Player实例上调用将被调用的扩展名Player.store().(现在没问题)我不想复制粘贴相同的代码,我喜欢写更少的重用更多.所以我需要在内部Player.store()调用泛型RealmObject.store()

我知道了.我在那里写的代码实际上按预期工作:D

我要问的是(仅仅因为我是通过个人直觉写的):

这是好方法吗?!还是有更好的方法?

谢谢

super kotlin kotlin-extension kotlin-android-extensions

5
推荐指数
1
解决办法
333
查看次数

为每条记录重复一个复杂的布局

我有一个查询数据库并获取记录集的应用程序,在显示器上,我需要使用一个复杂布局的行来呈现这些数据.每行包含一些ImageView,许多TextView等...

以编程方式创建行布局真的很困难,有没有办法从xml中获取整个行布局(行布局的容器和子行),编辑一些属性(如行布局的TextViews)并添加结果为LinearLayout?

xml layout android

4
推荐指数
1
解决办法
5925
查看次数