我将GOPATH设置为
/Users/me/dev/go
我有
/Users/me/dev/go/src/client1
/Users/me/dev/go/src/client2
/Users/me/dev/go/src/client3
并且
/Users/me/dev/client1/rails_project
/Users/me/dev/client2/php_project
etc.
我不喜欢在我的root dev文件夹中如何强制使用这个通用的“ go”目录来保存许多不同客户的go项目。
我正在尝试验证传递的变量是否可以转换为特定类型。 我已经尝试了以下内容,但无法对其进行编译,因此我认为我将以错误的方式进行操作(我是C#的新手)
string myType = "System.Int32";
string myValue = "42";
bool canBeCast = false;
try
{
// try to convert the value to it's intended type to see if it's valid.
var result = (Type.GetType(typeString))dataValue;
canBeCast = true;
}
catch
{
canBeCast = false;
}
我基本上是在尝试避免大规模的switch语句
switch(myType){
case "System.Int32":
try
{
var convertedValue = Convert.ToInt32(myValue);
}
catch (Exception)
{
canBeConverted = false;
}
break;
case "another type":
...
}
编辑:
好的,基本上我有一个已知输入类型的数据库表,如下所示:
CREATE TABLE [dbo].[MetadataTypes] (
[typeName] VARCHAR (50) NOT NULL,
[dataType] VARCHAR (50) NOT NULL,
[typeRegex] VARCHAR (255) NULL
);
其中可能包含诸如
"StartTime","System.DateTime",null
"TicketId","System.String","$[Ff][0-9]{7}^"
输入到我的函数将是一个KeyValuePair类似于
myInput = new KeyValuePair<string,string>("StartTime","31/12/2010 12:00");
我需要检查KeyValuePair的值是否具有MetaDataType期望的正确数据类型。
编辑答案:
Leon非常接近我终于想到的解决方案。
供参考,我的函数现在如下所示:
public Boolean ValidateMetadata(KeyValuePair<string, string> dataItem)
{
// Look for known metadata with name match
MetadataType type = _repository.GetMetadataTypes().SingleOrDefault(t => t.typeName == dataItem.Key);
if (type == null) { return false; }
// Get the data type and try to match to the passed in data item.
Boolean isCorrectType = false;
string typeString = type.dataType;
string dataValue = dataItem.Value;
try
{
var cValue = Convert.ChangeType(dataValue, Type.GetType(typeString));
isCorrectType = true;
}
catch
{
isCorrectType = false;
}
//TODO: Validate against possible regex here....
return isCorrectType;
}
考虑以下代码,这是我的实际问题的SSCCE:
#include <iostream>
int roundtrip(int x)
{
return int(float(x));
}
int main()
{
int a = 2147483583;
int b = 2147483584;
std::cout << a << " -> " << roundtrip(a) << '\n';
std::cout << b << " -> " << roundtrip(b) << '\n';
}
我的计算机(Xubuntu 12.04.3 LTS)上的输出是:
2147483583 -> 2147483520
2147483584 -> -2147483648
请注意,正数b
在往返之后如何以负数结束。 这种行为是否有明确规定? 我本来希望从int到float的往返至少能够正确保留符号...
嗯,在ideone上,输出是不同的:
2147483583 -> 2147483520
2147483584 -> 2147483647
g ++小组是在同时修复了一个错误,还是两个输出都完全有效?
我知道这个问题已经被一遍又一遍地问了,但是我似乎找不到足够好的答案。 因此,为了明确说明我想知道的内容,我将其分为两个问题:
为什么接口不能具有静态方法签名? 我将尝试先回答以下非回答问题:为什么在世界上我想使用以下命令:我希望能够静态调用SqliteCodeGenerator
和MssqlCodeGenerator
上的interface ICodeGenerator
{
// this is the method I would like to be static:
string GetDbConnectionType();
}
abstract class CodeGeneratorBase : ICodeGenerator
{
public abstract string GetDbConnectionType();
public void GenerateSomeCode(StringBuilder s)
{
s.AppendLine("var foo = new " + GetDbConnectionType() + "();");
}
}
class SqliteCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SQLiteConnection";
}
}
class MssqlCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SqlConnection";
}
}
:
interface ICodeGenerator
{
// this is the method I would like to be static:
string GetDbConnectionType();
}
abstract class CodeGeneratorBase : ICodeGenerator
{
public abstract string GetDbConnectionType();
public void GenerateSomeCode(StringBuilder s)
{
s.AppendLine("var foo = new " + GetDbConnectionType() + "();");
}
}
class SqliteCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SQLiteConnection";
}
}
class MssqlCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SqlConnection";
}
}
另一方面,这是第二个问题,如果您知道达到上述目标的好选择,那么无论如何...
考虑:
template <typename T>
class Base
{
public:
static const bool ZEROFILL = true;
static const bool NO_ZEROFILL = false;
}
template <typename T>
class Derived : public Base<T>
{
public:
Derived( bool initZero = NO_ZEROFILL ); // NO_ZEROFILL is not visible
~Derived();
}
我无法使用GCC g ++ 3.4.4(cygwin)进行编译。
在将它们转换为类模板之前,它们是非泛型的,派生类能够查看基类的静态成员。 C ++规范的要求中是否存在这种可见性损失,还是我需要采用语法更改?
我了解到Base<T>
的每个实例都将具有其自己的静态成员“ ZEROFILL
”和“ NO_ZEROFILL
”,即Base<float>::ZEROFILL
和Base<double>::ZEROFILL
是不同的变量,但我并不在乎; 该常量用于代码的可读性。 我想使用静态常量,因为就名称冲突而言,这比使用宏或全局方法更安全。
我在将字符串日期解析为dateFrom
对象时遇到了一些麻烦。 我使用Sun Dec 04 00:00:00 GMT 2011
来解析该字符串,当我打印日期值时,它给出了我期望的结果。
但是,当我尝试获取日期,月份或年份时,会给我错误的值。 例如,那是2011年,但是当我执行dateFrom
时,它会给我111。我不知道为什么会这样。 这是相关的代码段:
Date dateFrom = null;
String gDFString = g.getDateFrom();
System.out.println(gDFString);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
dateFrom = df.parse("04/12/2011");
System.out.println(dateFrom);
System.out.println(dateFrom.getYear());
} catch (ParseException e) {
e.printStackTrace();
}
当我打印dateFrom
时,我得到Sun Dec 04 00:00:00 GMT 2011
,这就是您所期望的。 但是打印.getYear()
返回111
。
我需要能够获取时间序列图的日期,月份和年份。
如果我没有在PHP中捕获异常,则会在我的traceback.format_exc()
文件中获得带有堆栈跟踪的有用错误消息。 例如,如果我运行:
<?php
function foo() {
throw new Exception('Oh no!');
}
foo();
?>
然后将其写入日志:
[2013年3月6日星期三10:35:32] [错误] [客户端86.146.145.175] PHP致命 错误:未捕获的异常“ Exception”,消息为“哦,不!” 在 /var/www/test.php:4\n堆栈跟踪:\ n#0 /var/www/test.php(7): foo()\ n#1 {main} \ n在第4行的/var/www/test.php中抛出
有时我想捕捉异常,但仍然记录该细节。 我在想类似的东西:
<?php
function foo() {
throw new Exception('Oh no!');
}
try {
foo();
} catch (Exception $e) {
log_exception($e);
}
?>
其中traceback.format_exc()
将以与为未捕获的异常自动写入的格式基本相同的格式将某些内容写入错误日志-除了使用Caught exception
而不是PHP Fatal error: Uncaught exception
之外,在字面上可能完全相同。
是否有一个内置函数可以记录这样的异常信息,或将其捕获为字符串? 我正在想象类似于Python中的traceback.format_exc()
的东西。
我正在尝试使用模板类链接到共享库,但这给了我“未定义符号”错误。 我将问题压缩为大约20行代码。
共享的
template <class Type> class myclass {
Type x;
public:
myclass() { x=0; }
void setx(Type y);
Type getx();
};
共享的
#include "shared.h"
template <class Type> void myclass<Type>::setx(Type y) { x = y; }
template <class Type> Type myclass<Type>::getx() { return x; }
main.cpp
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[]) {
myclass<int> m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
return 0;
}
这是我编译库的方式:
g++ -fPIC -c shared.cpp -o shared.o
g++ -dynamiclib -Wl,-dylib_install_name -Wl,libshared.dylib -o libshared.dylib shared.o
和主程序:
g++ -c main.cpp
g++ -o main main.o -L. -lshared
仅得到以下错误:
Undefined symbols:
"myclass<int>::getx()", referenced from:
_main in main.o
_main in main.o
"myclass<int>::setx(int)", referenced from:
_main in main.o
如果我删除shared.h/cpp
中的“模板”内容,并仅用“整数”替换它们,那么一切正常。 另外,如果我只将模板类代码复制并粘贴到main.cpp
中,并且不链接到共享库,那么一切也将正常运行。
如何获得这样的模板类以通过共享库工作?
我将MacOS 10.5和GCC 4.0.1一起使用。
我在NET Core2.0 App中有以下课程。
// required when local database does not exist or was deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
public AppContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
return new AppContext(builder.Options);
}
}
当不存在数据库时,在进行迁移的Core 2.0中这是必需的,并且必须在运行update-database时创建。
升级到ASP.NET Core 2.0后无法创建迁移
我想在2个地方(在这里和appsettings.json中)没有ConnectionString,而仅在.json中所以我试图替换
"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
与
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
但它不起作用,我得到的是空值。
更新1:
只是要注意,在Core 2中不需要显式添加.json,因此问题不在于文件。
[HTTPS://Andrew lock.net/exploring-program-安定-startup-in-asp-net-core-2-preview1-2/]
更新2:
另外我已经在使用Configuration从.json发送ConnectionString到Context:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
}
但是我不能将其用于ToDoContextFactory,因为它没有配置,并且ToDoContextFactory被迁移使用,因此该应用程序根本没有运行。
解:根据@JRB的回答,我将其工作如下:
public AppContext CreateDbContext(string[] args)
{
string projectPath = AppDomain.CurrentDomain.BaseDirectory.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0];
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(projectPath)
.AddJsonFile("appsettings.json")
.Build();
string connectionString = configuration.GetConnectionString("DefaultConnection");
var builder = new DbContextOptionsBuilder<AppContext>();
builder.UseSqlServer(connectionString);
return new AppContext(builder.Options);
}
我们有一台运行Django支持站点的服务器。 由于我们要测试该站点,因此我们使用的是Django的内置开发服务器(即0.0.0.0
)。 但是我很好奇以下命令的ip:
python manage.py runserver 0.0.0.0:80
这将导致一个运行中的站点,我们可以使用服务器的ip远程访问该站点。
但是,当使用0.0.0.0
代替时:
python manage.py runserver 127.0.0.1:80
没有人可以使用另一台计算机的服务器IP访问该站点。
所以为什么? 0.0.0.0
到底是什么意思(Google说这是默认路由)? 为什么不能远程访问127.0.0.1:80
?
我想绘制概率图,但是imshow会为概率为零的点生成模糊值。 如何摆脱围绕真实网格点的模糊外围?
例:
import numpy as np
import matplotlib.pyplot as plt
a=np.asarray([[ 0.00000000e+00 , 1.05824446e-01 , 2.05086136e-04, 0.00000000e+00],
[ 1.05824446e-01 , 3.15012305e-01 , 1.31255127e-01 , 1.05209188e-01],
[ 2.05086136e-04 , 1.31255127e-01 , 0.00000000e+00 , 0.00000000e+00],
[ 0.00000000e+00 ,1.05209188e-01 , 0.00000000e+00 , 0.00000000e+00]])
im=plt.imshow(a,extent=[0,4,0,4],origin='lower',alpha=1,aspect='auto')
plt.show()
我已经阅读了很多有关C ++类的教程,但是他们错过了其他教程包括的内容。
有人可以告诉我如何编写和使用一个非常简单的C ++类,该类使用可见性,方法以及简单的构造函数和析构函数吗?
我正在使用CMake生成Visual Studio项目文件。 我想在设置PATH环境变量后运行测试可执行文件,以便它能够加载所需的dll。 我按照[http://www.mail-archive.com/cmake@cmake.org/msg21493.html]上的讨论进行了尝试,但是它不起作用。
您是否已将CMake与Visual Studio一起使用? 请分享您的经验。
另外,我找不到调试CMake脚本的简便方法,例如查看它为PATH变量分配了什么值。 用CMAKE_VERBOSE_MAKEFILE
设置CMake冗长无济于事。 我将如何自行调试?
我试图了解fold和foldLeft以及各自的reduce和reduceLeft是如何工作的。 我以fold和foldLeft为例
scala> val r = List((ArrayBuffer(1, 2, 3, 4),10))
scala> r.foldLeft(ArrayBuffer(1,2,4,5))((x,y) => x -- y._1)
scala> res28: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(5)
scala> r.fold(ArrayBuffer(1,2,4,5))((x,y) => x -- y._1)
<console>:11: error: value _1 is not a member of Serializable with Equals
r.fold(ArrayBuffer(1,2,4,5))((x,y) => x -- y._1)
为什么fold
无法用作foldLeft
? 什么是Serializable with Equals
? 我了解fold和foldLeft在参数泛型类型方面具有稍微不同的API签名。 请指教。 谢谢。
测试点P是否在由一组点X形成的凸包内的最简单方法是什么?
我想要一种在高维空间(例如,最多40个维)中工作的算法,该算法不会显式计算凸包本身。 有任何想法吗?
当我在稳定频道中将Android Studio更新为3.0并运行该项目时,我开始收到以下错误消息。
Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
我尝试清理和重建项目,但是没有成功。 任何帮助将不胜感激。
项目级别build.gradle
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'com.google.gms:google-services:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
应用程序级别build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.med.app"
minSdkVersion 21
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
resConfigs "auto"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
//appcompat libraries
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:design:26.1.0'
//butterknife
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//picasso
compile 'com.squareup.picasso:picasso:2.5.2'
//material edittext
compile 'com.rengwuxian.materialedittext:library:2.1.4'
// Retrofit & OkHttp & and OkHttpInterceptor & gson
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
// FirebaseUI for Firebase Auth
compile 'com.firebaseui:firebase-ui-auth:3.1.0'
}
apply plugin: 'com.google.gms.google-services'
我已经尝试了所有给出的答案,但无法解决此错误。 请帮忙。
我正在用python做一些脚本。 我创建一个保存在文件中的字符串。 这个字符串有很多数据,来自目录的树状结构和文件名。根据convmv的介绍,我所有的树状结构都是UTF-8。
我想将所有内容都保留在UTF-8中,因为之后将其保存在MySQL中。现在,在UTF-8的MySQL中,我遇到了一些字符问题(例如é或è-我是法语)。
我希望python始终将字符串用作UTF-8。 我在互联网上阅读了一些信息,我确实是这样。
我的脚本以此开头:
#!/usr/bin/python
# -*- coding: utf-8 -*-
def createIndex():
import codecs
toUtf8=codecs.getencoder('UTF8')
#lot of operations & building indexSTR the string who matter
findex=open('config/index/music_vibration_'+date+'.index','a')
findex.write(codecs.BOM_UTF8)
findex.write(toUtf8(indexSTR)) #this bugs!
当我执行时,这是答案:SHOW variables LIKE 'char%'
编辑:我发现在我的档案中口音写得很好。 创建此文件后,我将其读取并将其写入MySQL。但是我不明白为什么,但是我在编码方面遇到了问题。我的MySQL数据库位于utf8中,或者似乎是SQL查询SHOW variables LIKE 'char%'
仅向我返回utf8或二进制。
我的功能看起来像这样:
#!/usr/bin/python
# -*- coding: utf-8 -*-
def saveIndex(index,date):
import MySQLdb as mdb
import codecs
sql = mdb.connect('localhost','admin','*******','music_vibration')
sql.charset="utf8"
findex=open('config/index/'+index,'r')
lines=findex.readlines()
for line in lines:
if line.find('#artiste') != -1:
artiste=line.split('[:::]')
artiste=artiste[1].replace('\n','')
c=sql.cursor()
c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom="'+artiste+'"')
nbr=c.fetchone()
if nbr[0]==0:
c=sql.cursor()
iArt+=1
c.execute('INSERT INTO artistes(nom,status,path) VALUES("'+artiste+'",99,"'+artiste+'/")'.encode('utf8')
很好地显示在文件中的Artiste会将错误写入BDD。问题是什么 ?
有什么办法可以在PHP
中将json
转换为xml
? 我知道xml到json的可能性很大。
我最近完成了一堆Java编码,并且已经习惯了非常特定的软件包命名系统,例如深度嵌套。 com.company.project.db
。在Java,AS3 / Flex和C#中运行正常。 我也曾经在C ++中看到过相同的范例,但是我也听说将C ++名称空间视为Java包的直接对应对象是很不好的。
是真的,为什么? 名称空间/程序包有何相似之处和不同之处? 如果您使用深层嵌套的名称空间,可能会出现什么问题?