程序员问答大本营 98sky.com.
votes
answers
11 views
+50

Difference between static and shared libraries?

What is the difference between static and shared libraries?

I use Eclipse and there are several project types including Static Libraries and Shared Libraries? Does one have an advantage over the other?

votes
answers
34 views
+50

oracle apex觸發鼠標點擊區域使用jquery

0

我在我的apex頁面有3個區域。 R1,R2和R3。 R1是一個表格區域。 R2和R3是R1的子區域。我想在點擊按鈕時使用javascript觸發區域R3上的虛假鼠標單擊事件。所以觸發鼠標點擊區域R3(靜態ID:R3)我使用的代碼oracle apex觸發鼠標點擊區域使用jquery

$('#R3').trigger("click"); 

但這並不行。當我檢查頁面時,我發現區域ID爲'SR_R3_tab'。於是我將代碼改爲

$('#SR_R3_tab').trigger("click"); 

這並沒有取得任何進展。我怎樣才能做到這一點 ?

votes
answers
11 views
+50

Integrating Sphinx to MySQL

I am trying to use Sphinx full-text search capability for my MySQL server. I have setup a local Sphinx service based on the installation manual and able to do text search.

I can connect to

mysql.exe --host=127.0.0.1 port=9306

Where the port 9306 is the port configured in sphinx.conf:

searchd {
...
listen = 9306:mysql41
...
}

And do SphinxQL queries. I am using the default Sphinx example database shipped with the release package.

However I want to integrate Sphinx with my MySQL server, such that all the clients connecting to my sql server can do SphinxQL and I want to try it out with the MySQL sample database sakila

  • What are the steps to achieve that?
  • Do I need to convert the database engine from InnoDB to Sphinx?
  • Also, from what it seems, Sphinx can only index one (1) database table per configuration, how can I make sure that all tables in the MySQL database gets indexed?
votes
answers
34 views
+50

無法通過IntelliJ在tomcat上運行服務Idea

0

我正在研究一個框架「beadledom」。 我對IntelliJ Idea也比較新,我之前用過eclipse,beadledom框架包含項目子模塊, api 服務 客戶端 在Eclipse中如果我們要運行服務,我會右鍵點擊「服務「子模塊在服務器上運行 - > tomcat;它會運行。 我的webapp存儲在「服務」文件夾中。無法通過IntelliJ在tomcat上運行服務Idea

我不知道我該怎麼做它的IntelliJ

我沒有設置運行Configuartion。 我被要求創建在編輯配置> Tomcat之類的「神器」 enter image description here

votes
answers
10 views
+50

劃分一個小數字不會給商0

0

我有下一個問題: 當我試圖做一個較小的數字分成一個更大的一個我得到商很高,我不明白爲什麼。這裏是我試圖劃分1到5的程序,結果是256.(也是變量'a'和'b'必須是db類型的) 有人可以幫助我嗎?謝謝你在前進劃分一個小數字不會給商0

.model small 
afisareanr macro nr 
local m11 
local m 
xor ax, ax 
mov ax, nr 
push ax    
mov si, 10   
mov di, 5   

mov dx, 0   
cmp ax, 0   
jge m    
neg ax    

m:div si    
add dl, 30h   

mov s[di],dl   

xor dx,dx   
dec di    
cmp ax, 0   

jne m    

pop ax    

cmp ax, 0   
jge m11    
mov s[di], '-'  

m11: 
mov ah, 9   
lea dx, s 
int 21h 
endm 

.stack 
.data 
a db 5 
b db 1 
s db 6 dup(" "), '$' 

.code 
mov ax, @data 
mov ds, ax 

xor ax, ax 
xor bx, bx 
mov al, b 
idiv a 
mov bx, ax 
afisareanr bx 

mov ax, 4c00h 
int 21h 

end 
votes
answers
11 views
+50

Android Studio emulator does not come with Play Store for API 23

I selected this emulator from the newest version of Android Studio AVD.

Google API

I have selected the latest version of android API 23. Because it says "with Google APIs", I thought that it would actually include all the Google apps, including Play Store so that I can install apps like Facebook.

I have seen other threads on SO which seems to be outdated now (How to install Google Play app in Android Studio emulator?), this one gives instructions for installing Google apps based on universal packages but it only goes up to Android 4.3 API 18: http://wiki.rootzwiki.com/Google_Apps#Universal_Packages_2

I would like the one for API 23. Is there a way to install the Google Apps package on the emulator?

It seems strange that the official android emulator doesn't come standard with all the google apps in the first place...This doesn't seem very supportive of google and would potential mean developers will have to buy actual devices to develop for API 23?

votes
answers
22 views
+50

看不到第三個div。溢出另一個

0

嘿傢伙我不知道我的代碼有什麼問題。但page3溢出page2。但我需要他們一個接一個來。我複製粘貼的page2,只是改變了類名。看不到第三個div。溢出另一個

.main { 
 
    color: white; 
 
    width: 100%; 
 
    height: 100vh; 
 
    background-image: url("landbackground2.jpeg"); 
 
    background-size: cover; 
 
    background-position: center bottom; 
 
} 
 

 
.overlay { 
 
    width: 100%; 
 
    height: 100vh; 
 
    background-color: rgba(0, 0, 0, 0.5); 
 
} 
 

 
.main-content { 
 
    padding: 50px; 
 
    position: absolute; 
 
    left: 50%; 
 
    top: 50%; 
 
    transform: translate3d(-50%, -50%, 0); 
 
} 
 

 
.icon { 
 
    padding: 7px; 
 
    display: inline-block; 
 
    background-color: rgba(255, 255, 255, 0.5); 
 
    border-radius: 50%; 
 
    font-size: 20px; 
 
    float: right; 
 
} 
 

 
.logo { 
 
    font-size: 20px; 
 
    display: inline-block; 
 
} 
 

 
.header { 
 
    z-index: 100; 
 
    width: 100%; 
 
    position: fixed; 
 
    padding: 20px 20px; 
 
} 
 

 

 
#main-h1 { 
 
    font-size: 50px; 
 
    font-weight: bold; 
 
    font-family: 'Indie Flower', cursive; 
 
} 
 

 

 

 
/* NOTE: PAGE 2 */ 
 

 

 
.page2 { 
 
    position: absolute; 
 
    color: white; 
 
    width: 100%; 
 
    height: 100vh; 
 
    background-image: url("page2.jpg"); 
 
    background-size: cover; 
 
    background-position: center; 
 

 
} 
 

 
.page2-content { 
 
    padding: 20px 30px; 
 
    background-color: rgba(0, 0, 0, 0.5); 
 
    text-align: center; 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    transform: translate(-50%, -50%); 
 

 
} 
 

 
a { 
 
    text-decoration: none; 
 
    padding: 10px; 
 
    border: 1px solid white; 
 
    border-radius: 5px; 
 
    color: white; 
 
    transition: 0.5s; 
 
} 
 

 
a:hover { 
 
    text-decoration: none; 
 
    color: white; 
 
    background-color: rgba(0, 0, 0, 0.7); 
 
    box-shadow: white 0px 0px 20px; 
 
} 
 

 
.bg-attach { 
 
    background-attachment: fixed; 
 
} 
 

 
.page3 { 
 
    position: absolute; 
 
    color: white; 
 
    width: 100%; 
 
    height: 100vh; 
 
    background-image: url(".jpg"); 
 
    background-size: cover; 
 
    background-position: center; 
 
} 
 

 

 

 
.fuck { 
 
    position: relative; 
 
    display: block; 
 
    height: 100vh; 
 
    background: pink; 
 
}
<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
 
    <link rel="stylesheet" href="C:UsersAdminDesktopLabbyootstrap-4.0.0-beta.2distcssootstrap.min.css"> 
 
    <link rel="stylesheet" href="reset.css"> 
 
    <link rel="stylesheet" href="C:UsersAdminDesktopLabbycssfont-awesome.min.css"> 
 
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet"> 
 
    <link rel="stylesheet" href="C:UsersAdminDesktopLabbylanding pageslandpage.css"> 
 
    <title>Landing Page</title> 
 
</head> 
 
<body> 
 
    <div class="main"> 
 
    <div class="overlay"> 
 
     <header> 
 
     <div class="header"> 
 
      <p class="logo">Road trip</p> 
 
      <i class="fa fa-bars icon" aria-hidden="true"></i> 
 
     </div> 
 
     </header> 
 
     <div class="main-content"> 
 
     <h1 id="main-h1">This is Road Trip</h1> 
 
     </div> 
 
    </div> 
 
    </div> 
 

 
    <div class="page2"> 
 
    <div class="overlay"> 
 
     <div class="page2-content"> 
 
     <h1 >This is Road Trip</h1> 
 
     <h2>21.12.2112</h2> 
 
     <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure nam, nihil blanditiis.</p> 
 
     <div class="btn"> 
 
      <a href="#">Learn more . . .</a> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    </div> 
 
    <div class="page3"> 
 
    <div class="overlay"> 
 
     <div class="page3-content"> 
 
     <h1 >This is Road Trip</h1> 
 
     <h2>21.12.2112</h2> 
 
     <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure nam, nihil blanditiis.</p> 
 
     <div class="btn"> 
 
      <a href="#">Learn more . . .</a> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    </div> 
 

 

 

 

 

 

 

 

 
    </body> 
 
</html>

+2

如果您希望元素互相跟隨 - 在頁面的自然流動 - 那麼就不要使用絕對定位。它們會自然地出現在彼此之後。 –

+0

的作品,但在這種情況下,我不能使用頂部或左側居中我的主要內容。第2頁上的內容將其從fisrt頁面的頂部開始。 –

+0

如果你正在談論'.main-content',那麼你仍然可以絕對定位。這是一個塊,你*不需要在自然流動。 –

votes
answers
19 views
+50

錯誤:「指定的LINQ表達式包含對與不同上下文關聯的查詢的引用」

-4

當我嘗試獲取屬於它們的部門名稱的所有用戶時,使用ASP.Net MVC我不斷收到此錯誤:錯誤:「指定的LINQ表達式包含對與不同上下文關聯的查詢的引用」

DepartmentName = db.Departments.Where(d => d.DepartmentId == u.DepartmentId).Select(n =>n.DepartmentName).ToString() 

從我在谷歌搜索,我想我必須執行兩個查詢,但我不知道該怎麼做。 這是我的ViewModel

public class UserListViewModel 
    { 
     public string Id { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string Email { get; set; } 
     public string RoleName { get; set; } 
     public string DepartmentName { get; set; } 

    } 

和行動

public ActionResult Users() 
     { 

      List<UserListViewModel> model = new List<UserListViewModel>(); 

      model = UserManager.Users.Select(u => new UserListViewModel 
      { 

       Id = u.Id, 
       FirstName = u.FirstName, 
       LastName = u.LastName, 
       Email = u.Email, 

       DepartmentName = db.Departments.Where(d => d.DepartmentId == u.DepartmentId).Select(n =>n.DepartmentName).ToString() 

      }).ToList(); 

預先感謝您!

+2

'UserManager'和'db'是兩個不同的上下文。嘗試移動查詢中的「DepartmentName」選項以獲取用戶 - 只需在擁有用戶標識後獲取。 – Dido

+0

@Dido感謝您的迴應,但我怎樣才能獲取用戶和部門分開,你能告訴我嗎?我嘗試之前像這樣DepartmentName = db.Departments.Where(d => d.DepartmentId == ?????)。Select(n => n.DepartmentName).ToString(),但d => d.DepartmentId with什麼? –

votes
answers
25 views
+50

將佈局從一個活動傳遞到另一個活動

0

如何將精確的RelativeLayout從一個活動傳遞到另一個活動。結果建議立即進行刪除是這個樣子:Example將佈局從一個活動傳遞到另一個活動

爲了解釋:

我有一個從數據庫中使用SimpleCursorAdapter和局部佈局填充一個GridView。 部分佈局看起來是這樣的:

<RelativeLayout>  
    <TextView/> 
    <TextView/> 
    <Button/> 
    <Button/>  
</RelativeLayout> 

當用戶點擊一個項目的詳細信息按鈕,我woud喜歡該項目的RelativeLayout的傳遞給DetailsActivity。

據我所知cloning是不可能的,inflating不是一個選項。

我發誓傳遞每個id,標籤和文本值並重新創建一個佈局,但我是hopinbg有一個更簡單的方法。

+0

該佈局添加到第二個活動的頂部。您不需要anything.after它的所有細節活動通過這樣就會產生這些值。 – Adithya

votes
answers
25 views
+50

在終端提示符當前git分支

-1

我試圖做一個小工具(也許它已經存在)來幫助從終端處理存儲庫和分支。在終端提示符當前git分支

基本上這個想法是在提示符下輸入分支的名稱(類似於虛擬環境,它也顯示提示中的當前環境)。

下面的命令只是提取分公司目前我在名字。

git branch | grep "*" | cut -c3- 

包括這在我的.bashrc文件修改PS1作品,但只有當控制檯打開時改變了提示。

我想在每次更改文件夾cd my_folder,cd ..時更新提示,所以如果我轉到另一個存儲庫,它會更新分支。

所以我爲cd創建了一個別名,它在執行cd之後現在追加了這個小腳本。

但是,如果我使用git更改分支,因爲我沒有更改文件夾,提示未立即更新。

我也可以爲git創建一個別名,但我的印象是我改變了太多的東西,也許這是已經存在的東西。

爲避免重新發明輪子,這是否已經存在?使用它是一個好主意嗎?

謝謝

+2

有許多shell框架可以做到這一點。請在https://github.com/robbyrussell/oh-my-zsh,https://github.com/sorin-ionescu/prezto等找到實例。 –

votes
answers
10 views
+50

How to limit depth for recursive file list?

Is there a way to limit the depth of a recursive file listing in linux?

The command I'm using at the moment is:

ls -laR > dirlist.txt

But I've got about 200 directories and each of them have 10's of directories. So it's just going to take far too long and hog too many system resources.

All I'm really interested in is the ownership and permissions information for the first level subdirectories:

drwxr-xr-x 14 root   root  1234 Dec 22 13:19 /var/www/vhosts/domain1.co.uk  
drwxr--r-- 14 jon    root  1234 Dec 22 13:19 /var/www/vhosts/domain1.co.uk/htdocs  
drwxr--r-- 14 jon    root  1234 Dec 22 13:19 /var/www/vhosts/domain1.co.uk/cgi-bin  
drwxr-xr-x 14 root   root  1234 Dec 22 13:19 /var/www/vhosts/domain2.co.uk  
drwxr-xrwx 14 proftp root  1234 Dec 22 13:19 /var/www/vhosts/domain2.co.uk/htdocs  
drwxr-xrwx 14 proftp root  1234 Dec 22 13:19 /var/www/vhosts/domain2.co.uk/cgi-bin  
drwxr-xr-x 14 root   root  1234 Dec 22 13:19 /var/www/vhosts/domain3.co.uk  
drwxr-xr-- 14 jon    root  1234 Dec 22 13:19 /var/www/vhosts/domain3.co.uk/htdocs  
drwxr-xr-- 14 jon    root  1234 Dec 22 13:19 /var/www/vhosts/domain3.co.uk/cgi-bin  
drwxr-xr-x 14 root   root  1234 Dec 22 13:19 /var/www/vhosts/domain4.co.uk  
drwxr-xr-- 14 jon    root  1234 Dec 22 13:19 /var/www/vhosts/domain4.co.uk/htdocs
drwxr-xr-- 14 jon    root  1234 Dec 22 13:19 /var/www/vhosts/domain4.co.uk/cgi-bin

EDIT:

Final choice of command:

find -maxdepth 2 -type d -ls >dirlist
votes
answers
14 views
+50

Android: How to pass Parcelable object to intent and use getParcelable method of bundle?

Why bundle has getParcelableArrayList, getParcelable methods; but Intent has only putParcelableArrayListExtra method? Can I transmit only object<T>, not ArrayList of one element? Then, what is getParcelable for?

votes
answers
7 views
+50

根據內部數組上的對象的屬性對數組進行排序

0

我有一個從我們的API返回的具有以下數據結構的帳戶數組。根據內部數組上的對象的屬性對數組進行排序

Accounts[] accounts = [ 
    { 
     AccountNumber: 0000000001, 
     PrimaryPerson: Virginia, 
     PrimaryPersonNumber: 0001, 
     PersonRoleCode: "OWN", 
     PersonRoleDescription: "Owner", 
     RoleOrder: 1 
     PersonRoles: [ 
         { 
          AccountRoleCode: "CO", 
          AccountRoleDescription: "Co-Owner", 
          PersonName: "David", 
          PersonNumber: 0002, 
          RoleOrder: 2 
         }, 
         { 
          AccountRoleCode: "POA", 
          AccountRoleDescription: "Power of Attorney", 
          PersonName: "Clark", 
          PersonNumber: 0003, 
          RoleOrder: 6 
         } 
        ] 
    }, 
    { 
     AccountNumber: 0000000002, 
     PrimaryPerson: Clark, 
     PrimaryPersonNumber: 0003, 
     PersonRoleCode: "OWN", 
     PersonRoleDescription: "Owner", 
     RoleOrder: 1 
     PersonRoles: [ 
         { 
          AccountRoleCode: "CO", 
          AccountRoleDescription: "Co-Owner", 
          PersonName: "Virginia", 
          PersonNumber: 0001, 
          RoleOrder: 2 
         }, 
         { 
          AccountRoleCode: "POA", 
          AccountRoleDescription: "Power of Attorney", 
          PersonName: "David", 
          PersonNumber: 0002, 
          RoleOrder: 6 
         } 
        ] 
    }, 
    { 
     AccountNumber: 0000000003, 
     PrimaryPerson: David, 
     PrimaryPersonNumber: 0002, 
     PersonRoleCode: "OWN", 
     PersonRoleDescription: "Owner", 
     RoleOrder: 1 
     PersonRoles: [ 
         { 
          AccountRoleCode: "CO", 
          AccountRoleDescription: "Co-Owner", 
          PersonName: "Clark", 
          PersonNumber: 0003, 
          RoleOrder: 2 
         }, 
         { 
          AccountRoleCode: "CO", 
          AccountRoleDescription: "Co-Owner", 
          PersonName: "Virginia", 
          PersonNumber: 0001, 
          RoleOrder: 2 
         }, 
         { 
          AccountRoleCode: "POA", 
          AccountRoleDescription: "Power of Attorney", 
          PersonName: "Virginia", 
          PersonNumber: 0001, 
          RoleOrder: 6 
         } 
        ] 
    } 
]; 

我需要梳理基礎上,RoleOrderAccounts對象本身這個Accounts對象和RoleOrder在每個PersonRoles[]指數PersonRole對象。

我試過用LINQ來做,但我不確定它爲什麼不能正常工作。

下面是我試過的和我期望它做的事情。

IEnumberable<Account> sortedAccounts = accounts 
    .OrderBy(acct => acct.PersonRoles 
    .Where(role => role.PersNbr == 0001) 
    .Select(x => x.RoleOrder)).ToList(); 

我預期它由PersonRoles[]其中PersNbr是等於給定PersNbr(0001)訂購的主accounts[]和排序在RoleOrder

所以基本上我想根據RoleOrder爲一個特定的人排序accounts[]

所以排序基於Virginia將導致Accounts[] accounts = [0000000001, 0000000003, 0000000002]

排序基於David將導致Accounts[] accounts = [0000000003, 0000000001, 0000000002]

我有LINQ沒有做任何事情(順序保持不變),這讓我覺得我正在按照正確的順序執行查詢。

如何編寫LINQ查詢來執行此操作,還是需要將它分解爲不同的查詢?

votes
answers
17 views
+50

如何在基本身份驗證中使用Jenkinsfile管道中的httpRequest

0

有誰知道如何在基本身份驗證中使用Jenkinsfile管道中的httpRequest? 我檢查了https://github.com/jenkinsci/http-request-plugin,它們支持支持基本認證(請參閱全局配置)。但是當我在我的groovy腳本中實現時,我發現了以下錯誤。任何人都可以展示如何將用戶名和密碼傳遞給httprequest。如何在基本身份驗證中使用Jenkinsfile管道中的httpRequest

def masterDataReplicatorTriggerDeployment() { 
milestone 40 
VaultUtil vaultUtil = PipelineUtil.getInstance(this).getProdVaultUtil() 
def ROUTER_USER 
def ROUTER_PASS 
def baseurl="http://master-data-replicator.cfapps.us10.hana.ondemand.com" 
def sourcetenant="revcdevkp" 
def targettenant="revcdevpo" 
def copyBCdata="/replicator/v1/businessConfig/" 
def response 


ROUTER_USER=vaultUtil.readCredential 
("secret/landscapes/infrastructure/router").get("router.security.username") 
ROUTER_PASS=vaultUtil.readCredential 
("secret/landscapes/infrastructure/router").get("router.security.password") 
response = httpRequest url: 
baseurl+copyBCdata+sourcetenant+"/"+targettenant, 
httpMode: 'POST', 
authentication: [Username: ROUTER_USER, Password: ROUTER_PASS] 

}

org.kohsuke.stapler.NoStaplerConstructorException:有一個關於在org.kohsuke.stapler.ClassDescriptor.loadConstructorParamNames(ClassDescriptor.java類java.lang.String 的任何構造沒有@DataBoundConstructor: 247) 在org.jenkinsci.plugins.structs.describable.DescribableModel。(DescribableModel.java:122) 在org.jenkinsci.plugins.structs.describable.DescribableModel.coerce(DescribableModel.java:380) 在

 def creds = "ROUTER_USER:ROUTER_PASS" 
    String auth = creds.bytes.encodeBase64().toString() 
    httpRequest consoleLogResponseBody: true, 
     url: baseurl+copyBCdata+sourcetenant+"/"+targettenant,      
     customHeaders:[[name:'Authorization', value:"Basic ${auth}"]] 

新問題:401認證問題。 但我確實使用了正確的憑證並可以訪問它們。

我知道我的認證格式不正確,你知道哪個應該是正確的方法嗎? 謝謝。

最好的問候,

votes
answers
17 views
+50

Algolia Places錯誤「container」必須指向<input>元素

1

我一直在試圖將Algolia Places應用到我的註冊頁面,並努力讓它適用於城市輸入。Algolia Places錯誤「container」必須指向<input>元素

控制檯錯誤: 未捕獲錯誤:Algolia Places:'container'必須指向一個元素。

我已經試過各種選擇都沒有成功:

  • 容器: 「#ID城」
  • 容器:document.querySelector( '#id_city')
  • 容器:document.querySelector( '輸入#id_city')
  • 容器:document.querySelector( 「輸入[ID = 'id_city']」)
  • 容器:document.querySelector( 「輸入[名稱= '城市']」)

我敢肯定,這是愚蠢的東西,但不知道我做錯了什麼......

感謝您的幫助!

<input type="text" class="form-control " name="city" id="id_city" value="" size="20" maxlength="120"> 


<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> 
<script> 

var options = { 
    container: "#id-city", 
    type: "city", 
}; 
places(options); 
</script> 
+0

奧利弗結帳的答案,如果是足夠您的需要 –

votes
answers
25 views
+50

sha256_crypt.encrypt總是返回另一個散列

0

我正在開發一個使用python和flask的webapp。它有一個用戶系統,當然還有一個註冊表。我正在使用,加密要註冊的用戶的密碼,passlib.hash.sha256。以下是我在做什麼:sha256_crypt.encrypt總是返回另一個散列

from passlib.hash import sha256_crypt as sha256 
[...] 
if request.method == "POST" and form.validate(): 
    username = request.form['username'] 
    password = request.form['password'] 
    confirm_password = request.form['confirm_password'] 
    email = request.form['email'] 

    password = sha256.encrypt(password) #Encryption. 



    c, conn = connection('accounts') #Connection to the database 


    x = c.execute("SELECT * FROM accounts WHERE username = '%s' OR email = '%s'" %(thwart(username), thwart(email))) 

    if x: 
     flash("We are very sorry, but this Username/Email-address is already taken. Please try again") 
    else: 
     c.execute('INSERT INTO accounts VALUES ("%s", "%s", "%s")' %(thwart(username), thwart(password), thwart(email))) 
     conn.commit() 
     flash('Succesfully Registered!') 

在數據庫中,即使輸入了相同的密碼,散列總是變化。有人知道爲什麼嗎?我究竟做錯了什麼?

+0

你已經發現了這個概念鹽https://en.wikipedia.org/wiki/Salt_(cryptography)。你確定你有足夠的資格來處理認證嗎? –

+0

你是什麼意思「合格」 – MisterMM23

+0

我明白了。但是我沒有編寫任何可以添加隨機數據的程序。這是python的sha256的新功能嗎? – MisterMM23

votes
answers
15 views
+50

wp_customize-自定義設置不保存

0

我剛開始使用WordPress,並試圖添加一些控件到我的後端來自定義我的網站。我添加的第一個控件 - 圖像選擇器 - 工作得很好,但第二個setting-background-size-不保存該值,因此在刷新頁面後,圖像會從style.css文件返回到默認值。所有設置都會正確應用,直到我刷新。wp_customize-自定義設置不保存

這裏是我到目前爲止的代碼同時與背景圖像和背景大小:

的style.css:

section#banner { 
background-image: url(images/banner.jpg); 
background-size: auto; 
background-repeat: no-repeat; 
background-position: left top; 
} 

的functions.php:

/** 
* Customizer Options for #banner 
* Theme Options Customizer Implementation. 
* 
* @param WP_Customize_Manager $wp_customize Object that holds the customizer data. 
*/ 
function pf_banner_customizer($wp_customize){ 

/* 
* Failsafe is safe 
*/ 
if (! isset($wp_customize)) { 
    return; 
} 

/** 
* Add '#banner' Section. 
*/ 
$wp_customize->add_section(
    // $id 
    'pf_section_banner', 
    // $args 
    array(
     'title'   => __('#banner', 'theme-slug'), 
     'active_callback' => 'is_front_page', 
     'priority' => 1, 
    ) 
); 

/** 
* Add 'Backgrounds Background Image' Setting. 
*/ 
$wp_customize->add_setting(
    // $id 
    'pf_banner_background_image', 
    // $args 
    array(
     'default'  => get_stylesheet_directory_uri() . '/images/welcome-background.jpg', 
     'sanitize_callback' => 'esc_url_raw', 
     'transport'  => 'postMessage' 
    ) 
); 

/** 
* Add 'Backgrounds Background Image' image upload Control. 
*/ 
$wp_customize->add_control(
    new WP_Customize_Image_Control(
     // $wp_customize object 
     $wp_customize, 
     // $id 
     'pf_banner_background_image', 
     // $args 
     array(
      'settings'  => 'pf_banner_background_image', 
      'section'  => 'pf_section_banner', 
      'label'   => __('Backgrounds Background Image', 'theme-slug'), 
     ) 
    ) 
); 

$wp_customize->add_setting(
    // $id 
    'pf_banner_scaling', 
    // $args 
    array(
     'default'  => 'Auto', 
     'sanitize_callback' => 'esc_url_raw', 
     'transport'  => 'postMessage' 
    ) 
); 

$wp_customize->add_control(
    new WP_Customize_Control(
      // $wp_customize object 
      $wp_customize, 
      // $id 
      'pf_banner_scaling', 
      // $args 
      array(
       'label'    => __('Banner Scaling Options', 'theme-slug'), 
       'description' => __('Options for Scaling the background image'), 
       'settings'  => 'pf_banner_scaling', 
       'priority'  => 10, 
       'section'   => 'pf_section_banner', 
       'type'    => 'select', 
       'choices'   => array(
        'auto'  => 'Auto', 
        'cover'  => 'Cover', 
        'contain' => 'Contain', 
        'custom' => 'Custom', 
       ) 
      ) 
    ) 
); 

} 
// Settings API options initilization and validation. 
add_action('customize_register', 'pf_banner_customizer'); 

/** 
* Writes the Backgrounds background image out to the 'head' element of the document 
* by reading the value from the theme mod value in the options table. 
*/ 
function pf_change_background_img() { 
?> 
<style type="text/css"> 
    <?php 
     if (get_theme_mod('pf_banner_background_image')) { 
      $banner_background_image_url = get_theme_mod('pf_banner_background_image'); 
     } else { 
      $banner_background_image_url = get_stylesheet_directory_uri() . '/images/welcome-background.jpg'; 
     } 
     section#banner { 
      background-image: url(<?php echo $banner_background_image_url; ?>); 
     } 
    <?php // } // end if ?> 
</style> 
<?php 

} // end pf_customizer_css 
add_action('wp_head', 'pf_change_background_img'); 

function pf_change_background_size() { 
?> 
<style type="text/css"> 
<?php 
    $bg_size = get_theme_mod('pf_banner_scaling'); 
     ?> 
     section#banner { 
      background-size: <?php echo $bg_size; ?>; 
      background-color: '#00ffff' 
     } 
     ?> 
</style>; 
<?php 
} 
add_action('wp_head', 'pf_change_background_size'); 

/** 
* Registers the Theme Customizer Preview with WordPress. 
* 
* @package sk 
* @since  0.3.0 
* @version 0.3.0 
*/ 
function pf_customizer_live_preview() { 
wp_enqueue_script(
    'pf-theme-customizer', 
    get_stylesheet_directory_uri() . '/js/theme-customizer.js', 
    array('customize-preview'), 
    '0.1.0', 
    true 
); 
} // end pf_customizer_live_preview 
add_action('customize_preview_init', 'pf_customizer_live_preview'); 

JS /主題 - customizer.js:

(function($) { 
    "use strict"; 
    // Image Control for section#banner 
    wp.customize('pf_banner_background_image', function(value) { 
     value.bind(function(to) { 
      $('#banner').css('background-image', 'url(' + to + ')'); 
     }); 
    }); 

})(jQuery); 

(function($) { 
    "use strict"; 
    // Image Scaling Option for section#banner 
    wp.customize('pf_banner_scaling', function(value) { 
     value.bind(function(to) { 
      $('#banner').css('background-size', to); 
     }); 
    }); 

})(jQuery); 

對不起,代碼的牆。

下面是一個相關的問題:

我刷新後,下拉控件是空的。我希望它顯示當前值或默認值,都是'自動'。

任何指針非常感謝!

votes
answers
22 views
+50

項目歐拉#11邏輯

-3

我已經開始玩弄項目歐拉,但是我打了一個路障在problem 11項目歐拉#11邏輯

什麼是四個相鄰數的最大產品在同一 方向(上,下,在20×20格左,右,或對角)?`

有可能是在我的邏輯的地方,但即使多休息和新方法後的一個錯誤,我仍然沒有成功。

正確的輸出應該是70600674,但我得到51267216.

這更是一個教育問題,我想至少知道我搞砸了。

input.txt中:

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 

Main.py:

in_file = 'input.txt' 

m = list(map(lambda line_str: list(map(int, line_str.split(' '))), open(in_file, 'r').read().split('
'))) 

for line in m: 
    print(' '.join(map(lambda num: str(num).rjust(2), line))) 
print() 

vertical_max = horizontal_max = main_diag_max = second_diag_max = 0 

for line in range(17): 
    for col in range(20): 
     vertical_max = max(vertical_max, m[line][col] * m[line+1][col] * m[line+2][col] * m[line+3][col]) 

for line in range(20): 
    for col in range(17): 
     horizontal_max = max(horizontal_max, m[line][col] * m[line][col+1] * m[line][col+2] * m[line][col+3]) 

for line in range(17): 
    for col in range(17): 
     main_diag_max = max(main_diag_max, m[line][col] * m[line+1][col+1] * m[line+2][col+2] * m[line+3][col+3]) 

for line in range(3, 20): 
    for col in range(3, 20): 
     second_diag_max = max(second_diag_max, m[line][col] * m[line-1][col-1] * m[line-2][col-2] * m[line-3][col-3]) 


print('max vertical:   ', vertical_max) 
print('max horizontal:  ', horizontal_max) 
print('max main diagonal:  ', main_diag_max) 
print('max secondary diagonal:', second_diag_max) 
print('max result:   ', max(vertical_max, horizontal_max, main_diag_max, second_diag_max)) 
+1

你的問題是什麼? – DavidG

+0

是什麼問題?輸出是否錯誤(如果是這樣,它應該是什麼)?或者你有錯誤信息? – JJJ

+0

你好@DavidG。這個問題在帖子的最後一行是正確的^^「這更像是一個教育問題,我想至少知道我在哪裏搞砸了。」我做錯了什麼? –

votes
answers
14 views
+50

Javascript - 正在更新字符串值

0

我一直在嘗試創建一張虛擬撲克牌,其中一張牌可以從卡組中抽出一張隨機牌。Javascript - 正在更新字符串值

我做這個工作的方式是通過一個switch語句,這樣如果繪製一個'AH'的值,那麼所顯示的圖像就是一張Card of Ace of Hearts。到現在爲止還挺好。

但是,我試圖實現一個小功能,以便顯示一條消息,說'你畫了心的王牌。我的(失敗)的嘗試在成纔是分割變量「AH」成2個獨立的變量:

var drawnCardValue = 'A'; 
var drawnCardSuit = 'H'; 

然後使用switch語句「A」到「王牌」和「H」轉換成「心」:

function fullName(){ 
    switch(drawnCardValue){ 
     case 'A': 
      drawnCardValue = "Ace"; 
      break; 
     } //repeated for all values 
    switch(drawnCardSuit){ 
     case 'H': 
      drawnCardValue = "Ace"; 
      break; 
     } //repeated for all suits 
    } 

當我的drawcard()函數實現上述功能,如下所示:

function drawCard(){ 
    if(count < 52){ 
     drawnCard = deck.shift(); 
     showCard(); 
     var drawnCardValue = drawnCard.slice(0, -1); 
     var drawnCardSuit = drawnCard.slice(-1); 
     fullName(); 
     document.getElementById("info").innerHTML = "You drew " + drawnCardValue + " of " + drawnCardSuit; 
     count++; 
    } else{ 
     document.getElementById("info").innerHTML = "Out of Cards"; 
    } 
} 

仍然顯示:您畫了一個h的

這是什麼原因?我該如何解決它?

在此先感謝!

+1

請提供完整的代碼,或者至少到它的鏈接。 – deathangel908

+0

請創建工作模型或jsfiddle – brk

+0

看起來像你永遠不會打電話fullName()' –

votes
answers
32 views
+50

如何爲python 3實現RC4加密?

-1

我的代碼引發此錯誤:如何爲python 3實現RC4加密?

Error :  
    j = (j + S[i] + k[i % keyLen]) % 256 
    IndexError: list index out of range 

我的代碼:

#!/usr/bin/python3 
key = 242 

def main(): 

    initializeS(key) 

#Key-Scheduling algorithm used to initialize a permutation in array S 
#Keylength is the number of bytes in the key it can vary from 0 - 256 bytes 
def initializeS(k): 

    k = str(k).encode('utf-8') 
    print(k) 
    keyLen = len(k) 
    S = [] 
    j = 0 

    for i in range(0, 256): 
     j = (j + S[i] + k[i % keyLen]) % 256 
     S[i], S[j] = S[j], S[i] 
return S 

main() 
+1

提供您的代碼並解釋問題是什麼以及您嘗試了什麼,IOW a [mcve],這意味着樣本輸入和輸出,錯誤和錯誤消息。 – zaph

+0

道歉,我已經添加了代碼。謝謝 – Nick

+1

提示:使用中間變量而不是複合語句,如'(j + S [i] + k [i%keyLen])%256'。這樣你就可以確切地知道是什麼導致了錯誤。 – zaph

votes
answers
27 views
+50

如何從QT中的QFileSystemModel獲取文件路徑(C++)

-1

首先,假設存在一個存儲多個圖像的文件夾。然後,我嘗試單擊UI中的按鈕打開文件夾,然後將該文件夾中所有圖像的文件路徑保存到QList(僅限過濾的圖像文件)。但QList不存儲任何東西。請幫忙。如何從QT中的QFileSystemModel獲取文件路徑(C++)

void MainWindow::on_pushButton_clicked() 
{ 
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), 
               "/home", 
               QFileDialog::ShowDirsOnly 
               | QFileDialog::DontResolveSymlinks); 
    model = new QFileSystemModel(); 
    filesPath = dir; 
    model->setRootPath(dir); 
    QStringList filter; 
    filter <<"*.png" <<"*.jpg" <<"*.bmp" <<"*.gif"; 
    model->setNameFilters(filter); 
    model->setNameFilterDisables(false); 

    ui->treeView->setModel(model); 
    ui->treeView->setRootIndex(model->index(dir)); 
    ui->treeView->setAnimated(false); 
    ui->treeView->setSortingEnabled(true); 

    QList<QString> path_list; 
    QModelIndex parentIndex = model->index(dir); 
    int numRows = model->rowCount(parentIndex); 

    for (int row = 0; row < numRows; ++row) { 
     QModelIndex childIndex = model->index(row, 0, parentIndex); 
     QString path = model->data(childIndex).toString(); 
     if(!QFileInfo(path).isDir()) 
      path_list.append(path); 
    } 
} 
+0

你需要閱讀Qt文檔:http://doc.qt.io/qt-5/qfilesystemmodel.html#details –

+0

@ md612爲什麼你使用'QFileSystemModel'? –

+0

@Dmitry Sazonov將其與QtreeView – md612

votes
answers
21 views
+50

Python:編寫命令行指令時的字符串格式化

1

我有一個任務,我必須每次運行一系列參數略有不同的仿真。我想編寫一個Python腳本來自動執行此操作,但我遇到了一個問題。Python:編寫命令行指令時的字符串格式化

爲了簡化描述,我基本上有從命令行調用的N模擬,每個模擬都有一組不同的參數,我希望腳本一個接一個地執行它們。想象一下,要運行模擬,我會將execute_simulation...寫入命令行,其中...代表給定模擬的參數。這是我的腳本看起來像:

from subprocess import call 

<code> 

for i in range(0, N): 
    call('execute_simulation_%s' % (parameters[i])) 

但是,我總是在調用腳本時收到錯誤消息。任何人都可以提出爲什麼這可能是這種情況?

+2

什麼是錯誤信息? ['call'](https://docs.python.org/2.7/library/subprocess.html#subprocess.call)需要一個參數列表,而不是一個字符串(除非你使用'shell = True',你應該避免)。 – 2017-11-11 18:11:23

+1

什麼錯誤消息? –

+0

準確的模擬文件是什麼?你的'parameters []'是否也包含文件擴展名? 'call('ca%s.exe'%'lc')'正在爲我工??作(Win7)。 – bastelflp

votes
answers
26 views
+50

gnuplot的:格式YAXIS在10^x的

0

我有以下數據項:gnuplot的:格式YAXIS在10^x的

y, x 
1, 8.0    
10, 3.6    
100, 3.36    
1000, 3.212     
10000, 3.152    
100000, 3.14316    
1000000, 3.14266   
10000000, 3.1420448   
100000000, 3.14190876 
1000000000, 3.141573084 

,我試圖在10^x

術語格式y軸上pi的 Ñ計算值我用下面的代碼:

set terminal pngcairo size 1280,800 enhanced font 'Helvetica,24' 
set output "fig.png" 

# Title, axis label, range and ticks 
set title "Simulations" 
set xlabel "Number of Iterations(n)" 
set ylabel "Computed values" 

# Legend location and grid 

set key top left 
set grid 
set ytics out nomirror 
set xtics out nomirror 
set format y "10^{%L}" 


# Plot the data 
plot data.dat" using 2:1 title "" with linesp lw 2 pt 7 ps 1.5 

但我得到以下的輸出:

enter image description here

請幫

感謝

votes
answers
25 views
+50

MongoDB C# Driver - Ignore fields on binding

When using a FindOne() using MongoDB and C#, is there a way to ignore fields not found in the object?

EG, example model.

public class UserModel
{
    public ObjectId id { get; set; }
    public string Email { get; set; }
}

Now we also store a password in the MongoDB collection, but do not want to bind it to out object above. When we do a Get like so,

  var query = Query<UserModel>.EQ(e => e.Email, model.Email);
  var entity = usersCollection.FindOne(query);

We get the following error

Element 'Password' does not match any field or property of class 

Is there anyway to tell Mongo to ignore fields it cant match with the models?

votes
answers
16 views
+50

提示某些AWS Cli操作上的MFA代碼

0

我們強制MFA用於AWS Web控制檯訪問。但是我也想要一些aws動作來提示MFA代碼。提示某些AWS Cli操作上的MFA代碼

aws iam delete-users --user-name theusername 
Enter MFA: ********* 

這可能嗎?

votes
answers
14 views
+50

C#線程問題

0

我想做一件簡單的事情。C#線程問題

我有一個輔助線程正在聽USB讀卡器,當讀卡器「讀取」某些內容時,線程會觸發一個事件。那個事件啓動一個計時器,但計時器不起作用,我相信這是因爲關於線程。

此外,計時器必須更改窗體中的一些圖像,所以這必須在主線程中完成。

我希望我很清楚。

private void listenReader() 
    { 
     while (whileState) 
     { 

       if (readsSomething) 
       { 
        evt.OnSomeEvent(); 
        break; 
       } 

     } 
    } 

    private void eventStartsThisMethot(){ 
     //do a lot of things and start the timer 
     } 

    private void counter(){ 
     pictureBox.Image = Resources._5; 
    //the timer ticks this methot 
    } 

所以,聽讀者必須對原因很明顯單獨的線程,但第二個方法必須從主線程來完成,所以我用一個事件,但如果你有另一個想法。

感謝

+1

因此,如果該線程觸發啓動計時器的事件,誰正在監聽此計時器?另外,你正在使用哪個計時器類? – leppie 2012-07-20 21:44:21

+3

澤維爾,如果沒有發佈能夠證明您的問題的代碼示例,將很難獲得任何有意義的答案。 – 2012-07-20 21:45:30

+1

'我希望我明白:S'我恐怕你不是。 – 2012-07-20 21:53:00

votes
answers
28 views
+50

HighCharts同步提示作用的其他圖

0

我使用多個highChart在多個圖表的儀表盤頁面如linearea,花鍵,餡餅和同步HighCharts同步提示作用的其他圖

設置提示同步原型

Highcharts.Pointer.prototype.reset = function() { 
    return undefined; 
}; 

Highcharts.Point.prototype.highlight = function (event) { 
    this.onMouseOver(); // Show the hover marker 
    this.series.chart.tooltip.refresh(this); // Show the tooltip 
    this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair 
}; 

但上述功能的影響所有的高圖例如linearea和樣條圖等等我想申請的同步只有

votes
answers
25 views
+50

Bootstrap 4無法在導航欄中的鏈接之間創建保證金

-1

我想在引導程序4菜單中的鏈接之間創建一些保證金,但我無法和不知道爲什麼。當我嘗試基本上保證每一個我都沒有頁面。Bootstrap 4無法在導航欄中的鏈接之間創建保證金

<!DOCTYPE html> 
<html lang="sk"> 

<head> 

<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
<link rel="stylesheet" type="text/css" href="styles/normalize.css"> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> 
<link rel="stylesheet" type="text/css" href="styles/style.css"> 
<title>Reštaurácia</title>  

</head> 

<body> 

<!-- Navigation --> 
<nav class="navbar navbar-expand-sm navbar-light bg-faded"> 
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#nav-content" aria-controls="nav-content" aria-expanded="false" aria-label="Toggle navigation"> 
<span class="navbar-toggler-icon"></span> 
</button> 

<!-- Brand --> 
<a class="navbar-brand mleft" href="#">Reštaurácia</a> 

<!-- Links --> 
<div class="collapse navbar-collapse mright" id="nav-content"> 
<ul class="navbar-nav ml-auto"> 
<li class="nav-item "> 
<a class="nav-link " href="#">Domov</a> 
</li> 
<li class="nav-item "> 
<a class="nav-link " href="#">Rezervácia</a> 
</li> 
<li class="nav-item "> 
<a class="nav-link " href="#">Menu</a> 
</li> 
<li class="nav-item "> 
<a class="nav-link " href="#">Galéria</a> 
</li> 
<li class="nav-item "> 
<a class="nav-link " href="#">Kontakt</a> 
</li> 
</ul> 
</div> 
</nav> 






<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> 
</body> 


</html> 

bootstrap中可能有一些默認設置,不允許我做這些更改,但我無法找到它們。

+0

你能張貼你的CSS? – stojevskimilan

+0

你知道flex樣式嗎? –

+0

其實我只有一個視頻的flex的基本知識。我的CSS正常化,下一個CSS只有一個類,所以我不認爲是必要的。 –

votes
answers
13 views
+50

對話框將url發送到不同的應用程序

-1

當我點擊Google PlayStore上的共享圖標時,它會自動打開WhatsApp,Skype和Facebook等各種應用程序的選項以發送URL。對話框將url發送到不同的應用程序

是否有任何代碼或小工具具有相同的成就?

votes
answers
19 views
+50

在類函數中運行線程

0

我需要用線程運行我的代碼的一些部分。但是我訪問run()函數中的變量時遇到問題。變量(也是函數參數)需要被定義爲final,但是當我這樣做時,我不能在run()函數中更改它們的值。例如,現在變量ivrun()方法中不可訪問。在類函數中運行線程

有什麼辦法可以解決這個問題嗎?

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

    LayoutInflater inflater = getLayoutInflater(); 

    convertView = getLayoutInflater().inflate(R.layout.gallery_gridsq, parent, false); 
    ImageView iv = (ImageView) convertView.findViewById(R.id.icon); 
    final File file = new File(Uri.parse(getItem(position).toString()).getPath()); 


    Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      Bitmap bmp = null; 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inJustDecodeBounds = true; 
      try { 
       BitmapFactory.decodeStream(new FileInputStream(file), null, options); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 

      options.inJustDecodeBounds = false; 
      options.inSampleSize = 2; 
      try { 
       bmp = BitmapFactory.decodeStream(new FileInputStream(file), null, options); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 

      iv.setImageBitmap(bmp); 
     } 
    }; 

    new Thread(runnable).start(); 
    return convertView; 
} 
+0

你不重新分配'iv'變量......它可以是'final' –

votes
answers
29 views
+50

是否應該爲角材料2組件編寫包裝?

2

我正在處理幾個角度5的項目,我們想要使用https://material.angular.io/中的材料設計組件。是否應該爲角材料2組件編寫包裝?

爲了封裝材料設計組件,編寫封裝層是一個好主意嗎? 因此,我們不會寫<mat-card>...</mat-card>,而是寫<my-app-card>...</my-app-card>之類的東西。

主要動機是確保在我們所有項目中一致且易於更改用戶界面。

votes
answers
29 views
+50

How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office? [closed]

How can I create an Excel Spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?

votes
answers
12 views
+50

角 - 結合公共/私人性質

0

我做角教程在angular.io,在那裏我閱讀:角 - 結合公共/私人性質

構造(公共 messageService:MessageService){}

的messageService屬性必須是public,因爲您即將在模板中綁定它。

Angular只綁定到public組件屬性。

我強調public那裏。

但是,如果我改變公共私人 那裏,一切都和以前一樣......

所以,請指引我的地方,我能打消我的疑慮。

我的角度版本:5.0.0,

謝謝!

+0

據我所知,AOT編譯將投訴約'private'財產,AOT束還優選督促構建.. –

votes
answers
7 views
+50

是有可能使用的println在科特林

0

函數引用在Java 8和9,可以有方法引用打印到控制檯,像如:是有可能使用的println在科特林

List.of(1, 2, 3).forEach(System.out::println); 

在科特林我沒有找到一個使用方法引用打印到控制檯的方法。我試圖把這種使用函數引用:

listOf(1, 2, 3).forEach { println(it) } 

到:

listOf(1, 2, 3).forEach { ::println } 

但我收到此錯誤:

Overload resolution ambiguity. All these functions match. 
@InlineOnly public inline fun println(): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Any?): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Boolean): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Byte): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Char): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: CharArray): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Double): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Float): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Int): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Long): Unit defined in kotlin.io 
@InlineOnly public inline fun println(message: Short): Unit defined in kotlin.io 

我怎樣才能解決這個分辨率不確定性?在這種情況下是否可以使用函數引用?

+0

如果科特林不支持指定你可以創建一個調用正確的過載和使用的包裝功能的重載代替。 –

+1

文檔鏈接:https://kotlinlang.org/docs/reference/reflection.html#function-references – chris

votes
answers
11 views
+50

在for循環中使用條件之間的多條if語句

1

我是一個新的R用戶,我一直試圖執行嵌套在for循環中的if語句以編寫新變量。我有一個data.frame,其中一些人之前忘記了從E-prime編碼「條件」變量(3個級別的因素:舊,新,誘餌)。該任務有兩個階段編碼/檢索(塊1和2),兩組圖像(A和B)和一個唯一的Word ID。在for循環中使用條件之間的多條if語句

所以我有這樣的:

phase <- rep(c("Block1", "Block2"), each = 7) 
condition <- rep(NA, times = 14) 
setAorB <- rep(c("A", "B"), times = c(9,5)) 
WordID <- c(23,34,56,76,45,88,99,23,34,56,76,45,100,105) 

loris_data <- data.frame(phase,condition,setAorB,WordID) 

這給了我:

> loris_data 
    phase  condition setAorB WordID 
1 Block1  NA  A  23 
2 Block1  NA  A  34 
3 Block1  NA  A  56 
4 Block1  NA  A  76 
5 Block1  NA  A  45 
6 Block1  NA  A  88 
7 Block1  NA  A  99 
8 Block2  NA  A  23 
9 Block2  NA  A  34 
10 Block2  NA  B  56 
11 Block2  NA  B  76 
12 Block2  NA  B  45 
13 Block2  NA  B 100 
14 Block2  NA  B 105 

我想什麼實現的是:在檢索(塊2),如果setAorB是 「A」,那麼條件老了」。我嘗試了這個基本循環,但顯然,只適用於舊物品,因爲它不會區分誘餌與新物品。

for(i in 1:length(loris_data$condition)) { 
     if(loris_data$setAorB[i] == "A") { 
      loris_data$condition[i] <-"old"} 
     else { 
      loris_data$condition[i] <- "new" 
     } 
    } 

然後,我想地說:如果setAorB是「B」和單詞ID是相同的A(這意味着是誘餌),那麼條件是「誘餌」,否則如果setAorB是「B」但它有一個唯一的WordID,條件是「新」。

這將是預期的輸出:

> loris_data 
    phase condition setAorB WordID 
1 Block1  <NA>  A  23 
2 Block1  <NA>  A  34 
3 Block1  <NA>  A  56 
4 Block1  <NA>  A  76 
5 Block1  <NA>  A  45 
6 Block1  <NA>  A  88 
7 Block1  <NA>  A  99 
8 Block2  old  A  23 
9 Block2  old  A  34 
10 Block2  lure  B  56 
11 Block2  lure  B  76 
12 Block2  lure  B  45 
13 Block2  new  B 100 
14 Block2  new  B 105 

任何人都可以使用此代碼有所幫助我還在學習,我掙扎了很多?

+0

我想很容易做到你想要的,但請張貼預期的最終產出。 – PoGibas

+0

我剛剛編輯過帖子,包括預期的最終輸出 – Lollo

+0

也許你需要'library(data.table); setDT(loris_data)[phase ==「Block2」,condition:= c('new','old','lure')[as.integer(factor(1 + 2 *(setAorB ==「A」)+ 4 *(setAorB ==「B」&WordID%in%loris_data $ WordID [loris_data $ setAorB ==「A」]))]]]'將列條件轉換爲字符或使用'condition < - rep(NA_character_,times = 14)' – akrun

votes
answers
24 views
+50

在科爾多瓦更改錯誤圖像

0

我正在使用Cordova和InAppBrowser插件在我的應用程序(android)中查看外部鏈接。但是,當設備沒有連接,我想去外部鏈接它顯示Android錯誤(見圖片)。在科爾多瓦更改錯誤圖像

問題: 如何將此標準錯誤頁面(standard error image)更改爲我的自定義錯誤頁面?

非常感謝

votes
answers
17 views
+50

將值輸出給用戶

0

我試圖弄清楚如何將num1 num2和func的值輸出到用戶看到的屏幕上。這是一個計算器應用程序即時試圖完全功能。該應用程序已經工作,但我似乎無法得到數字和操作設置爲變量func顯示給用戶的屏幕。 如果您需要更多信息,請讓我知道。將值輸出給用戶

$(document).ready(function() { 
 
    var num1 = [] 
 

 
    var num2 = [] 
 

 
    var func = null 
 

 
    $('#one').click(function() { 
 
    if (func === null) { 
 
     num1.push('1') 
 
     console.log(num1) 
 
    } else { 
 
     num2.push('1') 
 
     console.log(num2) 
 
    } 
 
    }); 
 

 
    $('#two').click(function() { 
 
    if (func === null) { 
 
     num1.push('2') 
 
     console.log(num1) 
 
    } else { 
 
     num2.push('2') 
 
     console.log(num2) 
 
    } 
 
    }); 
 

 
    $('#three').click(function() { 
 
    if (func === null) { 
 
     num1.push('3') 
 
    } else { 
 
     num2.push('3') 
 
    } 
 
    }); 
 

 
    $('#four').click(function() { 
 
    if (func === null) { 
 
     num1.push('4') 
 
    } else { 
 
     num2.push('4') 
 
    } 
 
    }); 
 

 
    $('#five').click(function() { 
 
    if (func === null) { 
 
     num1.push('5') 
 
    } else { 
 
     num2.push('5') 
 
    } 
 
    }); 
 

 
    $('#six').click(function() { 
 
    if (func === null) { 
 
     num1.push('6') 
 
    } else { 
 
     num2.push('6') 
 
    } 
 
    }); 
 

 
    $('#seven').click(function() { 
 
    if (func === null) { 
 
     num1.push('7') 
 
    } else { 
 
     num2.push('7') 
 
    } 
 
    }); 
 

 
    $('#eight').click(function() { 
 
    if (func === null) { 
 
     num1.push('8') 
 
    } else { 
 
     num2.push('8') 
 
    } 
 
    }); 
 

 
    $('#nine').click(function() { 
 
    if (func === null) { 
 
     num1.push('9') 
 
    } else { 
 
     num2.push('9') 
 
    } 
 
    }); 
 

 
    $("#zero").click(function() { 
 
    if (func === null) { 
 
     num1.push('0') 
 
    } else { 
 
     num2.push('0') 
 
    } 
 
    }); 
 

 
    $('#plus').click(function() { 
 
    func = "+" 
 
    console.log(func) 
 
    }); 
 

 
    $('#minus').click(function() { 
 
    func = "-" 
 
    }); 
 

 
    $('#divide').click(function() { 
 
    func = "/" 
 
    }); 
 

 
    $('#multiply').click(function() { 
 
    func = "*" 
 
    console.log(func) 
 
    }); 
 

 
    $('#equals').click(function() { 
 
    if (func === "+") { 
 
     num1 = num1.join("") 
 
     number1 = parseInt(num1) 
 
     num2 = num2.join("") 
 
     number2 = parseInt(num2) 
 
     var complete = number1 + number2 
 
     console.log(complete) 
 
    } else if (func === "-") { 
 
     num1 = num1.join("") 
 
     number1 = parseInt(num1) 
 
     num2 = num2.join("") 
 
     number2 = parseInt(num2) 
 
     var complete = number1 - number2 
 
     console.log(complete) 
 
    } else if (func === "*") { 
 
     num1 = num1.join("") 
 
     number1 = parseInt(num1) 
 
     num2 = num2.join("") 
 
     number2 = parseInt(num2) 
 
     var complete = number1 * number2 
 
     console.log(complete) 
 
    } else if (func === "/") { 
 
     num1 = num1.join("") 
 
     number1 = parseInt(num1) 
 
     num2 = num2.join("") 
 
     number2 = parseInt(num2) 
 
     var complete = number1/number2 
 
     console.log(complete) 
 
    } else { 
 
     console.log("error") 
 
    } 
 
    }); 
 

 
    $('#clear').click(function() { 
 
    num1 = [] 
 
    num2 = [] 
 
    func = null 
 
    console.log(num1) 
 
    console.log(num2) 
 
    console.log(func) 
 
    }); 
 

 

 

 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"> 
 
</script> 
 

 
<div id="calculator-container"> 
 
    <form class="show"> 
 
    <input type="text" name="numbers" disabled><br> 
 
    </form> 
 
    <center> 
 
    <div class="calculator-view"> 
 
     <table> 
 
     <tr> 
 
      <td> 
 
      <button id="clear" type="button">AC</button> 
 
      <button id="sign" type="button">+/-</button> 
 
      <button id="divide" type="button">÷</button> 
 
      </td> 
 
     </tr> 
 
     <tr> 
 
      <td> 
 
      <button id="seven" type="button">7</button> 
 
      <button id="eight" type="button">8</button> 
 
      <button id="nine" type="button">9</button> 
 
      <button id="multiply" type="button">X</button> 
 
      </td> 
 
     </tr> 
 
     <tr> 
 
      <td> 
 
      <button id="four" type="button">4</button> 
 
      <button id="five" type="button">5</button> 
 
      <button id="six" type="button">6</button> 
 
      <button id="minus" type="button">-</button> 
 
      </td> 
 
     </tr> 
 
     <tr> 
 
      <td> 
 
      <button id="one" type="button">1</button> 
 
      <button id="two" type="button">2</button> 
 
      <button id="three" type="button">3</button> 
 
      <button id="plus" type="button">+</button> 
 
      </td> 
 
     </tr> 
 
     <tr> 
 
      <td> 
 
      <button id="zero" type="button">0</button> 
 
      <button id="equals" type="button">=</button> 
 
      </td> 
 
     </tr> 
 
     </table> 
 
    </div>

+0

綁定所有的點擊次數也請添加您的HTML,什麼是錯誤你越來越多了? –

votes
answers
23 views
+50

Java,多個線程,每次只執行一個線程

4

我正在完成一項任務,必須創建兩個類,一個代表一個人,另一個代表一個橋,另一個代表橋。只有一個人可以在任何時候「穿越」橋,但可能有人在等待穿越Java,多個線程,每次只執行一個線程

我很容易用多線程來實現這一點,允許多人同時跨越,但我遇到問題時改變它只允許一個線程運行...

我的主要問題是他們想要的類設計,我必須在人類中開始線程,但橋類需要能夠等待並通知他們開始/停止

任何想法我可以做到這一點?

votes
answers
10 views
+50

你如何編碼PHP來檢查空容器,如果沒有,然後運行SQL查詢?

0

這是我有,它不工作。我需要檢查Your_Location.php中的字段是否爲空。如果是,則拋出錯誤。如果不;按照以下方式運行查詢。如果我扔//這將工作,如果(!mysqli_query($康恩,$的SQLInsert))你如何編碼PHP來檢查空容器,如果沒有,然後運行SQL查詢?

<?php 
    //session_start(); 
    include 'dbConfig.php'; 
    include 'Your_Location.php'; 

    $childfirst = $_POST['element_1']; 
    $childlast = $_POST['element_2']; 
    $childdobyear = $_POST['element_3_3']; 
    $childdobmon = $_POST['element_3_1']; 
    $childdobday = $_POST['element_3_2']; 
    $childbaptize = $_POST['element_4']; 
    $childrelationship = $_POST['inputrelation']; 
    $childdob = "$childdobyear-$childdobmon-$childdobday"; 



    $sqlinsert="INSERT INTO memchild (ID, FirstName, LastName, DOB, Baptize, Relationship) 
    VALUES 
    ('$getid2','$childfirst','$childlast','$childdob','$childbaptize','$childrelationship')"; 



    //Build arrays of fields 

    $required = array('element_1', 'element_2', 'element_3_3', 'element_3_2', 'element_3_1', 'elelment_4', 'inputrelation'); 

    //Loop to check for empties 
    $error = false; 

    foreach($required as $fields) { 
     if(empty($_POST[$fields])){ 
      $error = true; 
     } 
    } 

    if($error){ 
    Sleep(3) 
    ?> 
    <script> 
     document.getElementById('li_9').innerHTML = '* $childfirst Make sure the fields are not empty.'; 
    </script> 
    <?php 
    exit(); 
    }Else{ 
    mysqli_query($conn,$sqlinsert) 
    ?> 
    <script> 
     document.getElementById('li_9').innerHTML = '$childfirst $childlast has been added.'; 
    </script> 
    <?php 
    sleep(3); 
    echo "<meta http-equiv='refresh' content='0'>"; 
    } 
    ?> 
+0

這可行,但我需要檢查,看看字段是空的。 」; } ?> –

+0

這與'Java'有什麼關係?你是否意指'JavaScript',這是一種完全不同的語言? – Andreas

votes
answers
13 views
+50

Android Studio錯誤安裝Java

-2

我正在嘗試安裝Android Studio,並且出現無法修復的錯誤。見附圖:Android Studio錯誤安裝Java

Image

+1

它看起來像你正在搖籃錯誤。請找出如何將這些錯誤的文本複製到剪貼板,然後將它們粘貼到格式化的塊中,減去txtspk和plz-halp-me請求。 – halfer

+0

1.Error:java.util.concurrent.ExecutionException:com.android.tools.aapt2.Aapt2Exception:AAPT2錯誤:檢查日誌以獲取詳細信息 –

+0

2.Error:執行任務':app:mergeDebugResources'失敗。 >錯誤:java.util.concurrent.ExecutionException:com.android.tools.aapt2.Aapt2Exception:AAPT2錯誤:檢查日誌以獲取詳細信息 –

votes
answers
21 views
+50

如何在xcode中啓動儀器

0

任何人都可以告訴我,如何在xcode環境中啓動儀器工具來測試內存泄漏。 注:IAM無法與設備連接,只用模擬器檢查它 - XCODE - 3.2.3版,iOS版-4提前如何在xcode中啓動儀器

votes
answers
21 views
+50

在謂詞Prolog中進行功能檢查對象

0

我最近開始學習Prolog,並且對謂詞和函數有疑問。我怎麼能寫一個函數,它會檢查是否在謂詞對象是另一個謂詞例如:在謂詞Prolog中進行功能檢查對象

vertex(a). 
edge(l,k,-1). 
edge(k,l,4). 
edge(a,z,-2). 
checkEdges(edge(X,Y,_)) :- vertex(X),vertex(Y) 

P.S我怎樣才能讓此功能打印一條消息,如果元素不是頂點?

+2

這不是一個函數。 Prolog沒有功能,它只有謂詞和函子。 –

votes
answers
22 views
+50

Code Composer Studio - MSP430編譯錯誤「目標配方失敗」

0

我嘗試在4年後再次使用MSP430 Launchpad和Code Composer Studio。我之前已經安裝了CCS v5,並且最近將V7安裝到了D驅動器中(我自己選擇)Code Composer Studio - MSP430編譯錯誤「目標配方失敗」

在我最後幾個小時發生編譯錯誤後,我一直無法修復......我發現我有v5文件仍在計算機上。所以我卸載V7,手動刪除所有文件V5,然後重新安裝CCS V7進入C盤(默認目錄)

我得到同樣的錯誤依然:

"C:\ti\ccsv7\utils\bin\gmake" -k -j 4 all -O 
subdir_rules.mk:9: recipe for target 'blink.obj' failed 
gmake: *** [blink.obj] Error 1 
gmake: Target 'all' not remade because of errors. 
**** Build Finished **** 

現在,我的代碼運行是隨包裝附帶的示例代碼,所以我認爲它是正確的。錯誤所指的文件似乎是在嘗試編譯時自動生成的,因此它似乎不太可能在代碼中有任何問題,因爲它是由編譯器/生成文件的人員所做的。

9號線:

@echo 'Building file: $<' 

Code Composer Editor View - Attached Picture

我趕在11行很長的路徑定義輸入幾次,所以所有的包括已經填充到第17行,只是爲了便於在圖像中顯示,但他們其實都在第11行。

votes
answers
19 views
+50

Get Android Phone Model programmatically

I would like to know if there is a way for reading the Phone Model programmatically in Android.

I would like to get a string like HTC Dream, Milestone, Sapphire or whatever...

votes
answers
20 views
+50

fork() branches more than expected?

Consider the following piece of code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    int i;
    for(i = 0; i < 2; i++)
    {
        fork();
        printf(".");
    }
    return 0;
}

This program outputs 8 dots. How can that be possible? Should not there be 6 dots instead?

votes
answers
18 views
+50

無法解決org.jetbrains.android

1

使用的IntelliJ和gradle這個作爲依賴管理構建一個Android Studio插件,並試圖指定的IntelliJ支持IDE的無法解決org.jetbrains.android

<depends>org.jetbrains.android</depends> 

問題org.jetbrains.android沒有得到解決。

的建議解決方案是:

你需要添加插件/安卓/ lib中/的android.jar您的IntelliJ IDEA SDK的類路徑

找不到plugins/android/lib/android.jar。有關如何找到此信息的任何信息?

votes
answers
10 views
+50

ClLocation地標不返回管理區域

-1

嘿我有一些座標[「37.7」,「-122.4」],我試圖用來反轉geoCode。所以我可以得到一個簡單的UI標籤的城市和國家。 但是,當我使用CLLocation通過用placeMark標準的administrativeArea var/method來獲取狀態時,它返回nil。ClLocation地標不返回管理區域

?一些:1個元件 - 0:舊金山灣,舊金山灣,舊金山,美國@ < + 37.80000000,-122.50000000> +/-100.00米,區域CLCircularRegion(標識符:」 < + 37.79999999,-122.50000000>半徑141.72' ,中心:< + 37.79999999,-122.50000000>,半徑:141.72米)

這是我從完成處理回。這使得很明顯,沒有任何狀態從這個返回。爲什麼會這樣,我還能如何獲得這個狀態。

封閉的代碼塊控制這個行動所有幫助表示讚賞。

CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placeMark, error) in 
      if error != nil{ 
       print("There was an error") 
      }else{ 
       if let place = placeMark?[0]{ 
        print(place) 
        print(place.locality ?? "") 
        print(place.subAdministrativeArea ?? "") 
        let myAttribute = [NSAttributedStringKey.font:UIFont(name: "Times New Roman", size: 15.3)!] 
        let myAttrString = NSAttributedString(string: place.locality ?? "", attributes: myAttribute) 
        locLabel.attributedText = myAttrString 
       } 
      } 

     }) 
votes
answers
41 views
+50

Matlab:沒有足夠的GPU內存用於分類

0

我已經從頭開始用我自己的類別(現在只是花類型)培訓了Mathworks提供的Resnet50,並且想要測試它。Matlab:沒有足夠的GPU內存用於分類

雖然在將訓練選項中的MiniBatchSize更改爲5而不是10後,訓練沒有問題,但分類不會啓動,因爲它表示沒有足夠的內存可用。我正在使用imageDataset中的測試圖像,就像在培訓期間一樣。

有沒有辦法強制CPU分類或調整一些選項,以便它能夠運行? 歡迎任何其他想法!

votes
answers
11 views
+50

sqlite的格式文本與變量值

0

我想要做的這個Java代碼相當於源碼在加薪的錯誤消息(中止,「消息」),sqlite的格式文本與變量值

String location = //initialize string 
String output = String.format("Error: Insert into the SIGHTINGS table references location %s that is not found in database.", location); 

這是我嘗試過,但它似乎沒有工作:

CREATE TRIGGER SightingLocationError 
    BEFORE INSERT ON SIGHTINGS 
    FOR EACH ROW 
    WHEN NEW.LOCATION NOT IN FEATURES 
BEGIN 
    SELECT RAISE(ABORT, 'Error: Insert into the SIGHTINGS table references location'|| CAST(NEW.LOCATION AS TEXT) || 
'that is not found in the database.'); 
END; 

我也試了一下沒有投成文本,並與周圍的整個消息的一部分括號,這些方法也不能工作。 格式化錯誤消息的正確方法是什麼,以便它將顯示無法插入的位置的名稱,因爲它不在FEATURE表中?

votes
answers
21 views
+50

在模板方法消除警告由於unsignedness

4

我發現它在某些時候進行以下檢查一些模板代碼:在模板方法消除警告由於unsignedness

template<class IntegralType> 
void randomFunction(IntegralType t) 
{ 
    ... 
    if (t < 0) 
    ... 
} 

代碼的想法是,t是一個整體式的(無論是有符號或無符號)。代碼工作得很好,無論簽名如何,但編譯器發出警告,因爲在unsigned整數的情況下,檢查將始終爲真。

是否有方法C++ 03修改代碼以擺脫警告而不是壓制它?不知何故,我正在考慮檢查T的簽名,不知道它是可能的。

我知道C++ 11的is_signed,但我不確定它如何在C++ 03中實現。

+0

對於'unsigned IntegralType',您總是可以使用* specialization *,它不會進行比較併爲其他常用代碼調用一個或多個函數。 –

+0

@Someprogrammerdude看起來如何? 'template void randomFunction(unsigned IntegralType)''將'unsigned'解釋爲'unsigned int'並且抱怨。 – user2891462

+0

可能重複的[比較始終是錯誤的,因爲範圍有限...使用模板](https://stackoverflow.com/questions/2056996/comparison-is-always-false-due-to-limited-range-with-模板) – jww

votes
answers
14 views
+50

How do you add an action to a button programmatically in xcode

I know how to add an IBAction to a button by dragging from the interface builder, but I want to add the action programmatically to save time and to avoid switching back and forth constantly. The solution is probably really simple, but I just can't seem to find any answers when I search it. Thank you!

votes
answers
16 views
+50

FileBasedSink的類型參數是什麼?

1

我正在遷移將FileBasedSink從2.0.0版擴展到2.2.0的自定義接收器。類已發生變化,增加了兩個類型參數:UserTDestinationTFileBasedSink的類型參數是什麼?

@Experimental(value=FILESYSTEM) 
public abstract class FileBasedSink<UserT,DestinationT,OutputT> 
extends java.lang.Object 
implements java.io.Serializable, HasDisplayData 

我檢查的FileBasedSink的文檔,但無法找到它的目的。

所有類型的參數只有OutputT有一個文檔:

* @param <OutputT> the type of values written to the sink.` 
votes
answers
17 views
+50

Websockets with Tornado: Get access from the “outside” to send messages to clients

I'm starting to get into WebSockets as way to push data from a server to connected clients. Since I use python to program any kind of logic, I looked at Tornado so far. The snippet below shows the most basic example one can find everywhere on the Web:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hello World")

    def on_message(self, message):
        print 'message received %s' % message
        self.write_message('ECHO: ' + message)

    def on_close(self):
    print 'connection closed'


application = tornado.web.Application([
  (r'/ws', WSHandler),
])


if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

As it is, this works as intended. However, I can't get my head around how can get this "integrated" into the rest of my application. In the example above, the WebSocket only sends something to the clients as a reply to a client's message. How can I access the WebSocket from the "outside"? For example, to notify all currently connected clients that some kind event has occured -- and this event is NOT any kind of message from a client. Ideally, I would like to write somewhere in my code something like:

websocket_server.send_to_all_clients("Good news everyone...")

How can I do this? Or do I have a complete misundersanding on how WebSockets (or Tornado) are supposed to work. Thanks!

votes
answers
9 views
+50

科特林-的Android空不能轉換到非空型kotlin.String

-1

我不能同步我的項目,因爲這樣的:科特林-的Android空不能轉換到非空型kotlin.String

Caused by: kotlin.TypeCastException: null cannot be cast to non-null type kotlin.String 
    at org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt.loadKotlinVersionFromResource(KotlinPluginWrapper.kt:89) 
    at org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt.access$loadKotlinVersionFromResource(KotlinPluginWrapper.kt:1) 
    at org.jetbrains.kotlin.gradle.plugin.KotlinBasePluginWrapper.<init>(KotlinPluginWrapper.kt:39) 
    at org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPluginWrapper.<init>(KotlinPluginWrapper.kt:70) 
    at org.gradle.api.internal.DependencyInjectingInstantiator.newInstance(DependencyInjectingInstantiator.java:81) 
    at org.gradle.api.internal.plugins.DefaultPluginManager.instantiatePlugin(DefaultPluginManager.java:72) 
    ... 126 more 

這事我更新了科特林插件1.1.61

votes
answers
14 views
+50

爲什麼內的函數調用運行第一比母體函數調用角2

1

我有兩個功能,第一個是myFunction的()和myDiv()爲什麼內的函數調用運行第一比母體函數調用角2

<div (click)="myDiv()"> 
    <button (click)="myFunction()"> Submit </button> 
</div> 

在AppComponent我有這兩種功能的認定中像這樣:

myFunction() 
{ 
    console.log("I am in myFunction"); 
} 

myDiv() 
{ 
    console.log("I am in myDiv"); 
} 

這樣做的結果應該是:

我在myFunction的

我在myDiv

爲什麼myFunction在myDiv之前先運行?是什麼原因?

+0

原因是這是事件如何傳播。閱讀關於此https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Examples#Example_5:_Event_Progagation – dfsq

votes
answers
13 views
+50

Clearing localStorage in javascript?

Is there any way to reset/clear browser's localStorage in javascript?

votes
answers
17 views
+50

完整性約束違規:1052列和where子句是曖昧

0

我有兩個表的Tbl_payroll_leave_employeev2tbl_payroll_leave_schedulev2,我想join他們,但即時得到類似這樣的錯誤完整性約束違規:1052列和where子句是曖昧

「SQLSTATE [23000]:完整性約束違規:1052列 'payroll_leave_employee_id' 在where子句是不明確的(SQL:選擇payroll_employee_idtbl_payroll_leave_employee_v2內上tbl_payroll_leave_employee_v2加入tbl_payroll_leave_schedulev2payroll_leave_employee_id = tbl_payroll_leave_schedulev2payroll_leave_employee_id其中payroll_leave_employee_id = 5。)?」

我的表結構 enter image description here

$employee_id = Tbl_payroll_leave_employeev2::select('payroll_employee_id') 
    ->join('tbl_payroll_leave_schedulev2','tbl_payroll_leave_employee_v2.payroll_leave_employee_id','=','tbl_payroll_leave_schedulev2.payroll_leave_employee_id') 
    ->where('payroll_leave_employee_id',$emp) 
    ->get(); 
votes
answers
14 views
+50

How to fix Eclipse validation error “No grammar constraints detected for the document”?

Eclipse 3.5.2 is throwing an XML schema warning message:

No grammar constraints (DTD or XML schema) detected for the document.

The application.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<application
  xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/application_5.xsd"
  version="5">

</application>

I do not want to disable the warning. How can I get Eclipse to correctly validate the XML document?

votes
answers
33 views
+50

Web服務客戶端VS直接訪問遠程數據庫

0

有什麼缺點和網絡服務的優點VS直接客戶的SQL Server通信?Web服務客戶端VS直接訪問遠程數據庫

從我的理解:

優點:

  • 如果Web服務是同一臺計算機上安裝遠程分貝??那麼就沒有必要打開SQL Server的端口,這樣客戶端可以訪問遠程數據庫。如果Web服務位於另一臺計算機上,則需要打開端口以便Web服務訪問遠程數據庫。

  • 如果有人設法得到的用戶保持:通過他只能在分貝爲架構的網絡服務,而不是在整個數據庫中的所有操作不操作。

缺點:

  • 更多的程序員

  • 較慢的工作

votes
answers
17 views
+50

how is cherrypy working? it handls requests well compared with tornado when concurrence is low

I carried out a test on cherrypy (using web.py as a framework) and tornado retrieving webpages from the internet.

I have three test cases using siege to send requests to server (-c means number of users; -t is testing time). Code is below the test results.

1. web.py (cherrpy)

  siege ip -c20 -t100s             server can handle 2747requests  
  siege ip -c200 -t30s             server can handle 1361requests
  siege ip -c500 -t30s             server can handle 170requests

2. tornado synchronous

  siege ip -c20 -t100s             server can handle 600requests  
  siege ip -c200 -t30s             server can handle 200requests
  siege ip -c500 -t30s             server can handle 116requests

3. tornado asynchronous

  siege ip -c20 -t100s             server can handle 3022requests  
  siege ip -c200 -t30s             server can handle 2259requests
  siege ip -c500 -t30s             server can handle 471requests

performance analysis:

tornado synchronous < web.py (cherrypy) < tornado asynchronous

Question 1:

I know, using an asynchronous architecture can improve the performance of a web server dramatically.

I'm curious about the difference between tornado asynchronous architecture and web.py (cherry).

I think tornado synchronous mode handles requests one by one, but how is cherrypy working, using multiple threads? But I didn't see a large increase of memory. Cherrypy might handle multiple requests concurrently. How does it solve the blocking of a program?

Question 2:

Can I improve the performance of tornado synchronous mode without using asynchronous techniques? I think tornado can do better.

Web.py code:

import web
import tornado.httpclient
urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self, name):
        client = tornado.httpclient.HTTPClient()
        response=client.fetch("http://www.baidu.com/")
        return response.body

if __name__ == "__main__":
    app.run()

Tornado synchronous:

import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        client = tornado.httpclient.HTTPClient()
        response = client.fetch("http://www.baidu.com/" )
        self.write(response.body)


if __name__=='__main__':
    tornado.options.parse_command_line()
    app=tornado.web.Application(handlers=[(r'/',IndexHandler)])
    http_server=tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

Tornado asynchronous:

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
from tornado.options import define, options
define("port", default=8001, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        client = tornado.httpclient.AsyncHTTPClient()
        response = client.fetch("http://www.baidu.com/" ,callback=self.on_response)

    def on_response(self,response):
        self.write(response.body)
        self.finish()

if __name__=='__main__':
    tornado.options.parse_command_line()
    app=tornado.web.Application(handlers=[(r'/',IndexHandler)])
    http_server=tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
votes
answers
15 views
+50

Why does C++ compilation take so long?

Compiling a C++ file takes a very long time when compared to C# and Java. It takes significantly longer to compile a C++ file than it would to run a normal size Python script. I'm currently using VC++ but it's the same with any compiler. Why is this?

The two reasons I could think of were loading header files and running the preprocessor, but that doesn't seem like it should explain why it takes so long.

votes
answers
16 views
+50

Cross compile Go on OSX?

I am trying to cross-compile a go app on OSX to build binaries for windows and linux. I have read everything what I could find on the net. Closest example that I have found has been published on (apart from many unfinished discussions on go-nuts mailing list):

http://solovyov.net/en/2012/03/09/cross-compiling-go/

yet it does not work on my installation. I have go 1.0.2. As 1.0.2 is quite recent it looks to me that all above examples do not apply to this version.

Tried to do ./make.bash --no-clean with ENV vars set to 386/windows, it does build go, however it builds go for my installation which is darwin/amd64 and completely ignores what is set in ENV that suppose to build different compiler.

Any advises how it can be done (if it can be done at all)?

votes
answers
35 views
+50

在Sling OSGi容器中實現Alexa技能

2

我使用Apache Tomcat上託管的Java Alexa Skills Kit SDK實現了Alexa技能邏輯(speechlets)。但是,我需要將該項目移動到基於Apache Sling的服務器。它基於OSGi容器(Apache Felix)。我發現Sling DI機制非常有用。然而,它看起來像Java Alexa技能套件SDK完全不準備這樣的使用。主要問題是SDK servlet是普通的Java Servlet,而Sling不支持它。而且SDK甚至不是OSGi包。在Sling風格中使用它會很好,但我不想從頭開始複製SDK。在Sling OSGi容器中實現Alexa技能

有沒有人在OSGi容器中創建技能作爲吊索服務?我是否必須自己創建SlingServlet? Java Alexa技能套件SDK可以使用Sling服務嗎?

votes
answers
15 views
+50

Find the dependent bundles in Eclipse at runtime

How can an Eclipse bundle (eg. within activator code) find the dependent Bundle instances at runtime? I would like to find the bundles that Eclipse has choosen to satisfy the dependency requirements, I do not want to interprete the manifest myself.

An example: I would like to find all resources named "marker.txt" in all bundles on which my current bundle depends upon. Also the transitive dependencies. In order to accomplish this I need to be able to find all these bundles to begin with.

votes
answers
27 views
+50

A cycle was detected in the build path of project xxx - Build Path Problem

I'm in the process of converting my projects to OSGI bundles using maven and eclipse. Maven builds the stuff just fine, only I get the above error now within Eclipse. How can I find out which project causes this? Is there a special view or something? How can this happen, I would expect that maven can detect cyclic dependencies as well?

Update

Ok, I found something here and here

Could this be caused by the felix maven-bundle-plugin which does for each export also an import?

votes
answers
26 views
+50

如何重命名使用gradle工作區插件生成的包

-1

好吧,我想重命名由我的構建生成的包,以指定其名稱中的版本,但我所做的一切似乎都被忽略,並且包最終與項目文件夾名稱每次。如何重命名使用gradle工作區插件生成的包

的build.gradle文件

apply plugin: 'java' 

repositories { 
    mavenCentral() 
} 

dependencies { 
    // https://mvnrepository.com/artifact/org.osgi/org.osgi.core 
    compile group: 'org.osgi', name: 'org.osgi.core', version: '6.0.0' 
} 

task copyJar(type: Copy) { 
    from('generated') 
    include('*.jar') 
    into("$rootDir/build/lib/bundles") 
} 

build.finalizedBy(copyJar) 

gradle.properties

bundle_name=helloworld 
bundle_version=5.1.2 

從我個人理解,jar任務使用基本名稱和版本屬性,與其他屬性一起命名的罐子,如果沒有已經指定,所以我嘗試build.gradle文件,但它不工作,我不斷得到一個jar文件的項目文件夾的名稱

jar.baseName = "$bundle_name" 
jar.version = "$bundle_version" 

也即時通訊使用BND工作區插件,並且我認爲它覆蓋的方式jar任務的作品,但林不知道

這裏的build.gradle

//Applying the Gradle BND Plugin for Workspace Builds 
    //https://github.com/bndtools/bnd/blob/master/biz.aQute.bnd.gradle/README.md 
buildscript { 
    repositories { 
     mavenCentral() 
    } 
    dependencies { 
     classpath "biz.aQute.bnd:biz.aQute.bnd.gradle:${bnd_version}" 
    } 
} 
apply plugin: 'biz.aQute.bnd.workspace' 
apply plugin: 'java' 

    // Repositorios, aguante Maven Central. 
/* 
repositories { 
    mavenCentral() 
} 
*/ 

clean { 
    delete ("$rootDir/build/libs/bundles") 
} 

感謝你的父項目閱讀

votes
answers
25 views
+50

如何遠程訪問OSGi捆綁包信息

-1

我需要訪問有關遠程AEM應用程序(Apache Felix)的所有捆綁軟件和服務的信息。 需要包的信息:如何遠程訪問OSGi捆綁包信息

  1. 導出包和版本
  2. 導入的包和版本
  3. 捆綁狀態

需要的服務信息:

  1. 實現的接口
  2. 排名
  3. 路徑,resourceTypes,選擇了Servlet的

我們怎麼能可能聚攏通過Java程序中的所有上述信息?

我無法在OSGi容器上部署任何自定義遠程服務。必須通過外部執行的遠程Java程序來收集所有的細節。

+0

您使用哪個OSGi容器?另外,請檢查OSGi容器的API如何獲取已安裝的軟件包列表。編輯你的問題以包含你想要做的描述,因爲它聽起來像一個[X-Y問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – Progman

+0

你想看看遠程OSGi框架,但你不允許安裝任何軟件包?我不認爲這是可能的,對不起。 –

votes
answers
20 views
+50

Maven: Failed to read artifact descriptor

I am hoping someone can help me with a problem I am struggling with.

When I try to build my project from the terminal I get this error:

Failed to read artifact descriptor for com.morrislgn.merchandising.common:test-data-utils:jar:0.3b-SNAPSHOT: Could not find artifact com.morrislgn.merchandising:merchandising:pom:0.3b-SNAPSHOT

The common.test-data-utils jar is created by a separate project and shared between this and another project (the other project doesn't build either, but that is down to another problem).

I am able to build com.morrislgn.merchandising.common:test-data-utils without issue, I can see the entry it makes in the .m2 local repository on my machine. I have reindexed my repository in Eclipse also.

The POM for my project has this entry:

<dependency>
    <groupId>com.morrislgn.merchandising.common</groupId>
    <artifactId>test-data-utils</artifactId>
    <version>0.3b-SNAPSHOT</version>
</dependency>

Which appears to be correct to me - the POM doesn't report any errors either when it is viewed in Eclipse.

Can some one tell me what I am missing here or doing wrong?

votes
answers
24 views
+50

Detecting superfluous #includes in C/C++?

I often find that the headers section of a file get larger and larger all the time but it never gets smaller. Throughout the life of a source file classes may have moved and been refactored and it's very possible that there are quite a few #includes that don't need to be there and anymore. Leaving them there only prolong the compile time and adds unnecessary compilation dependencies. Trying to figure out which are still needed can be quite tedious.

Is there some kind of tool that can detect superfluous #include directives and suggest which ones I can safely remove?
Does lint do this maybe?

votes
answers
26 views
+50

兩個庫引入了不同版本的相同依賴關係。如何導入它們兩個?

10

我有以下情況:兩個庫引入了不同版本的相同依賴關係。如何導入它們兩個?

+ DentistApp 
    L TreatsLibrary 
    L IceCream 1.0 
    L CavityCausesLib 
    L IceCream 2.0 

現在,我得到一個VerifyError因爲TreatsLibrary使用IceCream.giveToKidAfterDrill()這是在2.0版本中刪除的,因爲法律上的原因。

如何導入兩個版本並確保每個版本都使用自己的版本?

+2

這不能通過在一個ClassLoader中使用一個ClassLoader來完成,只能存在該類的一個版本。 如果你不想實現自己的類加載機制,你可能想看看OSGi。 –

+0

是的,它可以完成,我只是不記得如何,它與重命名庫有關 – gurghet

+0

你用sbt-assembly標記了這個,它只會幫助你,如果你使用超級JAR打包你的庫。 –

votes
answers
27 views
votes
answers
17 views
+50

How do I tell Maven to use the latest version of a dependency?

In Maven, dependencies are usually set up like this:

<dependency>
  <groupId>wonderful-inc</groupId>
  <artifactId>dream-library</artifactId>
  <version>1.2.3</version>
</dependency>

Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)?

votes
answers
24 views
+50

使用JAR依賴項時的Android Studio - NoClassDefFoundError(一個libGDX項目)

0

因此,我編寫了一個我想在我的Android項目中使用的普通Java項目。要導入的項目是用Eclipse編寫的,所以我將它導出爲(可運行的)JAR文件並將其添加到項目的依賴項中。但是,當我嘗試使用此消息運行時,程序失敗:使用JAR依賴項時的Android Studio - NoClassDefFoundError(一個libGDX項目)

FATAL EXCEPTION: GLThread 20499 
Process: com.mkcode.droidrogue, PID: 29039 
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/mkcode/dmg/Generator; 

我是Android Studio新手。我知道在Eclipse中我可以編輯項目的運行配置並在其中添加JAR,但在Android Studio中我沒有找到類似的東西。我已經添加了JAR既是編譯時和運行時的依賴這樣的:

project dependencies

該項目是libGDX項目分成子項目(核心是,Android,iOS設備,桌面)。每個啓動項目都包含核心項目。

我能做些什麼來完成這項工作?

votes
answers
18 views
+50

Why does npm install say I have unmet dependencies?

I have a node package. When I run npm install from the package root, it installs a bunch of things, but then prints several error messages that look like this:

npm WARN unmet dependency /Users/seanmackesey/google_drive/code/explore/generator/node_modules/findup-sync/node_modules/glob requires graceful-fs@'~1.2.0' but will load

I must be confused about what exactly npm install does. If it detects a dependency, shouldn't it install it? Under what conditions does it give me error messages like this, and how can I resolve the dependencies?

votes
answers
23 views
+50

2單個表中的函數依賴關係

2

我正在嘗試基於這兩個函數依賴關係創建一個模式。2單個表中的函數依賴關係

A - > B,C,d

乙 - > d

我試圖建立一個單一的表既包括這些的FD與以下約束的:

  • 一對元組(B,D)可以重複,但遵循FD的定義(每當有兩個B值相同,則D值也相同)。

    CREATE TABLE one(
        B INT PRIMARY KEY, 
        D INT NOT NULL, 
        UNIQUE (B, D) 
    ); 
    
    CREATE TABLE two(
        A INT PRIMARY KEY, 
        B INT NOT NULL, 
        C INT NOT NULL, 
        D INT NOT NULL, 
        FOREIGN KEY(B, D) REFERENCES one(B, D) 
    ); 
    

    我只是想知道如果有一個方法可以讓我在短短一個表結合這2桌,而無需使用TRIGGERS:現在

,我在2個表如下實施本在Postgresql中?

編輯:

示例數據:

enter image description here

+2

你說的'在短短一個table'結合這兩個表是什麼意思?你能舉出你想要的例子嗎,最好包括例子數據? *(我相信我理解你描述的約束條件,我只是不明白最後一點...)* – MatBailie

+0

@MatBailie我的意思是,不是創建2個單獨的表,我只是想創建一個包含所有這些屬性的表。我用一個例子編輯了這篇文章。 –

+0

好吧,我想你的意思是'我只是想創建一個包含所有這些屬性的表格,並且強制執行所有這些約束而不需要第二個表格...... – MatBailie

votes
answers
28 views
+50

Maven does not find JUnit tests to run

I have a maven program, it compiles fine. When I run mvn test it does not run any tests (under TESTs header says There are no tests to run.).

I've recreated this problem with a super simple setup which I will include below as well as the output when run with -X.

The unit tests run fine from eclipse (both with its default junit package and when I instead include the junit.jar downloaded by maven). Also mvn test-compile correctly creates the class under test-classes. I am running this on OSX 10.6.7 with Maven 3.0.2 and java 1.6.0_24.

Here is the directory structure:

/my_program/pom.xml
/my_program/src/main/java/ClassUnderTest.java
/my_program/src/test/java/ClassUnderTestTests.java

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>my_group</groupId>
    <artifactId>my_program</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>My Program</name>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

ClassUnderTest.java:

public class ClassUnderTest {

    public int functionUnderTest(int n) {
        return n;
    }

}

ClassUnderTestTests.java:

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ClassUnderTestTests {

    private ClassUnderTest o;

    @Before
    public void setUp() {
        o = new ClassUnderTest();
    }

    @Test
    public void testFunctionUnderTest_testCase1() {
        Assert.assertEquals(1, o.functionUnderTest(1));
    }

    @Test
    public void testFunctionUnderTest_testCase2() {
        Assert.assertEquals(2, o.functionUnderTest(2));
    }
}

End of mvn -X test:

[DEBUG] Configuring mojo org.apache.maven.plugins:maven-surefire-plugin:2.7.1:test from plugin realm ClassRealm[plugin>org.apache.maven.plugins:maven-surefire-plugin:2.7.1, parent: sun.misc.Launcher$AppClassLoader@5224ee]
[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-surefire-plugin:2.7.1:test' with basic configurator -->
[DEBUG]   (s) basedir = /Users/aaron/Programs/my_program
[DEBUG]   (s) childDelegation = false
[DEBUG]   (s) classesDirectory = /Users/aaron/Programs/my_program/target/classes
[DEBUG]   (s) disableXmlReport = false
[DEBUG]   (s) enableAssertions = true
[DEBUG]   (s) forkMode = once
[DEBUG]   (s) junitArtifactName = junit:junit
[DEBUG]   (s) localRepository =        id: local
      url: file:///Users/aaron/.m2/repository/
   layout: none

[DEBUG]   (f) parallelMavenExecution = false
[DEBUG]   (s) pluginArtifactMap = {org.apache.maven.plugins:maven-surefire-plugin=org.apache.maven.plugins:maven-surefire-plugin:maven-plugin:2.7.1:, org.apache.maven.surefire:surefire-booter=org.apache.maven.surefire:surefire-booter:jar:2.7.1:compile, org.apache.maven.surefire:surefire-api=org.apache.maven.surefire:surefire-api:jar:2.7.1:compile, org.apache.maven.surefire:maven-surefire-common=org.apache.maven.surefire:maven-surefire-common:jar:2.7.1:compile, org.apache.maven.shared:maven-common-artifact-filters=org.apache.maven.shared:maven-common-artifact-filters:jar:1.3:compile, org.codehaus.plexus:plexus-utils=org.codehaus.plexus:plexus-utils:jar:2.0.5:compile, junit:junit=junit:junit:jar:3.8.1:compile, org.apache.maven.reporting:maven-reporting-api=org.apache.maven.reporting:maven-reporting-api:jar:2.0.9:compile}
[DEBUG]   (s) printSummary = true
[DEBUG]   (s) project = MavenProject: my_group:my_program:1.0-SNAPSHOT @ /Users/aaron/Programs/my_program/pom.xml
[DEBUG]   (s) projectArtifactMap = {junit:junit=junit:junit:jar:4.8.1:test}
[DEBUG]   (s) redirectTestOutputToFile = false
[DEBUG]   (s) remoteRepositories = [       id: central
      url: http://repo1.maven.org/maven2
   layout: default
snapshots: [enabled => false, update => daily]
 releases: [enabled => true, update => never]
]
[DEBUG]   (s) reportFormat = brief
[DEBUG]   (s) reportsDirectory = /Users/aaron/Programs/my_program/target/surefire-reports
[DEBUG]   (s) session = org.apache.maven.execution.MavenSession@dfbb43
[DEBUG]   (s) skip = false
[DEBUG]   (s) skipTests = false
[DEBUG]   (s) testClassesDirectory = /Users/aaron/Programs/my_program/target/test-classes
[DEBUG]   (s) testFailureIgnore = false
[DEBUG]   (s) testNGArtifactName = org.testng:testng
[DEBUG]   (s) testSourceDirectory = /Users/aaron/Programs/my_program/src/test/java
[DEBUG]   (s) trimStackTrace = true
[DEBUG]   (s) useFile = true
[DEBUG]   (s) useManifestOnlyJar = true
[DEBUG]   (s) workingDirectory = /Users/aaron/Programs/my_program
[DEBUG] -- end configuration --
[INFO] Surefire report directory: /Users/aaron/Programs/my_program/target/surefire-reports
[DEBUG] Setting system property [user.dir]=[/Users/aaron/Programs/my_program]
[DEBUG] Setting system property [localRepository]=[/Users/aaron/.m2/repository]
[DEBUG] Setting system property [basedir]=[/Users/aaron/Programs/my_program]
[DEBUG] Using JVM: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for /Users/aaron/.m2/repository
[DEBUG] dummy:dummy:jar:1.0 (selected for null)
[DEBUG]   org.apache.maven.surefire:surefire-booter:jar:2.7.1:compile (selected for compile)
[DEBUG]     org.apache.maven.surefire:surefire-api:jar:2.7.1:compile (selected for compile)
[DEBUG] Adding to surefire booter test classpath: /Users/aaron/.m2/repository/org/apache/maven/surefire/surefire-booter/2.7.1/surefire-booter-2.7.1.jar Scope: compile
[DEBUG] Adding to surefire booter test classpath: /Users/aaron/.m2/repository/org/apache/maven/surefire/surefire-api/2.7.1/surefire-api-2.7.1.jar Scope: compile
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for /Users/aaron/.m2/repository
[DEBUG] dummy:dummy:jar:1.0 (selected for null)
[DEBUG]   org.apache.maven.surefire:surefire-junit4:jar:2.7.1:test (selected for test)
[DEBUG]     org.apache.maven.surefire:surefire-api:jar:2.7.1:test (selected for test)
[DEBUG] Adding to surefire test classpath: /Users/aaron/.m2/repository/org/apache/maven/surefire/surefire-junit4/2.7.1/surefire-junit4-2.7.1.jar Scope: test
[DEBUG] Adding to surefire test classpath: /Users/aaron/.m2/repository/org/apache/maven/surefire/surefire-api/2.7.1/surefire-api-2.7.1.jar Scope: test
[DEBUG] Test Classpath :
[DEBUG]   /Users/aaron/Programs/my_program/target/test-classes
[DEBUG]   /Users/aaron/Programs/my_program/target/classes
[DEBUG]   /Users/aaron/.m2/repository/junit/junit/4.8.1/junit-4.8.1.jar
[DEBUG] Using manager EnhancedLocalRepositoryManager with priority 10 for /Users/aaron/.m2/repository
[DEBUG] dummy:dummy:jar:1.0 (selected for null)
[DEBUG]   org.apache.maven.surefire:surefire-booter:jar:2.7.1:compile (selected for compile)
[DEBUG]     org.apache.maven.surefire:surefire-api:jar:2.7.1:compile (selected for compile)
[DEBUG] Adding to surefire booter test classpath: /Users/aaron/.m2/repository/org/apache/maven/surefire/surefire-booter/2.7.1/surefire-booter-2.7.1.jar Scope: compile
[DEBUG] Adding to surefire booter test classpath: /Users/aaron/.m2/repository/org/apache/maven/surefire/surefire-api/2.7.1/surefire-api-2.7.1.jar Scope: compile
Forking command line: /bin/sh -c cd /Users/aaron/Programs/my_program && /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -jar /Users/aaron/Programs/my_program/target/surefire/surefirebooter6118081963679415631.jar /Users/aaron/Programs/my_program/target/surefire/surefire4887918564882595612tmp /Users/aaron/Programs/my_program/target/surefire/surefire9012255138269731406tmp

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.089s
[INFO] Finished at: Mon May 30 12:03:09 EDT 2011
[INFO] Final Memory: 7M/62M
[INFO] ------------------------------------------------------------------------
votes
answers
43 views
+50

無法覆蓋的想法

0

我有maven安裝在系統中的重寫默認平方米文件夾庫(它從默認位置移動到另一個磁盤) 。但是每次我在Idea中重寫這個Maven設置時,它會不斷將其更改爲默認值,當我打開另一個項目時。我在主意默認設置file -> other settings -> default settings -> mavenfile -> settings -> maven(此處不斷更改爲默認值)中進行更改。我在做什麼錯了?無法覆蓋的想法

votes
answers
20 views
+50

How to configure encoding in Maven?

When I run maven install on my multi module maven project I always get the following output:

[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!

So, I googled around a bit, but all I can find is that I have to add:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

...to my pom.xml. But it's already there (in the parent pom.xml).

Configuring <encoding> for the maven-resources-plugin or the maven-compiler-plugin also doesn't fix it.

So what's the problem?

votes
answers
17 views
+50

Maven Install on Mac OS X

I'm trying to install maven through the terminal by following these instructions.

So far I got this

export M2_HOME=/user/apple/apache-maven-3.0.3
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
export JAVA_HOME=/usr/java/jdk1.6.0_22

This is probably a stupid question where do you go to find this?

votes
answers
20 views
+50

maven包:skip成功構建的子模塊

0

我試圖用--fail-at-end使用maven 3.3.9來構建一個多子模塊項目。運行這個階段的一個週期花費了很多時間(幾個小時),並且在每個週期中我都解決了構建一些子模塊和再次運行Maven構建(從另一個週期開始)的問題。 所以問題是:有沒有辦法迫使maven不要嘗試構建在以前的週期中成功構建的包?周圍的每一次 預先感謝maven包:skip成功構建的子模塊

+0

你真的在運行數小時以上的版本嗎?多少條代碼行(1000萬行?)?多少次測試? 10或5萬? – khmarbaise

votes
answers
27 views
+50

如何在eclipse中運行JUnit測試的行爲與在命令行上運行Maven測試的行爲相同?

0

我在Mac OS上爲Eclipse開發人員使用Eclipse Oxygen。我已將我的Maven項目導入到IDE中。通常情況下,在命令行,當我運行一個測試,我將運行像如何在eclipse中運行JUnit測試的行爲與在命令行上運行Maven測試的行爲相同?

mvn test -Dtest=UserServiceTest 

除了運行「測試」的目標,這也將在「過程 - 執行一些自定義代碼我有資源「和」測試編譯「目標。但是,當我在Eclipse IDE中運行我的測試時(通過右鍵單擊包資源管理器中的類名稱,選擇「運行」然後選擇「JUnit測試」),我注意到這些其他目標未運行。

有沒有一種方法來全局設置我的項目,以便當我運行JUnit測試時,它會像輸入上面的命令一樣自動運行?我意識到我可以單獨編輯每個測試的運行配置,但是由於我有數百個,所以這將需要很多工作,並且每次我創建一個新測試時都必須執行它。如果有一些全球性的方式來設置Eclipse來爲我完成這將是非常棒的。

+1

也許運行,因爲maven構建會幫助你。 maven和eclipse不能很好地協同工作..所以我建議eighter用maven(命令行或者maven構建)運行你的測試,或者找到另一個設置你的測試的解決方案,也許@BeforeClass可以幫助你? – IEE1394

+0

是的,但運行Mvaen在命令行編譯時不允許設置斷點和輕鬆排除故障,除非有可以簡化所有這些操作的anotehr(免費)IDE。 – Dave

+0

您可以使用'mvnDebug'命令來獲取可調試的Maven會話,您可以將其附加到您的調試器。 –

votes
answers
20 views
+50

Maven 3 warnings about build.plugins.plugin.version

Since I updated to Maven 3 I get the following warning messages at each build :

How can I get rid of these warnings?

[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for proj:id:jar:3.1
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-javadoc-plugin is missing. @ line 195, column 15
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 204, column 15
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-surefire-plugin is missing. @ line 227, column 15
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-jar-plugin is missing. @ line 215, column 15
[WARNING] 'reporting.plugins.plugin.version' for org.codehaus.mojo:jdepend-maven-plugin is missing. @ line 271, column 15
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
votes
answers
31 views
+50

由於缺少WebApp庫而導致Spring引導啓動項目中的構建失敗

0

我在Eclipse Oxygen 4.7.0中有一個Spring-Boot-Starter-project,並且正在嘗試構建一個用於在EC2實例上部署的.war。我已經添加了兩個jar來允許JDBC從我部署的戰爭中連接到PostgresSQL DB服務器。由於缺少WebApp庫而導致Spring引導啓動項目中的構建失敗

location of added jars in spring-boot-starter project

我還添加了src/main/webapp/WEB-INF/lib路徑到項目的構建路徑如下圖所示

src/main/webapp/WEB-INF/lib path is added to Java build path

但是,我得到的時候我做mvn compile與構建失敗的編譯錯誤陳述原因爲無法使用瓶類

任何幫助將非常感謝

enter image description here

+1

您必須在您的pom文件中添加依賴項。如果您正在使用Maven,您需要了解事實只有在POM中,而不是在您的IDE中...... – khmarbaise

votes
answers
23 views
+50

JDBC嵌套while循環

1

那裏。 我是一個初學者使用java。我想爲我的SQL查詢結果做一個嵌套的while循環。JDBC嵌套while循環

我最初的結果就像下面,

eno ename title date_visit ssn   pname  charge  
103 Jekyl Doctor 20170717 946883650 Gershwin 125 
106 Ratchet Nurse 20170817 946883650 Gershwin 125 
103 Jekyl Doctor 20170917 946883650 Gershwin 182 
104 Caligari Doctor 20170707 831287780 Schubert 182 
106 Ratchet Nurse 20170930 799023031 Haydn 190 
102 Welby Doctor 20170818 416806352 Bernstein 210 
102 Welby Doctor 20170808 874136439 Brahms 245 
104 Caligari Doctor 20170808 796235486 Wagner 245 
102 Welby Doctor 20170929 445139565 Chopin 405 
102 Welby Doctor 20170910 874136439 Brahms 512 
103 Jekyl Doctor 20170910 524246868 Verdi 512 
103 Jekyl Doctor 20170909 129141378 Vivaldi 667 
103 Jekyl Doctor 20170909 524246868 Verdi 667 

,我寫我的Java語句像下面,

//Now we execute our query and store the results in the myresults object:  
    ResultSet myresults1 = stmt1.executeQuery("SELECT DISTINCT eno, ename, title FROM Staff_Activity"); 
    ResultSet myresults2 = stmt2.executeQuery("SELECT eno, ename, title, date_visit, ssn, pname, SUM(charge) AS total_charge FROM Staff_Activity GROUP BY eno, ename, title, date_visit, ssn, pname"); 

    System.out.println("Employee_ID	Employee_Name	Title"); 
    System.out.println("-----------	-------------	------"); //Print a header 

    while (myresults1.next()) { //pass to the next row and loop until the last   
     System.out.println(myresults1.getInt("eno") + "		" + myresults1.getString("ename") + "		" + myresults1.getString("title")); 

     while (myresults2.next()) { 
      if (myresults1.getInt("eno")==(myresults2.getInt("eno"))) { 
       System.out.println(myresults2.getInt("date_visit") + "		" + myresults2.getInt("ssn") + "		" + myresults2.getString("pname") + "		" + myresults2.getInt("total_charge")); 
      }//Print the current row 
     } 
     System.out.println(); 
    } 

我只得到了結果我的表中只有一名工作人員,

Employee_ID  Employee_Name Title 
-----------  ------------- ------ 
103    Jekyl   Doctor 
20170909    524246868    Verdi   667 
20170909    129141378    Vivaldi   667 
20170910    524246868    Verdi   512 
20170717    946883650    Gershwin    125 
20170917    946883650    Gershwin    182 

106    Ratchet   Nurse 

102    Welby   Doctor 

104    Caligari    Doctor 

真的想知道我的代碼有什麼問題。

在此先感謝。

votes
answers
19 views
+50

的Java的PreparedStatement:com.microsoft.sqlserver.jdbc.SQLServerException:參數指標超出範圍

0

我嘗試使用JAVA 8 Java的PreparedStatement和代碼的打擊的Java的PreparedStatement:com.microsoft.sqlserver.jdbc.SQLServerException:參數指標超出範圍

 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
     con = DriverManager.getConnection(URl,user,""); 
     String sql = "Select Grade from XS_KC where Snum=? and Cnum=?"; 
     PreparedStatement pst = con.prepareStatement(sql); 
     pst.setString(1, "020101"); 
     pst.setString(2, "102"); 
     rs = pst.executeQuery(); 
     while(rs.next()) 
     { 
      System.out.print(rs.getString(1)); 
     } 

我得到的fllowing執行SQL查詢錯誤:com.microsoft.sqlserver.jdbc.SQLServerException:parameter index out of range 但是,如果使用

stat = con.createStatement(); 
rs = stat.executeQuery("Select Grade from XS_KC where Snum='020101' and Cnum='101'"); 

我能得到的結果 有什麼不對?

+0

你有不同的列名,不同的值(101 VS 102)......讓我不知道實際的代碼和SQL語句 –

+0

我很抱歉。我忘記更改列名稱。但這不是關鍵。因爲我只是把它翻譯成英文 –

votes
answers
28 views
+50

遷飛JDBC連接遷移麻煩

0


我有遷飛JDBC遷移麻煩:執行我試圖關閉數據庫連接與conn.close();方法,而且所有報表後,我收到org.postgresql.util.PSQLException: This connection has been closed.例外。當我檢查數據庫時 - 我在遷移過程中所做的所有更改都已完成,但schema_version表未更新:未添加有關遷移的項目。
更多細節在這裏:
在flyway.properties我添加了classpath:com/packageone/somepackege/database/migrationflyway.locations部分。然後,我創建了將執行遷移類:public class V1_1_1__SomeImportantMigration implements JdbcMigration並填寫migrate方式類似:即在migrate方法做
遷飛JDBC連接遷移麻煩

@Override 
     public void migrate(Connection conn) throws Exception { 
      beforeActions(conn); 
      veryImportantMigration(conn, getData(conn)); 
      afterActions(conn); 
      conn.close(); 
     } 

事情被應用,但關閉連接導致異常。
由於上述信息,我有這樣的問題:爲什麼這個連接在被我關閉之前關閉?並通過什麼?

UPDATE(堆棧跟蹤):

[ERROR] Unable to rollback transaction 
org.postgresql.util.PSQLException: This connection has been closed. 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.checkClosed(AbstractJdbc2Connection.java:820) 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.rollback(AbstractJdbc2Connection.java:837) 
    at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:96) 
    at org.flywaydb.core.internal.command.DbMigrate.applyMigrations(DbMigrate.java:273) 
    at org.flywaydb.core.internal.command.DbMigrate.access$800(DbMigrate.java:53) 
    at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:210) 
    at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:146) 
    at org.flywaydb.core.internal.dbsupport.postgresql.PostgreSQLAdvisoryLockTemplate.execute(PostgreSQLAdvisoryLockTemplate.java:68) 
    at org.flywaydb.core.internal.dbsupport.postgresql.PostgreSQLDbSupport.lock(PostgreSQLDbSupport.java:162) 
    at org.flywaydb.core.internal.metadatatable.MetaDataTableImpl.lock(MetaDataTableImpl.java:174) 
    at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:146) 
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1010) 
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:971) 
    at org.flywaydb.core.Flyway.execute(Flyway.java:1464) 
    at org.flywaydb.core.Flyway.migrate(Flyway.java:971) 
    at org.flywaydb.maven.MigrateMojo.doExecute(MigrateMojo.java:30) 
    at org.flywaydb.maven.AbstractFlywayMojo.execute(AbstractFlywayMojo.java:600) 
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) 
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) 
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) 
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) 
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) 
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) 
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) 
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) 
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) 
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) 
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) 
[ERROR] Unable to restore autocommit to original value for connection 
org.postgresql.util.PSQLException: This connection has been closed. 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.checkClosed(AbstractJdbc2Connection.java:820) 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.setAutoCommit(AbstractJdbc2Connection.java:762) 
    at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:114) 
    at org.flywaydb.core.internal.command.DbMigrate.applyMigrations(DbMigrate.java:273) 
    at org.flywaydb.core.internal.command.DbMigrate.access$800(DbMigrate.java:53) 
    at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:210) 
    at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:146) 
    at org.flywaydb.core.internal.dbsupport.postgresql.PostgreSQLAdvisoryLockTemplate.execute(PostgreSQLAdvisoryLockTemplate.java:68) 
    at org.flywaydb.core.internal.dbsupport.postgresql.PostgreSQLDbSupport.lock(PostgreSQLDbSupport.java:162) 
    at org.flywaydb.core.internal.metadatatable.MetaDataTableImpl.lock(MetaDataTableImpl.java:174) 
    at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:146) 
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1010) 
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:971) 
    at org.flywaydb.core.Flyway.execute(Flyway.java:1464) 
    at org.flywaydb.core.Flyway.migrate(Flyway.java:971) 
    at org.flywaydb.maven.MigrateMojo.doExecute(MigrateMojo.java:30) 
    at org.flywaydb.maven.AbstractFlywayMojo.execute(AbstractFlywayMojo.java:600) 
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) 
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) 
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) 
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) 
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) 
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) 
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) 
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) 
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) 
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) 
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) 
[ERROR] Unable to release Flyway advisory lock 
org.postgresql.util.PSQLException: This connection has been closed. 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.checkClosed(AbstractJdbc2Connection.java:820) 
    at org.postgresql.jdbc3.AbstractJdbc3Connection.prepareStatement(AbstractJdbc3Connection.java:275) 
    at org.postgresql.jdbc2.AbstractJdbc2Connection.prepareStatement(AbstractJdbc2Connection.java:293) 
    at org.flywaydb.core.internal.dbsupport.JdbcTemplate.prepareStatement(JdbcTemplate.java:319) 
    at org.flywaydb.core.internal.dbsupport.JdbcTemplate.execute(JdbcTemplate.java:247) 
    at org.flywaydb.core.internal.dbsupport.postgresql.PostgreSQLAdvisoryLockTemplate.execute(PostgreSQLAdvisoryLockTemplate.java:81) 
    at org.flywaydb.core.internal.dbsupport.postgresql.PostgreSQLDbSupport.lock(PostgreSQLDbSupport.java:162) 
    at org.flywaydb.core.internal.metadatatable.MetaDataTableImpl.lock(MetaDataTableImpl.java:174) 
    at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:146) 
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1010) 
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:971) 
    at org.flywaydb.core.Flyway.execute(Flyway.java:1464) 
    at org.flywaydb.core.Flyway.migrate(Flyway.java:971) 
    at org.flywaydb.maven.MigrateMojo.doExecute(MigrateMojo.java:30) 
    at org.flywaydb.maven.AbstractFlywayMojo.execute(AbstractFlywayMojo.java:600) 
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) 
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) 
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116) 
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80) 
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51) 
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128) 
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307) 
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193) 
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106) 
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863) 
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288) 
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:498) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415) 
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356) 
+1

你說他們是部分完成的。你有沒有例外?你能提供日誌嗎? – Korgen

+2

您不應該關閉該連接,它由飛路擁有。 –

+0

@Korgen,我可以分享日誌。部分惹眼 - 這只是我的錯誤... –

votes
answers
31 views
+50

如何存儲JDBC服務器,數據庫,用戶名和密碼在NotesDocument的

2

我使用JDBC從EXTLIB在我的XPages應用程序連接到SQL,並有在Webcontent/WEB-INF/JDBC/mssql.jdbc如何存儲JDBC服務器,數據庫,用戶名和密碼在NotesDocument的

JDBC連接文件看起來像這樣和作品大

<jdbc> 
    <driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver> 
    <url>jdbc:sqlserver://server:1433;databaseName=db</url> 
    <user>sa</user> 
    <password></password> 
</jdbc> 

我有必要使這更動態在NotesDocument的存儲服務器名,數據庫,用戶名和密碼,這是可能的,如果是的話怎麼樣?

如果這是不可能的,是否有可能以編程方式更新JDBC文件或使用ExtLib中的其他功能來實現這一點?

+4

托馬斯嗨我們所做的正是這一點,我會盡量在本週找一些時間來分享解決方案 –

+0

謝謝,期待着 –

+0

嘿嘿mas只是讓你知道我沒有忘記這件事。剛剛準備了發佈+文檔,我希望作爲插件供人們測試,可能需要更多天 –

votes
answers
11 views
+50

java.util.Date vs java.sql.Date

java.util.Date vs java.sql.Date: when to use which and why?

votes
answers
23 views
+50

錯誤而使用PostgreTable JDBCUtils的truncateTable方法使用星火

0

我試圖用JDBCUtils截斷表從星火postgre_table,但它拋出下面的錯誤錯誤而使用PostgreTable JDBCUtils的truncateTable方法使用星火

< console>:71: error: value truncateTable is not a member of object org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils

val trucate_table = JdbcUtils.truncateTable()

我使用下面的代碼:

import org.apache.spark.sql.execution.datasources.jdbc._ 
import java.sql.DriverManager 
import java.sql.Connection 

val connection : Connection = DriverManager.getConnection(postgres_host + postgres_database,postgres_username,postgres_password) 

val table_existing = JdbcUtils.tableExists(connection, postgres_host + postgres_database, postgre_table) 
JdbcUtils.truncateTable(connection, postgres_host + postgres_database, postgre_table) 

我能夠刪除表,但不能截斷它。我可以在https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala中看到truncateTable方法

請提出解決方案以及如何在數據框中使用它。

votes
answers
27 views
+50

ExceptionInInitializer錯誤,同時從Teradata表讀取數據使用星火

0

我使用下面的代碼來讀取Teradata的數據,但收到錯誤ExceptionInInitializer錯誤,同時從Teradata表讀取數據使用星火

val jdbcDF = spark.read 
    .format("jdbc") 
    .option("url",s"jdbc:teradata://${TeradataDBHost}/database=${TeradataDBDatabase}") 
    .option("dbtable", TeradataDBDatabase+"."+TeradataDBTable) 
    .option("driver","com.teradata.jdbc.TeraDriver") 
    .option("user", TeradataDBUsername) 
    .option("password", TeradataDBPassword) 
    .load() 

錯誤堆棧跟蹤

Exception in thread "main" java.lang.ExceptionInInitializerError 
      at com.teradata.jdbc.jdbc.GenericTeraEncrypt.getGSSM(GenericTeraEncrypt.java:577) 
      at com.teradata.jdbc.jdbc.GenericTeraEncrypt.<init>(GenericTeraEncrypt.java:116) 
      at com.teradata.jdbc.jdbc.GenericTeradataConnection.<init>(GenericTeradataConnection.java:107) 
      at com.teradata.jdbc.jdbc_4.TDSession.<init>(TDSession.java:186) 
      at com.teradata.jdbc.jdk6.JDK6_SQL_Connection.<init>(JDK6_SQL_Connection.java:36) 
      at com.teradata.jdbc.jdk6.JDK6ConnectionFactory.constructSQLConnection(JDK6ConnectionFactory.java:25) 

Caused by: java.lang.NullPointerException 
     at com.teradata.tdgss.jtdgss.TdgssConfigApi.GetMechanisms(Unknown Source) 
     at com.teradata.tdgss.jtdgss.TdgssManager.<init>(Unknown Source) 
     at com.teradata.tdgss.jtdgss.TdgssManager.<clinit>(Unknown Source) 
votes
answers
28 views
+50

在playframework 2.6中配置多個連接池

0

我在這裏查看文檔:https://www.playframework.com/documentation/2.6.x/ScalaDatabase#How-to-configure-several-data-sources。使用在playframework 2.6中配置多個連接池

# Orders database 
db.orders.driver=org.h2.Driver 
db.orders.url="jdbc:h2:mem:orders" 

# Customers database 
db.customers.driver=org.h2.Driver 
db.customers.url="jdbc:h2:mem:customers" 

,你可以在代碼中引用:

package controllers 
import javax.inject.Inject 

import play.api.mvc.{BaseController, ControllerComponents} 
import play.api.db.{Database, NamedDatabase} 

// inject "orders" database instead of "default" 
class ScalaInjectNamed @Inject()(
    @NamedDatabase("orders") db: Database, 
    val controllerComponents: ControllerComponents 
) extends BaseController { 
    // do whatever you need with the db 
} 

但你如何自定義每個連接的連接池可以定義多個數據庫連接?

根據此文檔:https://www.playframework.com/documentation/2.6.x/SettingsJDBC您可以指定默認配置,數據庫等連接池的原型設置等。我如何定義每個連接池的設置?也許一個連接池只需要一個連接,另一個需要更多連接。

感謝

votes
answers
19 views
+50

How to add local jar files to a Maven project?

How do I add local jar files (not yet part of the Maven repository) directly in my project's library sources?

votes
answers
16 views
+50

Get source JARs from Maven repository

Does anyone have any idea if you can find source JARs on Maven repositories?

votes
answers
26 views
+50

Hosting a Maven repository on github

I have a fork of a small open sourced library that I'm working on on github. I'd like to make it available to other developers via maven, but I don't want to run my own Nexus server, and because it's a fork I can't easily deploy it to oss.sonatype.org.

What I'd like to do is to deploy it to github so that others can access it using maven. What's the best way to do this?

votes
answers
17 views
+50

How to see an html page on github as a normal rendered html page to see preview in browser, without downloading?

On http://github.com developer keep the html, csss , javascript and images files of the project. How i can see html output in browser?

for example this https://github.com/necolas/css3-social-signin-buttons/blob/master/index.html

when i open this it doesn't show the rendered html of the code of author. it shows the page as a source code.

Is it possible to see as rendered HTML directly? otherwise i always need download the whole zipt to just to see the result

votes
answers
25 views
+50

How do I print a list of “Build Settings” in Xcode project?

Alternate Titles

  • List of Xcode build variables
  • Print a list of Xcode Build Settings
  • Clang Environment Variables
  • Canonical list of Xcode Environment Variables

Is there a Canonical list of Xcode Environment Variables that can be used in Build Rules etc?

votes
answers
14 views
+50

Android Word-Wrap EditText text

I have been trying to get my EditText box to word wrap, but can't seem to do it.

I have dealt with much more complicated issues while developing Android applications, and this seems like it should be a straightforward process.

However, the issue remains, and I have a large text box that is only allowing me to enter text on one line, continuing straight across, scrolling horizontally as I enter text.

Here is the XML code for the EditText object from my layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/myWidget48"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
 <ScrollView
    android:id="@+id/myScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    >
    <LinearLayout
        android:id="@+id/widget37"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
    >

<EditText
        android:id="@+id/txtNotes"
        android:layout_width="300px"
        android:layout_height="120px"
        android:scrollbars="vertical"
        android:textSize="18sp"
        android:gravity="left"
        android:layout_marginTop="10dip"
        android:inputType="textCapSentences"
        >
    </EditText>
</LinearLayout>
</ScrollView>
</LinearLayout>
votes
answers
12 views
+50

Node.js version on the command line? (not the REPL)

I want to get the version of node.js on the command line - I'm expecting to run a command like:

node -version

but that doesn't work. Does anybody know what the command line would be? (ie not the REPL)

votes
answers
23 views
+50

Handling renames: svn vs. git vs. mercurial

How do each of these VCS handle renames?

I have found a lot of contradicting information stating that git tracks LOC (lines of code) instead of files, renames would therefore have no meaning for it.

votes
answers
40 views
+50

無法找到softAssert失敗後的元素

0

即使其中一個軟斷言失敗,測試也會繼續。 但在我的情況下,我的測試在軟件斷言失敗後停止,因爲找不到下一個測試元素。無法找到softAssert失敗後的元素

softAssert.assertTrue(p.OtsPage.fName().getAttribute("readonly").equals("true"), "field Name is Editable", "field Name is Read Only"); 
softAssert.assertTrue(p.OtsPage.fEditValue().isEnabled(), "field Edit Value is not Editable", "field Edit Value is Editable"); 

這工作正常,但如果我設置:

softAssert.assertFalse(p.OtsPage.fName().getAttribute("readonly").equals("true"), "field Name is Editable", "field Name is Read Only"); 
softAssert.assertFalse(p.OtsPage.fEditValue().isEnabled(), "field Edit Value is not Editable", "field Edit Value is Editable"); 

我有以下錯誤信息:

org.openqa.selenium.NoSuchElementException。 第二次軟斷言!!!

並停止測試。

環境:Selenium 3.5 + geckodriver + Mozilla 56.0.1。

votes
answers
23 views
+50

distinct或group by by

0

我有一個查詢來檢索oracle數據庫中某些表的數據。distinct或group by by

我最後需要的是獲取所有不重複的數據,爲此我需要所有沒有相同FOLIO,TARJETA,CUENTA和IMPORTE的記錄。 所以,爲此,我嘗試使用Distinct和Group,但我不知道腳本中應該使用哪個/如何使用它,以及它可能在哪裏更有效。

我試圖將GROUP BY與ORDER BY前面的值放在一起,但它表示「不是GROUP BY表達式」。我不想修改查詢,只需刪除重複的參數(FOLIO,TARJETA,CUENTA和IMPORTE)。

SELECT FOLIO_EXP, 
     FOLIO, 
     DOC, 
     REFERENCIA, 
     TARJETA, 
     CUENTA, 
     NOMBRE, 
     IMPORTE, 
     IMP_REC, 
     IMP_REPRE, 
     IMP_QUEB, 
     FECHA_PAGO, 
     MCC, 
     COMERCIO, 
     PCC, 
     FECHA_COM, 
     ADQUIRENTE, 
     ESTADO, 
     "TIPO DE FRAUDE", 
     F_FRAUDE, 
     F_RECLAMO, 
     F_REEMBOLSO, 
     DICAMINO 
FROM 
    (SELECT E.FOLIO_EXP, 
      A.FOLIO, 
      'D' AS DOC, 
      A.REFERENCIA, 
      A.TARJETA, 
      A.ACCT_NUM AS CUENTA, 
      B.NOMBRE_TH AS NOMBRE, 
      TO_CHAR(A.MONTO,'999,999.99') IMPORTE, 
      D.IMP_REC, 
      F.IMP_REPRE, 
      DECODE((A.MONTO -D.IMP_REC),NULL,A.MONTO,(A.MONTO -D.IMP_REC)) AS IMP_QUEB, 
      D.FECHA_PAGO, 
      A.SIC_CDE AS MCC, 
      A.COMERCIO, 
      C.PCC, 
      C.FECHA_COM, 
      C.ADQUIRENTE, 
      C.ESTADO, 
      'INTERNET' AS "TIPO DE FRAUDE", 
      A.FECHA_TRANS AS F_FRAUDE, 
      A.FECHA_RECLAMO AS F_RECLAMO, 
      A.FECHA_BONIFICACION AS F_REEMBOLSO, 
      A.USUARIO AS DICAMINO 
    FROM OPPF.T00EMISOR A 

    LEFT JOIN 
    (SELECT A.FECHA, 
      A.TARJETA, 
      C.PCC, 
      C.FECHA_COM, 
      C.ADQUIRENTE, 
      C.ESTADO 
     FROM 
     (SELECT TARJETA, 
       MAX(FECHA_INFO) FECHA 
     FROM OPPF.T00_PCC 
     GROUP BY TARJETA) A 
     LEFT JOIN 
     (SELECT FECHA_INFO, 
       TARJETA, 
       PCC, 
       FECHA_COM, 
       ADQUIRENTE, 
       ESTADO 
     FROM OPPF.T00_PCC)C ON(A.TARJETA = C.TARJETA 
           AND A.FECHA = C.FECHA_INFO)) C ON(TO_CHAR(C.TARJETA) = TO_CHAR(A.TARJETA)) 

    LEFT JOIN 
    (SELECT MAX(SE_REVISO) SE_REVISO, 
      NOMBRE_TH, 
      TARJETA 
     FROM OPPF.T00CASOSRESUELTOS 
     GROUP BY TARJETA, 
       NOMBRE_TH) B ON(SUBSTR(A.TARJETA,1,16) = SUBSTR(B.TARJETA,1,16) 
           AND A.FECHA_BONIFICACION = B.SE_REVISO) 
    LEFT JOIN 
    (SELECT MAX(FECHA_PAGO) FECHA_PAGO, 
      TARJETA, 
      REFERENCIA, 
      COUNT(REFERENCIA) N, 
      SUM(MONTO_LIQ) AS IMP_REC--, FECHA_TRXS 

     FROM OPPF.T00_CC_RECUP 
     GROUP BY TARJETA, 
       REFERENCIA, 
       FECHA_TRXS) D ON(TO_CHAR(D.TARJETA) = TO_CHAR(A.TARJETA) 
           AND D.REFERENCIA = A.REFERENCIA) 
    LEFT JOIN 
    (SELECT TARJETA, 
      COUNT(TARJETA) TRANS, 
      COUNT(REFERENCIA) NR, 
      REFERENCIA, 
      SUM(IMPORTE) IMP_REPRE 
     FROM OPPF.T00_REPRESENTACIONES 
     GROUP BY TARJETA, 
       REFERENCIA) F ON(A.TARJETA = F.TARJETA 
           AND LPAD(TO_CHAR(A.REFERENCIA),23,'0') = LPAD(TO_CHAR(F.REFERENCIA),23,'0')) 
    LEFT JOIN 
    (SELECT MIN(FOLIO) FOLIO_EXP, 
      TARJETA, 
      FECHA_BONIFICACION 
     FROM OPPF.T00EMISOR --WHERE FECHA_BONIFICACION BETWEEN '02/09/2015' AND '31/12/2015' 

     GROUP BY FECHA_BONIFICACION, 
       TARJETA 
     ORDER BY FECHA_BONIFICACION, 
       TARJETA, 
       FOLIO_EXP) E ON(E.TARJETA = A.TARJETA 
           AND E.FECHA_BONIFICACION = A.FECHA_BONIFICACION) 
    WHERE A.ENTRY_MODE IN (' ', 
          '1', 
          '01', 
          '001', 
          '0', 
          '00', 
          '012', 
          '010', 
          '12', 
          '10', 
          '11', 
          '011')) 
WHERE F_REEMBOLSO = '04/07/2017' 

ORDER BY FOLIO, 
     REFERENCIA 
+2

我相信你會得到解釋'DISTINCT'給你的答案。我只想評論一下,在大多數SQL查詢中,真正重複的記錄是設計不佳的數據模型和/或寫得不好的查詢的標誌。可能9次出10次,當我在初學者的代碼中看到「DISTINCT」關鍵字時,它是一個能夠掩蓋真正問題的創可貼。您可能想問自己:爲什麼我會首先獲取重複記錄? –

+0

是的,它的設計不好,客戶端軟件使用不好,都會影響數據 – arnoldssss

+1

鑑於查詢的可怕程度,@MatthewMcPeak是正確的:由於您的查詢定義不明確,您獲取「重複」記錄連接和過濾器。很顯然[你之前關於連接複雜性的問題](https://stackoverflow.com/q/47984589/146325)表明你知道這一點。但是,除非你能解釋產生這個怪物的業務邏輯,否則我們不能幫你重寫它。 – APC

votes
answers
16 views
+50

How to format code in Xcode? [duplicate]

This question already has an answer here:

I wonder how can I format my code to align it neatly? Does it have a feature similar to Eclipse's ctrlshiftf?

votes
answers
27 views
+50

如何接收LocalDate作爲參數

2

我想插入一個簡單的對象到數據庫,但在我的控制器上,我無法發送LocalDate參數。如何接收LocalDate作爲參數

錯誤說malformed request syntax, invalid request message framing, or deceptive request routing我很確定這個參數是LocalDate造成的。

我控制器

@RequestMapping(value = "/finance",method = RequestMethod.POST) 
    public String postFinance(@ModelAttribute("finance") 
     Finance finance, Model model){ 
     financeServices.targetActivate(finance); 
     model.addAttribute("targetSetStatus",true); 
     return "finance/finance"; 
} 

金融實體

@Entity 
public class Finance { 


    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    private LocalDate targetDate; 
    private Double targetAmount; 
    private LocalDate createdDate; 

     //getter setters // 

} 

編輯: - 我試圖從形式插入,所以我的形式看起來像: -

<form class="form-horizontal" id="productForm" 
th:action="@{/finance}" method="post"> 

     <div class="form-group"> 
      <div th:if="${targetSetStatus}"> 
       <div class="alert alert-success"> 
          <p>New Target Has Been Set</p> 
       </div> 
      </div> 
     </div> 

     <div class="form-group"> 
       <label class="control-label col-sm-3" 
       for="targetAmount">Target Amount:</label> 
      <div class="col-sm-9"> 
       <input type="number" class="form-control" 
           placeholder="Targeted Amount" 
           name="targetAmount" id="targetAmount"> 
     </div> 
     </div> 
     <div class="form-group"> 
      <label class="control-label col-sm-3" 
      for="targetDate">Target Date:</label> 
      <div class="col-sm-9"> 
      <input type="date" class="form-control" 
           placeholder="Targeted Date" 
           name="targetDate" id="targetDate"> 
     </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-sm-offset-3 col-sm-9"> 
       <button type="submit" class="btn btn-default">Set Target</button> 
     </div> 
    </div> 
</form> 

如果我用java.util.Date代替LocalDate它可以工作,但我想使用LocalDate它提供的java 8 API。

+1

基地支持在未來的未來,請參閱[拉入請求和分辨率(https://github.com/spring-projects/spring-boot/pull/9930)。與此同時,[看到這個問題](https://stackoverflow.com/questions/44924656/how-to-register-global-databinding-for-localdate-in-spring-mvc)。 –

votes
answers
11 views
+50

run main class of Maven project [duplicate]

This question already has an answer here:

I've created a simple console Java application that is built with Maven. Is there a way that the main class (which doesn't require any arguments) can be run from the command-line using a maven command like:

mvn run-app com.example.MainClass
votes
answers
14 views
+50

如何在顯示列表後刪除方括號?

1

我聲明ArrayList如何在顯示列表後刪除方括號?

ArrayList<ArrayList<String>> usersList1234 = new ArrayList<ArrayList<String>>(); 和listview。

我ArrayList中設定的ListView下列方式:

ArrayAdapter adapter = new ArrayAdapter<>(SearchFriendsActivity.this, android.R.layout.simple_list_item_1, usersList1234); 
     this.allUsers.setAdapter(adapter); 

我的列表中有相當多的元素(每個元素有三個領域,這是它的外觀:

Image1

Image2

在虛擬Android設備上查看時,它看起來像這樣()

[文本,文本,文本]

[文本1,文本1,文本1]

[文本2,文本2,文本2]

有沒有辦法來消除這些方括號?

+2

括號存在是因爲內部數組列表正在通過數組列表的默認toString方法打印。如果您想要自定義視圖,請使用您自己的佈局並製作自己的適配器,以根據需要顯示連接 – Kushan

votes
answers
15 views
+50

找到行數的最快方法?

4

我現在使用什麼:找到行數的最快方法?

numlines := strings.Count(editor.Text(), "
") 
fmt.Print(strconv.Itoa(numlines)) 
message.SetText(strconv.Itoa(numlines)) 

這是每當一個文本框更新運行。最類似這樣做的方式是什麼?

votes
answers
16 views
+50

Remove last character from C++ string

How can I remove last character from a C++ string?

I tried st = substr(st.length()-1); But it didn't work.

votes
answers
21 views
+50

谷歌存儲python API - 上傳一個StringIO對象

0

我成功地將文件上傳到谷歌存儲,但我想跳過創建一個文件,並使用StringIO而不是直接在谷歌存儲上創建文件。谷歌存儲python API - 上傳一個StringIO對象

由於我是新來的蟒蛇,我只是想用我用於上傳所創建的文件的標準方法:

def cloud_upload(self, buffer, bucket, filename): 
    buffer.seek(0) 
    client = storage.Client() 
    bucket = client.get_bucket(bucket) 
    blob = bucket.blob(filename) 
    blob.upload_from_filename(buffer) 

但我得到的錯誤:

類型錯誤:預期字符串或緩衝區

但是因爲我給了它的StringIO對象,我不知道爲什麼這不起作用?

votes
answers
20 views
+50

將存儲的包含html標籤的字符串轉換爲html文本格式

1

我有一個存儲Firebase數據的Angular項目。數據以字符串形式存儲在數據庫中(prdName: string;)。我想問一下,如果我在像<b>this is text</b>這樣的字符串中加入了一個html標記並將其存儲,然後將它們綁定/查看爲html文本格式,是否有可能? (文字成爲粗體)將存儲的包含html標籤的字符串轉換爲html文本格式

firebase

//service.ts 
 
getData() { 
 
    this.List = this.firebase.list('Product'); 
 
    return this.List; 
 
} 
 

 
insertProduct(Product: Product) { 
 
    this.productList.push({ 
 
    prdName: Product.prdName, 
 
    prdCategory: Product.prdCategory, 
 
    prdSup: Product.prdSup, 
 
    prdImage: Product.prdImage, 
 
    prdDescription: Product.prdDescription 
 
    }); 
 
}

//component.ts 
 
ngOnInit() { 
 
    var x = this.ListService.getData(); 
 
    x.snapshotChanges().subscribe(item => { 
 
    this.List = []; 
 
    item.forEach(element => { 
 
     var y = element.payload.toJSON(); 
 
     y["$prdKey"] = element.key; 
 
     this.List.push(y as List); 
 
    }); 
 
    }); 
 
}
<!--component.html--> 
 
<label>Product Name: </label> {{ListService.selectedProduct.prdName}}

請讓我知道,如果需要更多的片段。非常感謝你提前。

votes
answers
38 views
+50

使用子字符串R查找字符串R

3

我有一長串字符串,它們共享子字符串。該列表來自事件流數據,因此有成千上萬行,但我會簡化這個例子;寵物:使用子字符串R查找字符串R

+--------------------------------+ 
|    Pets    | 
+--------------------------------+ 
| "one calico cat that's smart" | 
| "German Shepard dog"   | 
| "A Chameleon that is a Lizard" | 
| "a cute tabby cat"    | 
| "the fish guppy"    | 
| "Lizard Gecko"     | 
| "German Shepard dog"   | 
| "Budgie Bird"     | 
| "Canary Bird in a coal mine" | 
| "a chihuahua dog"    | 
+--------------------------------+ 
dput output: structure(list(Pets = structure(c(8L, 6L, 1L, 3L, 9L, 7L, 6L, 4L, 5L, 2L),.Label = c("A Chameleon that is a Lizard", "a chihuahua dog", "a cute tabby cat", "Budgie Bird", "Canary Bird in a coal mine", "German Shepard dog", "Lizard Gecko", "one calico cat that's smart", "the fish guppy"), class = "factor")), .Names = "Pets", row.names = c(NA, -10L), class = "data.frame") 

我想基礎上,通用型寵物(狗,貓等)添加信息,我有保留此信息一鍵表:

+----------+----------------+ 
| key | classification | 
+----------+----------------+ 
| "dog" | "canine"  | 
| "cat" | "feline"  | 
| "lizard" | "reptile"  | 
| "bird" | "avian"  | 
| "fish" | "fish"   | 
+----------+----------------+ 
dput output: structure(list(key = structure(c(3L, 2L, 5L, 1L, 4L), .Label = c("bird", "cat", "dog", "fish", "lizard"), class = "factor"), classification = structure(c(2L, 3L, 5L, 1L, 4L), .Label = c("avian", "canine", "feline", "fish", "reptile"), class = "factor")), .Names = c("key", "classification"), row.names = c(NA, -5L), class = "data.frame") 

怎麼辦我使用Pets表中的「長字符串」在密鑰表中查找相關的classification?問題是,我的查找字符串包含在密鑰表中找到的子字符串。

我用grepl這樣開始:

key[grepl(pets[1,1], key[ , 2]), ] 

但是,這是行不通的,因爲「三色貓」是不是在鍵列表,雖然「貓」是。我正在尋找的結果將是「feline」。 (注意:我不能簡單地切換事物,因爲在我自己的代碼中,它位於一個apply函數中,並且循環遍歷數據中的每一行。所以,而不是pets[1,1]它是pets[n,1]最後我打算cbind對事件流數據的結果做進一步分析。)

我在繞包裝如何做到這一點時遇到了麻煩。有什麼建議?

+0

看來,鍵總是每個「長字符串」的第二個字。這是一個合理的假設嗎? – useR

+0

不幸的是,沒有。字符串有幾個到幾個不同的單詞。我只知道「關鍵」字在那裏。 – JoeM05

+1

然後你應該提供一個不符合這個假設的長字符串。此外,請提供您的數據集,並將'dput(my_data)'的輸出複製並粘貼到您的問題中,而不是您目前如何格式化它的數據集 – useR

votes
answers
4 views
+50

Simple way to repeat a String in java

I'm looking for a simple commons method or operator that allows me to repeat some String n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.

String str = "abc";
String repeated = str.repeat(3);

repeated.equals("abcabcabc");

Related to:

repeat string javascript Create NSString by repeating another string a given number of times

Edited

I try to avoid for loops when they are not completely necessary because:

  1. They add to the number of lines of code even if they are tucked away in another function.

  2. Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".

  3. Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".

  4. They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.

  5. For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.

  6. For loops increase the number of places a bug hunter has to look.

votes
answers
25 views
+50

的Python,BeautifulSoup4:其中多個屬性等於多個值中選擇的元素分別

-1
<TABLE cellSpacing=0 cellPadding=0 width=700 border=0 617px; HEIGHT: 22px 23px 536px;> 
    ... 
</TABLE> 

我想選擇的所有元素就像以上:所述標籤是TABLE,並且有幾個屬性(cellSpacing=0,cellPadding=0,width=700,border=0)。的Python,BeautifulSoup4:其中多個屬性等於多個值中選擇的元素分別

我嘗試以下Python腳本:

import requests 
from bs4 import BeautifulSoup 
result=requests.get("http://news.scu.edu.cn/news2012/cdzx/I0201index_1.htm") 
result.encoding="GBK" 
soup=BeautifulSoup(result.text,"html.parser") 
soup=soup.find("TABLE",attrs={"cellspacing":"0","cellpadding": "0","width": 
"700","border":"0"}) 
print(soup) 

沒有錯誤的腳本運行,但美麗的湯發現nothing.This一定是錯誤的,如果你打開的網頁(http://news.scu.edu.cn/news2012/cdzx/I0201index_1.htm)與瀏覽器,點擊右鍵,去檢查 - >網絡 - >文檔 - >響應,搜索<TABLE cellSpacing=0 cellPadding=0 width=700 border=0 617px; HEIGHT: 22px 23px 536px;>,您會發現30條匹配結果。

votes
answers
13 views
+50

訂閱中不能分配數據

0

我有一些Post方法的問題。我總是在我的temporarySegment中獲得空的segmentdata對象。我用數字做同樣的方式,這是工作。變量導致訂閱是SegmentData,並在console.log中收到預期的響應。這怎麼可能? 我的方法:訂閱中不能分配數據

onGetSegmentsClick(size: number) { 
    debugger; 
    if (size > 0) { 
     let counter = 0; 
     let temporarySegment = new SegmentData(); 
     while (counter < size) { 
      this.segmentService.getSegment(counter + 1, this.elementId, this.documentId).subscribe(result => { 
       console.log("get segment request is sended"); 
       temporarySegment = result; 
       console.log("gotten message is:", result); 
      }); 
      ModalComponent.segmentsCollection.push(new SegmentData()); 
      ModalComponent.segmentsCollection[ModalComponent.segmentsCollection.length - 1] = 
       ModalComponent.newer.TemporaryObjectEqualizer(temporarySegment); 
      ModalComponent.segmentsCollection[ModalComponent.segmentsCollection.length - 1].SegmentDataId = 
       counter + 1; 
      counter++; 
     } 
    } 
} 

我getSegment方法:

getSegment(segmentId: number, elementId: string, documentId: string) { 
    let headers = new Headers(); 
    headers.append("Content-type", "application/json"); 
    let input = { 
     "elementId": elementId, 
     "documentId": documentId, 
     "segmentNumber": segmentId 
    } 
    let sendingData = JSON.stringify(input); 
    let urlPost = "https://localhost:44375/api/data/SendSegmentData"; 
    let output = new AsyncSubject<SegmentData>(); 
    let options = new RequestOptions({ 
     headers: headers, 
     method: RequestMethod.Post, 
     url: urlPost 
    }); 
    this.http.post(urlPost, sendingData, options) 
     .subscribe(result => { 
      output.next(result.json()); 
      output.complete(); 
     }); 
    return output; 
} 

類SegmentData客戶端等於在服務器上的相關類。我的回答完美解析。如何解決這個問題? 提前致謝))

+0

您需要了解異步。當你訂閱()時,你發送一個請求。然後while循環中的其餘代碼立即執行。很久以後,異步地,當數千公里以外的服務器處理請求並且服務器已經發迴響應時,您傳遞給訂閱的回調函數被執行。因此,在發送請求後,您無法立即訪問響應中的值。把它放入烤麪包機後,你不能立即吃烤麪包片。烤麪包機告訴你它已經準備好了,你需要吃。 –

+0

謝謝,但如何等到響應回來? –

+0

你不要等待。您將需要訪問響應的代碼放入傳遞給subscribe()的回調中。 –

votes
answers
23 views
+50

SBT無法找到的Java

0

當我嘗試推出SBT,我得到以下信息:SBT無法找到的Java

~(501)$sbt 
(standard_in) 1: parse error 

No java installations was detected. 
Please go to http://www.java.com/getjava/ and download 

然而,Java和斯卡拉安裝

~(508)$java -version 
java version "1.8.0_65" 
Java(TM) SE Runtime Environment (build 1.8.0_65-b17) 
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode) 

這是斯卡拉

~(503)$scala 
Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 9.0.1). 
Type in expressions for evaluation. Or try :help. 

scala> 

而且你可以在路徑中找到它們

Java的路徑

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home/"  
export PATH=$PATH:"/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home/" 

SBT路徑

export SBT_HOME="/usr/local/Cellar/sbt/1.0.3/bin/" 
export PATH=$PATH:$SBT_HOME 

和Scala路徑

export SCALA_HOME="/usr/local/opt/scala/idea" 
export PATH=$PATH:$SCALA_HOME/bin 

我跑所有這些在MAC OS塞拉利昂v10.12.6 我感謝所有幫助。提前致謝。

votes
answers
21 views
+50

有沒有辦法將字符串jsx轉換爲React組件級別的反應本機?

0

我試圖從某個服務器轉換「hello」字符串以在React Native中呈現。有沒有辦法將字符串jsx轉換爲React組件級別的反應本機?

但即使刪除引號後,它也不會呈現。即使在刪除引號後,「hello」的類型也是「字符串」。看起來'對象'必須被插入到渲染函數中。

有什麼辦法可以試試嗎?看世博會的例子,網絡客戶端收到基本上產生實際應用程序的代碼行,我想可能有一些方法。

請與我分享任何想法!

votes
answers
15 views
+50

PostgreSQL syntax check without running the query

I want to verify the syntax of files containing sql queries before they can be committed in my CVS project.

In order to do that, I have a commitinfo script, but I have trouble finding out if the sql commands are valid. psql does not seem to have a dryrun mode, and constructing my own postgresql-dialact tester from the grammar (that is in the source) seems like a long stretch.

The scripts may contain multiple queries, so an EXPLAIN cannot be wrapped around them.

Any hints?

votes
answers
31 views
+50

如何找到遞歸語法的FIRST和FOLLOW集?

0

假設我有以下CFG:如何找到遞歸語法的FIRST和FOLLOW集?

S-> AACD | BcAe

A-> B | EPSILON

B-> cf | d

C-> FE

現在我敷在CFG的第一個規則:

FIRST(S)= FIRST(AACD)U FIRST(BcAe)

= {A} U FIRST(BcAe)

= {A} U FIRST(B) - {EPSILON} U FIRST(CAE)

= {A} U FI RST(B) - {EPSILON} U {C}

= {A} U FIRST(CF)U FIRST(d) - {EPSILON} U {C}

= {A,F,d, C,EPSILON}

FIRST(A)= FIRST(b)U FIRST(EPSILON)= = {b,EPSILON}

FIRST(b)= FIRST(CF)U FIRST(d)= {d中,f}

FIRST(C)= FIRST(FE)= {F}

現在我申請對CFG的FOLLOW規則:

FOLLOW(S)= {$}

FOLLOW(A)= {C,E}

FOLLOW(B)= {C}

FOLLOW(C)= {f}

有什麼不對嗎?如果不對,請告訴我該怎麼做。

+0

「我做完了我的功課嗎?」與堆棧溢出不匹配。如果你有一個關於算法的具體問題,你可以試着問一下,儘管這樣的問題很可能不在SO的範圍內,因爲它與編程很少或者沒有關係。 – rici

+0

@SourodipKundu這是錯的。它不是答案。 – Billa

+0

@SourodipKundu請檢查生產是否與我的問題相同。並且由於'C'在生產體S-> aACD中,'FOLLOW(C)'是'FIRST(D)'。由於'FIRST(D)'是'EPSILON',所以'EPSILON'替代'S-> aACD'中的'D'。所以它變成'S-> aAC'然後取'FOLLOW(C)',然後變成'FOLLOW(S)'這是'$'。我認爲你缺乏基礎知識,請參考我在答案中提出的視頻。 – Billa

votes
answers
14 views
+50

如何通過Angular 4中的字符串解析對象

0

我需要通過字符串鍵來解析對象,就像AngualarJS $解析服務一樣。 我有一個對象如何通過Angular 4中的字符串解析對象

message = { 
    text: 'msome text', 
    userFrom: { 
    name: 'Alex' 
    } 
} 

而且我有一個字符串「userFrom.name」

如何我可以通過使用一些角4服務「userFrom.name」字符串獲得message.userFrom.name價值?

在AngularJS這是可以做到這樣的:

$parse("userFrom.name")(message) === 'Alex'; 
+0

你可以添加一些更多的情況下你的問題。你想達到什麼目的? – Flaugzig

votes
answers
10 views
+50

JSONException: Value of type java.lang.String cannot be converted to JSONObject

I have a JSON file with 2 JSON-Arrays in it: One Array for routes and one Array for sights.

A route should consist of several sights where the user gets navigated to. Unfortunately I am getting the error:

JSONException: Value of type java.lang.String cannot be converted to JSONObject

Here are my variables and the code that parses the JSON-File:

private InputStream is = null;
private String json = "";
private JSONObject jObj = null;

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "
");
    }
    is.close();
    // hier habe ich das JSON-File als String
    json = sb.toString();
    Log.i("JSON Parser", json);
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;
}

Log.i("JSON Parser", json); shows me that at the beginning of the generated string there is a strange sign: enter image description here

but the error happens here:

try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data org.json.JSONException: Value //STRANGE SIGN HERE // of type java.lang.String cannot be converted to JSONObject

anybody has a clue on how to get rid of these signs in order to create the JSONObject?

votes
answers
26 views
+50

或拆分功能不能嵌套工作

1
case1 = """ do some test 
here""" 
case2 = """ do some test2 
here""" 

print(case1.split("some")[1].split('
|,')[0]) 

既不 也不,在這裏工作。或拆分功能不能嵌套工作

輸出應該

test 

但它給我

test, 
here 
+2

'split'並不需要一個正則表達式。 –

votes
answers
23 views
+50

Java拆分(「\ |」)不適用於空間字符串

1

對於下面的輸入im期望所有以「|」分隔的字符串在數組中可用。但只有第一個字符串可用,下一個字符串部分可用,其餘字符串根本不可用。請幫助我理解它。我探索了所有幫助文檔和以前的stackoverflow的東西,但無法解決它。我嘗試了split(String regex,int limit),但沒用。我不想取代空白,因爲我需要保留該空白。Java拆分(「 |」)不適用於空間字符串

輸入 「1 |紐約| 1345 | 134 | 45634」 預期成果是:1,紐約,1345,134,45634 實際輸出爲:1,新

public class test1 { 

    public static void main(String[] args) { 

     Scanner scanner = new Scanner(System.in); 
     String strinp=scanner.next(); 
     //System.out.println(strinp.replaceAll(" ", "")); 
     String[] strArr=strinp.split("\|"); 
     //System.out.println(Arrays.deepToString(strArr)); 
     for (String s:strArr) { 
      System.out.println(s); 

     } 
    } 

} 
+0

嗯,這個在這裏產生的預期輸出: 字符串strinp =「1 |紐約| 1345 | 134 | 45634「; String [] strArr = strinp.split(「\ |」); (String s:strArr){ System.out.println(s); } –

+0

public static void main(String [] args){ Scanner scanner = new Scanner(System.in); String strinp = scanner.nextLine(); strinp = strinp.replace('|',','); System.out.println(strinp); } 輸入: 「1 |紐約| 1345 | 134 | 45634」 輸出: 「1,紐約,1345,134,45634」 –

votes
answers
37 views
+50

我怎麼能編碼MATLAB中的一些元素?

1

我做了兩個隨機數從0到3我怎麼能編碼MATLAB中的一些元素?

a=0; 
b=3; 
A=round(a+(b-a)*rand(1,1000)); 
B=round(a+(b-a)*rand(1,1000)); 

然後我他們中的每兩位補充。然後我將其轉換爲二進制文件。

SUM = A + B; 
binarySum = dec2bin(SUM); 

,因爲我想算的轉變,我寫這樣的代碼:

s = 1; 
for i = 1:1000 
    for j = 1:3 
     M(1,s) = binarySum(i,j); 
     s = s+1; 
    end 
end 
Tr = sum(diff(M)~=0); 

現在我想M的每3個元件分開,並對其進行編碼通過另一種元素。例如000到000000,110通過000001,001通過00001,100通過0001,101 001,010通過01,011由1

我用這個方法,但它不工作。它有什麼問題?

Lookup_In = [ 000  110  001 100 101 010 011 ] ; 
Lookup_Out = {'000000','000001','00001','0001','101','01','1' } ; 
StrOut = repmat({'Unknown'},size(M)) ; 
[tf, idx] =ismember(M, Lookup_In) ; 
StrOut(tf) = Lookup_Out(idx(tf)) 
votes
answers
25 views
+50

如果有積極的lookahead和積極的lookbehind而不是分隔符,我該如何分割一個字符串?

3

例子:如果有積極的lookahead和積極的lookbehind而不是分隔符,我該如何分割一個字符串?

s = "Thisissometext andthisissometext" 

我想之間的文本拆分 「是」 和 「一些」:

["Thisis", "sometext andthisis", "sometext"] 

如果我這樣做:

re.split("(?<=is)s(?=ome)", s) 
--> ['Thisis', 'ometext andthisis', 'ometext'] 

沒有 'S'

如果我這樣做

re.split("(?<=is)(s)(?=ome)", s) 
--> ['Thisis', 's', 'ometext andthisis', 's', 'ometext'] 

如果我這樣做

re.split("(?<=is)(?=some)", s) 
--> ValueError: split() requires a non-empty pattern match. 

我怎麼可以拆分如果沒有分隔字符串?

votes
answers
7 views
+50

Parse (split) a string in C++ using string delimiter (standard C++) [duplicate]

This question already has an answer here:

I am parsing a string in C++ using the following:

string parsed,input="text to be parsed";
stringstream input_stringstream(input);

if(getline(input_stringstream,parsed,' '))
{
     // do some processing.
}

Parsing with a single char delimiter is fine. But what if I want to use a string as delimiter.

Example: I want to split:

scott>=tiger

with >= as delimiter so that I can get scott and tiger.

votes
answers
24 views
+50

如何使用JSTL函數將數字字符串拆分fn:split?

0

我有字符串filename3333。我需要將此字符串拆分爲兩個單獨的字符串filename3333。我想這與Fn鍵分裂:分裂這樣的:如何使用JSTL函數將數字字符串拆分fn:split?

<c:set var = "filenameParts" value = "${fn:split(filename, 'REGEX')}" /> 

是否有可能與JSTL FN做到這一點:通過使用正則表達式或類似的東西的功能?

votes
answers
33 views
+50

當焦油和分裂時使用所有核心

0

我想讓我的tar命令使用所有內核(8),當我打包到如下所示的單個包中時,我得到它的工作:tar -I pigz -cf packed.tar.gz folder/。 它正在工作,它使用所有內核。當焦油和分裂時使用所有核心

但是,當我需要打包成多個文件時,我無法使用它來使用所有內核,這是我的命令:tar cvzf - folder/ | split --bytes=4GB - packed.tar.gz。 如何讓這個命令使用所有核心而不僅僅是一個?

感謝您的所有意見。

votes
answers
28 views
+50

自定義類不會過濾掉行尾字符或空白

2

可能與問題3100585模糊相關。自定義類不會過濾掉行尾字符或空白

以下類的目的是獲取包含一行Java源代碼的字符串,並將其劃分爲將由單獨的類進一步分析的令牌字符串。 split方法中顯示的正則表達式將字符串除以運算符字符和空白,保留所有字符,然後該類遍歷結果數組並刪除所有空白字符和行尾字符。然後它將數組轉換成一個ArrayList並返回它。

public class Lexer { 

Lexer() { 
} 

public List<String> convertStringToTokens(String input) { 
    input = input.trim(); 

    String[] result = input.split("(?<=[-+*/=s<>()])|(?=[-+*/=s<>()])"); 
    List<String> resultList = new LinkedList<>(Arrays.asList(result)); 

    for (Iterator<String> iterator = resultList.iterator(); iterator.hasNext();) { 
     String string = iterator.next(); 
     if (string.isEmpty() || string.matches("\u000A") || string.matches("\u000D") || string.matches(" ") || string.matches("\u000B")) { 

       iterator.remove(); 
      } 
     } 

     return resultList; 
    } 
} 

不幸的是,班級沒有履行預期的角色,我不確定的原因。

最有可能的正則表達式在這裏是錯誤的。

如果有人知道我在這發生了什麼問題,請通知並告知。

編輯:輸入是單個字符串,如「Sphere s = new Sphere(16);」。輸出是一個字符串的ArrayList,(最多)長度爲兩個字符串,其中對於上述輸入將是

{"Sphere s = new Sphere(16",");"}. 

(右括號的分離形成參數意圖。順便說一下,會有人知道如何將參數與左括號分開?)

+0

你能提供樣品輸入如你預期它是不工作的輸出? – murraybo

votes
answers
23 views
+50

在不破壞封裝的情況下調用不同對象的方法

1

我有一個對象GameLogic,它有一個Player(接口)對象。在不破壞封裝的情況下調用不同對象的方法

GameLogic有一個方法getAvailableMoves()它用於內部GameLogicPlayer知道他可以移動。

我目前正在執行一個AIPlayer(執行Player),它應該使用Minimax算法作爲策略。爲了實現這一點,我希望能夠從AIPlayer內部使用GameLogicgetAvailableMoves()方法。但是,我希望在不破壞封裝的情況下做到這一點。也就是說,我試圖避免傳遞GameLogic作爲參考Player

這種情況下適合的解決方案是什麼?我假設我應該使用設計模式,但我不確定哪一個。

+0

您將需要一個服務類。 – SynchroDynamic

votes
answers
21 views
+50

Design patterns that every developer must know?

What are the design patterns that every developer must know?

I'm interested in the context of Java web developers working with Spring & Hibernate. I have often heard that good knowledge in design patterns is essential for working with those frameworks. Can anyone list the specifics?

For example, I know that understanding abstract factory & factory pattern, singleton pattern etc is absolutely essential. I'm looking for a comprehensive list.

votes
answers
32 views
+50

CSS旋轉取決於寬度/固定像素值

1

TLDR:我想實現這一目標爲可伸縮的解決方案: triangle with gradient and patternCSS旋轉取決於寬度/固定像素值

較長的解釋: 目標是有一個與一個梯度作爲背景旋轉的刻度。但問題是旋轉不能定義爲deg,因爲它根據瀏覽器寬度而變化。所以元素應該是100%寬度的瀏覽器,其左側的的固定高度爲,而右側的固定高度爲固定的較低高度。

基本上,這可以很容易地完成只有水平伸展的圖像背景。唯一的問題是,應該有也應該在同一地區被裁剪的圖案覆蓋,這應該重複和不舒展(你可以看到這些圖案由等於盒)

所以我的想法是:是是否可以旋轉特定目標像素的元素?

當前的例子:

.triangleClipper { 
    height: 100px; 
    overflow: hidden; 
} 

.designElement { 
    background: linear-gradient(to right, #03cc65, #fbfe02); 
    height: 100px; 
    width: 200%; 
    transform-origin: top left; 
    transform: rotate(-2deg); 
    margin-top: -60px; 
} 

https://jsfiddle.net/0egg320q/ 您調整瀏覽器時,看到右側邊緣的問題。所以在寬屏幕上,你會看到三角形的末端和小屏幕太高。目標是在每個瀏覽器大小的左右邊緣上保持相同的高度。

歡迎任何其他想法。

votes
answers
29 views
+50

用於處理未來更改的java類設計

-2

如果收到的對象[json或excel文件]有10個字段。從10個領域,4個穩定,6個領域和他們的名字正在改變。可能會從給定的6個字段中刪除字段,並且可能會添加新的字段。如何設計課程或在將來進行最小變化的情況下處理此類案例用於處理未來更改的java類設計

+0

也許只是使用地圖。 –

+0

如果由子訪問的地圖可以修改。我不想讓任何人改變穩定的字段名稱。 – user3401717

+0

你可以使它成爲一個不可改變的地圖 –

votes
answers
22 views
+50

MVC Java遊戲中的聲音放在哪裏?

0

我正在使用MVC設計模式,現在我想播放一些聲音。我應該在哪裏使用代碼播放音頻聲音? MVC的哪一層?MVC Java遊戲中的聲音放在哪裏?

某些聲音應該在用戶按下某個鍵後播放,因此可以將其包含在控制器中。然而,一些聲音只是在一段時間後才播放,沒有用戶交互,只有模型知道這種變化。但是,在模型中發出聲音聽起來像一個壞主意,所以...它如何解決?

+0

你是指聲音文件本身?或控制聲音播放的邏輯? –

+0

邏輯,代碼本身:) –

votes
answers
21 views
+50

C++ Singleton design pattern

Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real life example):

// a lot of methods are omitted here
class Singleton
{
   public:
       static Singleton* getInstance( );
       ~Singleton( );
   private:
       Singleton( );
       static Singleton* instance;
};

From this declaration I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem in the implementation.

My main question is, how do I implement it in the right way?

votes
answers
28 views
+50

如何計算,控制客戶信用並更新它?

2

我有一個財務系統,我必須設計一個保存,更新和控制限制的模塊。 您可以知道每個客戶都有一個用戶ID,每個用戶ID具有每天最高的信用額度。例如,UserID = 12具有MaxAmountPerDay = 10 $CurrentAmountPerDay如何計算,控制客戶信用並更新它?

起初,我想設計一個簡單的模塊和定義表如下:

User ID | MaxAmountPerDay | CurrentAmountPerDay 
------------------------------------------------- 
    12  | 10    | 0 
    25  | 100    | 84 

現在你能想象當用戶名顧客= 12做了交易我必須控制,如果交易金額+當前金額>最高金額然後拋出一個異常,否則我必須執行事務並更新當前金額,並且當更新後發生異常時,我必須回滾更新操作(update和rollback在不同的數據庫事務中所以回滾是與新金額相同的更新)

在我做這個設計之前,我決定尋找一個更好的解決方案,甚至是一個開源框架,因爲我想我的客戶的需求將在未來發生變化,例如他們需要MaxAmountPerMonth,或者一些更多的要求,我現在不知道。

votes
answers
21 views
+50

實體框架,存儲庫模式和2個數據庫

1

我正在使用2個DB工作的應用程序。我想使用EF,Repository和UnitOfWork模式。我正在學習乾淨的代碼原則和設計模式,所以想要得到一些反饋,因爲雖然我(認爲)理解了主要想法,但我在實現中遇到了一些困難。我收集了很多答案和文章,但仍然無法完全將這些想法帶入我的具體問題。實體框架,存儲庫模式和2個數據庫

我有2個DB。

  1. 我們的ERP系統的遺留數據庫。只讀訪問(又名ERP-DB)。從這個數據庫我必須採取我需要的所有信息。
  2. Project-DB。需要創建,對此我沒有任何限制。 (又名項目-DB

因此,首先,如果我的理解是正確的ERP-DB我應該使用DBFirst的方法,因爲我不能修改數據庫和項目數據庫,我可以用任何人,作爲CodeFirst也許是最好的方法(因爲我試圖做DDD),所以我可以先設計我的領域模型,然後定義將持續的東西。

現在的1個問題:

  • 的ERP-DB是很 「一般」,有例如一表 「的文章」。在這裏你可以找到任何類型的文章,從完整的構建設備到裝配件。 因此,對於DBFirst,EF爲其生成一個名爲「Articles」的實體。但我不想在我的領域模型中使用這樣的類,我想要更好的類如transmitter,termometer,measureCell等。它們是「特定」的文章。所以我需要將Articles映射到不同的域對象。

    • 我需要手動做還是EF可以在DBFirst中爲我做?
    • 如果手動,我應該爲每個域對象創建一個Repository並將地圖邏輯放入其中?或者我應該創建2個存儲庫,1個用於數據實體,1個用於域對象,然後創建地圖邏輯的位置?
    • 某些特定物品包含多個article,即transmitter具有measureCell,兩個實體都在相同的articles表中。所以在這裏,我的TransmitterRepository有一個方法,知道如何檢索一個發射器,或者我應該把這個邏輯放在哪裏?現在

,關於該項目-DB,我可以用CodeFirst專注於我的域模型,並確定需要保留什麼。所以,如果我選擇這種方法並理解它,我可以直接將我的數據實體映射到我的域對象。但是我不完全理解它,因爲對於我來說,我只是將相同的邏輯放在其他地方,而不是在回購中使用它,而是直接在我的對象中使用它,但是我在那裏「贏」了什麼?

+0

您可以[先對現有數據庫進行編碼](https://msdn.microsoft.com/en-us/library/jj200620(v = vs.113).aspx)。我不明白你最後的問題。 EF簡單地說就是已經實現了工作單元模式的對象關係映射器。關於是否使用存儲庫,首先編寫代碼和首先編寫數據庫等進行了大量的討論和討論。 –

votes
answers
33 views
+50

訪問私有變量在斯卡拉測試沒有鑄造

0

我需要你的幫助,我有這個斯卡拉問題。訪問私有變量在斯卡拉測試沒有鑄造

我有一個類的層次結構:車輛只有每個車輛的共同變量,然後是3個子類:Car,Truck和MotorCycle,每個人都有自己的特定變量。 我使用模式匹配在輔助對象的方法來做這取決於車輛的類型的一些變換:

object Transformation { 
    def someTransformation(vehicle:Vehicle):Vehicle = { 
     vehicle match { 
      case Car(<<<vars>>>) => Car(<<< transformed vars>>>) 
      case Truck(<<<vars>>>) => Truck(<<< transformed vars>>>) 
      case MotorCycle(<<<vars>>>) => MotorCycle(<<< transformed vars>>>) 
     } 
    } 
} 

我的問題是,當我必須測試它,因爲我返回一個車輛(可以說一個混合),我必須在每次出現時都施放以便獲得所涉及的車輛的私人汽車。 我想離開這段代碼的樣子,並且在測試過程中訪問私有成員而不投射,知道我作爲參數收到的車輛與我返回的車輛類型相同。 這可以通過泛型來解決嗎?如何?

謝謝,我希望它是可以理解的。

+0

我猜你真的不意味着該類的'private'成員,繼承特定的公正? – Kraylog

+0

恰恰是尼姆羅德阿爾戈夫 –

votes
answers
36 views
+50

Python:從陣列中匹配字符串與另一個陣列中文本的子字符串

1

目前,我正在使用Pythons BeautifulSoup Library來檢索報紙文章的網頁。這些文章存儲在對象「細節」中。Python:從陣列中匹配字符串與另一個陣列中文本的子字符串

然後我有幾個存儲在對象「行」中的各種街道名稱。現在我想搜索「行」中包含的街道名稱的文章。

如果其中一個街道名稱是其中一篇文章的一部分,我想在數組中保護街道名稱。

如果沒有匹配項目(所選文章不包含任何街道名稱),那麼數組中應該有一個空元素。例如,假設對象「線」由(「Abbey Road」,「St-John's Bridge」,「West Lane」,「Sunpoint」,「East End」)組成。

對象「細節」由4篇文章組成,其中2篇包含「Abbey Road」和「West Lane」(例如「Abbey Road車禍,三人受傷」)。其他兩篇文章不包含任何來自「行」的名稱。

那麼結果匹配應該是這樣的一個陣列中後: [] [「艾比路」] [] [「西一巷」]

我也被告知要使用矢量對於這一點,因爲我原來的數據樣本相當大。不過,我對字符串操作使用矢量化並不熟悉。有沒有人與此合作?

我的代碼目前看起來是這樣的,但是這僅返回「-1」作爲我得到的數組的元素:

from bs4 import BeautifulSoup 
import requests 
import io 
import re 
import string 
import numpy as np 


my_list = [] 
for y in range (0, 2): 
    y *= 27 
    i = str(y) 
    my_list.append('http://www.presseportal.de/blaulicht/suche.htx?q=' + 'einbruch' + '&start=' + i) 



for link in my_list: 
    # print (link) 
    r = requests.get(link) 
    r.encoding = 'utf-8' 
    soup = BeautifulSoup(r.content, 'html.parser') 



with open('a4.txt', encoding='utf8') as f: 
     lines = f.readlines() 
     lines = [w.replace('
', '') for w in lines]  


     details = soup.find_all(class_='news-bodycopy') 
     for class_element in details: 
      details = class_element.get_text() 

     sdetails = ''.join(details) 
     slines = ''.join(lines) 
     i = str.find(sdetails, slines[1 : 38506]) 
     print(i)     

如果有人想複製我的實驗,網站,鏈接在上面的代碼並且對象「細節」中的文章的抓取和存儲工作正常,因此代碼可以被複制。

中的.txt文件對我原來的數據爲對象的「線」可以在這個Dropbox的,文件夾進行訪問: https://www.dropbox.com/s/o0cjk1o2ej8nogq/a4.txt?dl=0

非常感謝任何提示我怎樣才能使這項工作,最好是通過矢量。

+0

我相當不確定的第二個for循環,其中變量'soup'將在每個迭代被覆蓋。無論如何,讓我嘗試運行你的整個代碼,並理解問題! –

+0

第二個for循環用於抓取存儲新聞報告的網站的不同頁面。我們創建一個鏈接列表,每個鏈接爲一個頁面,第一個for循環,分頁計數器在URL中爲27。 但是,我很難從文章中提取街道名稱,方法是將它們與「a4.txt」中的列表進行匹配,並將它們存儲在數組中,其中沒有匹配街道名稱的元素爲空,並且具有匹配名稱的元素包含匹配只有名字。 我的整個代碼都在上面的文章中,並且有一個「a4.txt」的鏈接。 @VivekHarikrishnan – DataFreshman

votes
answers
21 views
+50

什麼讓使用PHP的preg_match

0

我想解析使用正則表達式什麼讓使用PHP的preg_match

Option1假設DIV 類= 「class1的類class2 CLASS3 CLASS4」

我的HTML這樣

<div class="calss1 class2 class3"> 
    Content 1 
</div> 
<div class="calss1 class2 class3"> 
    Content 2 
</div> 
<div class="calss1 class2 class3"> 
    Content 3 
</div> 
<div class="calss1 class2 class3"> 
    Content 4 
</div> 
<div class="calss1 class2 class3"> 
    Content 5 
</div> 
它的div一流的名字內容

我想要使用第一部分div類名稱獲得所有div內容 我已嘗試此 其中$ my_content是總頁面contnet

if (preg_match('/<div class="class1">(.*?)</div>/is', $my_content, $img)) { 
      echo 'working'; 
     } 

這是工作的內容時,這樣

<div class="calss1"> 
    Content 1 
</div> 

,我需要使用正則表達式來檢查只有第一類名稱不完整的類名稱

votes
answers
28 views
+50

在safeTail函數中的Haskell模式匹配

-3

我得到了一個使用模式匹配定義的Haskell函數,但我不是很明白爲什麼它看起來像它的樣子。在safeTail函數中的Haskell模式匹配

safeTail (x : xs) = xs 

我不是特別明白在(x:xs),這是什麼意思?

+0

如果是這樣的功能的完整定義,我會已命名爲'unsafeTail'或'dangerousTail',因爲這將在空列表中崩潰。 – chi

+0

我得到了空列表的catchall,但決定不把它放在這裏,因爲這裏的重點是我不明白(x:xs)的語法而不是函數。 – Wandy

votes
answers
27 views
+50

斯卡拉:正則表達式模式匹配

0

我有以下的輸入字符串斯卡拉:正則表達式模式匹配

"/horses/[email protected]" 
"/Goats/[email protected]" 
"/CATS/[email protected]" 

我想獲得

"horses", "c132", "[email protected]" 
"Goats", "b-01", "[email protected]" 
"CATS", "001", "[email protected]" 

我嘗試以下

StandardTokenParsers以下爲輸出

import scala.util.parsing.combinator.syntactical._ 
val p = new StandardTokenParsers { 
lexical.reserved ++= List("/", "?", "XXX=") 
def p = "/" ~ opt(ident) ~ "/" ~ opt(ident) ~ "?" ~ "XXX=" ~ opt(ident) 
} 
p: scala.util.parsing.combinator.syntactical.StandardTokenParsers{def p: this.Parser[this.~[this.~[this.~[String,Option[String]],String],Option[String]]]} = [email protected] 

scala> p.p(new p.lexical.Scanner("/horses/[email protected]")) 
warning: there was one feature warning; re-run with -feature for details 
res3: p.ParseResult[p.~[p.~[p.~[String,Option[String]],String],Option[String]]] = 
[1.1] failure: ``/'' expected but ErrorToken(illegal character) found 

/horses/[email protected] 
^ 

正則表達式

import scala.util.matching.regex 
val p1 = "(/)(.*)(/)(.*)(?)(XXX)(=)(.*)".r 
p1: scala.util.matching.Regex = (/)(.*)(/)(.*)(?)(XXX)(=)(.*) 

scala> val p1(_,animal,_,id,_,_,_,company) = "/horses/[email protected]" 
scala.MatchError: /horses/[email protected] (of class java.lang.String) 
    ... 32 elided 

是否有人可以幫忙嗎?謝謝!

votes
answers
36 views
+50

與agrep匹配的模糊字符串

1

由於數據在遺留系統中存儲錯誤,因此我使用R和agrep()來匹配公司名稱列表 - 因爲數據在傳統系統中存儲錯誤 - 沒有第四種常規格式,公司在同一級別上錄製作爲客戶,這意味着每個新客戶都有一個新的公司條目,這導致一家公司擁有許多不同的公司名稱 - 這在很多情況下都能正常工作。與agrep匹配的模糊字符串

有時,特別是對於短字符串,我得到的 - 至少對我來說 - 奇怪的比賽,例如(ABC是第一家名稱):

ABC ABAXIS Europe GmbH 

ABC ABB Europe 

ABC ABB Group 

ABC ABB Stotz Kontakt GmbH 

ABC ABM Financial News 

ABC ABN AMRO Bank NV 

ABC AC Klöser GmbH 

ABC ACCBank 

ABC ACEA S.p.A. 

使用agrep()以下參數I'm:

agrep(vector1, vector2, value = TRUE, ignore.case = FALSE, max.distance = 0.01) 

是否有任何其他方式比最大距離來調整agrep()或更好的方式來做到這一點?

預先感謝

votes
answers
29 views
+50

在php中遇到小於(<)的操作符preg_match_all

1

我試圖解析一個查詢字符串,並遇到了一些我無法弄清楚的東西。在php中遇到小於(<)的操作符preg_match_all

試圖匹配一個字符串,該字符串可以包含<或>,但是隻有當字符串包含<時,纔會看到一些奇怪的輸出。

例子:

<?php 
$gt = 'wt>f'; 
preg_match_all("/([A-Za-z<>]+)/", $gt, $gtmatches); 
?> 

<pre><?php print_r($gtmatches); ?></pre> 

返回預期:

Array 
(
    [0] => Array 
     (
      [0] => wt>f 
     ) 

    [1] => Array 
     (
      [0] => wt>f 
     ) 
) 

但只需更換該>與<,給人很奇怪輸出:

代碼:

<?php 
$lt = 'wt<f'; 
preg_match_all("/([A-Za-z<>]+)/", $lt, $ltmatches); 
?> 

<pre><?php print_r($ltmatches); ?></pre> 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => wt Array 
     (
      [0] => wt 

我測試過這對PHP 5.6.24/IIS 10,並在本地上的PHP 32年6月5日/阿帕奇2.4.29。

解決由於iainn(該死,你們是快!)

我的瀏覽器被解釋<作爲標籤的開始,望着源,一切都很好。

+1

它適用於我: - https://eval.in/926067和https://eval.in/926069(兩個版本) –

votes
answers
23 views
+50

Why are elementwise additions much faster in separate loops than in a combined loop?

Suppose a1, b1, c1, and d1 point to heap memory and my numerical code has the following core loop.

const int n = 100000;

for (int j = 0; j < n; j++) {
    a1[j] += b1[j];
    c1[j] += d1[j];
}

This loop is executed 10,000 times via another outer for loop. To speed it up, I changed the code to:

for (int j = 0; j < n; j++) {
    a1[j] += b1[j];
}

for (int j = 0; j < n; j++) {
    c1[j] += d1[j];
}

Compiled on MS Visual C++ 10.0 with full optimization and SSE2 enabled for 32-bit on a Intel Core 2 Duo (x64), the first example takes 5.5 seconds and the double-loop example takes only 1.9 seconds. My question is: (Please refer to the my rephrased question at the bottom)

PS: I am not sure, if this helps:

Disassembly for the first loop basically looks like this (this block is repeated about five times in the full program):

movsd       xmm0,mmword ptr [edx+18h]
addsd       xmm0,mmword ptr [ecx+20h]
movsd       mmword ptr [ecx+20h],xmm0
movsd       xmm0,mmword ptr [esi+10h]
addsd       xmm0,mmword ptr [eax+30h]
movsd       mmword ptr [eax+30h],xmm0
movsd       xmm0,mmword ptr [edx+20h]
addsd       xmm0,mmword ptr [ecx+28h]
movsd       mmword ptr [ecx+28h],xmm0
movsd       xmm0,mmword ptr [esi+18h]
addsd       xmm0,mmword ptr [eax+38h]

Each loop of the double loop example produces this code (the following block is repeated about three times):

addsd       xmm0,mmword ptr [eax+28h]
movsd       mmword ptr [eax+28h],xmm0
movsd       xmm0,mmword ptr [ecx+20h]
addsd       xmm0,mmword ptr [eax+30h]
movsd       mmword ptr [eax+30h],xmm0
movsd       xmm0,mmword ptr [ecx+28h]
addsd       xmm0,mmword ptr [eax+38h]
movsd       mmword ptr [eax+38h],xmm0
movsd       xmm0,mmword ptr [ecx+30h]
addsd       xmm0,mmword ptr [eax+40h]
movsd       mmword ptr [eax+40h],xmm0

The question turned out to be of no relevance, as the behavior severely depends on the sizes of the arrays (n) and the CPU cache. So if there is further interest, I rephrase the question:

Could you provide some solid insight into the details that lead to the different cache behaviors as illustrated by the five regions on the following graph?

It might also be interesting to point out the differences between CPU/cache architectures, by providing a similar graph for these CPUs.

PPS: Here is the full code. It uses TBB Tick_Count for higher resolution timing, which can be disabled by not defining the TBB_TIMING Macro:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>

//#define TBB_TIMING

#ifdef TBB_TIMING   
#include <tbb/tick_count.h>
using tbb::tick_count;
#else
#include <time.h>
#endif

using namespace std;

//#define preallocate_memory new_cont

enum { new_cont, new_sep };

double *a1, *b1, *c1, *d1;


void allo(int cont, int n)
{
    switch(cont) {
      case new_cont:
        a1 = new double[n*4];
        b1 = a1 + n;
        c1 = b1 + n;
        d1 = c1 + n;
        break;
      case new_sep:
        a1 = new double[n];
        b1 = new double[n];
        c1 = new double[n];
        d1 = new double[n];
        break;
    }

    for (int i = 0; i < n; i++) {
        a1[i] = 1.0;
        d1[i] = 1.0;
        c1[i] = 1.0;
        b1[i] = 1.0;
    }
}

void ff(int cont)
{
    switch(cont){
      case new_sep:
        delete[] b1;
        delete[] c1;
        delete[] d1;
      case new_cont:
        delete[] a1;
    }
}

double plain(int n, int m, int cont, int loops)
{
#ifndef preallocate_memory
    allo(cont,n);
#endif

#ifdef TBB_TIMING   
    tick_count t0 = tick_count::now();
#else
    clock_t start = clock();
#endif

    if (loops == 1) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++){
                a1[j] += b1[j];
                c1[j] += d1[j];
            }
        }
    } else {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                a1[j] += b1[j];
            }
            for (int j = 0; j < n; j++) {
                c1[j] += d1[j];
            }
        }
    }
    double ret;

#ifdef TBB_TIMING   
    tick_count t1 = tick_count::now();
    ret = 2.0*double(n)*double(m)/(t1-t0).seconds();
#else
    clock_t end = clock();
    ret = 2.0*double(n)*double(m)/(double)(end - start) *double(CLOCKS_PER_SEC);
#endif

#ifndef preallocate_memory
    ff(cont);
#endif

    return ret;
}


void main()
{   
    freopen("C:\test.csv", "w", stdout);

    char *s = " ";

    string na[2] ={"new_cont", "new_sep"};

    cout << "n";

    for (int j = 0; j < 2; j++)
        for (int i = 1; i <= 2; i++)
#ifdef preallocate_memory
            cout << s << i << "_loops_" << na[preallocate_memory];
#else
            cout << s << i << "_loops_" << na[j];
#endif

    cout << endl;

    long long nmax = 1000000;

#ifdef preallocate_memory
    allo(preallocate_memory, nmax);
#endif

    for (long long n = 1L; n < nmax; n = max(n+1, long long(n*1.2)))
    {
        const long long m = 10000000/n;
        cout << n;

        for (int j = 0; j < 2; j++)
            for (int i = 1; i <= 2; i++)
                cout << s << plain(n, m, j, i);
        cout << endl;
    }
}

(It shows FLOP/s for different values of n.)

enter image description here

votes
answers
26 views
+50

向量化索引另一個數組的值數組

0

我正在嘗試矢量化下面的代碼。向量化索引另一個數組的值數組

for x in range (0, 500): 
     S = rand.choice(np.unique(Y)) 
     A = rand.choice(np.unique(X[Y==S])) 

Y和X是索引中的值需要匹配的數組。

目前我改性S是

S = np.random.choice(np.unique(Y),size=500) 

然而,我無法通過X具有數值•

爲大小的示例的陣列,以找出如何索引= 5可以是

Y = [0,0,2,3,2,4] 
X = [1,2,1,3,4,2] 

S = [0,2,0,3,2] 
X[Y==S] => ([1,2],[1,4],[1,2],[3],[1,4]) <= Not sure how to get this 
A = [2,4,1,3,1] 

有沒有簡單的方法來做到這一點?

votes
answers
20 views
+50

電報webhook沒有快速響應

0

我的機器人超過50K組,並使用Webhook接收每條消息。電報webhook沒有快速響應

問題是,在繁忙時間,電報會以較長的延遲(即一小時後)向我的webhook發送更新。

是否有任何參考文獻談論限制以及每秒電報傳遞給webhook的消息數量,並且通常我如何加快速度?

votes
answers
24 views
+50

Telegram bot api keyboard

I have problem with Telegram Bot Api and with "ReplyKeyboard". I'm using Python 2.7 and I send post request:

TelegramAPI.post(TELEGRAM_URL + "sendMessage", data=dict(chat_id=CHAT_ID, text="", keyboard={'keyboard': keyboard, 'one_time_keyboard': False, 'resize_keyboard': True})

keyboard in this format:

[["A button"], ["B button"]]

But in Telegram I don't see keyboard. What problem can be?

votes
answers
24 views
+50

TelegramBot申請停止與此錯誤(SocketException,請IOException異常,引發WebException,HttpRequestException)工作

0

我不知道我能do.My什麼telegrambot項目突然停止後約1 day.with這樣的錯誤工作。如果可能,請幫助我。TelegramBot申請停止與此錯誤(SocketException,請IOException異常,引發WebException,HttpRequestException)工作

Framework Version: v4.0.30319 
Description: The process was terminated due to an unhandled exception. 
Exception Info: System.Net.Sockets.SocketException 
at System.Net.Sockets.Socket.EndReceive(System.IAsyncResult) 
at System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult) 

Exception Info: System.IO.IOException 
at System.Net.Security._SslStream.EndRead(System.IAsyncResult) 
at System.Net.TlsStream.EndRead(System.IAsyncResult) 
at System.Net.PooledStream.EndRead(System.IAsyncResult) 
at System.Net.Connection.ReadCallback(System.IAsyncResult) 

Exception Info: System.Net.WebException 
at System.Net.HttpWebRequest.EndGetResponse(System.IAsyncResult) 
at System.Net.Http.HttpClientHandler.GetResponseCallback(System.IAsyncResult) 

Exception Info: System.Net.Http.HttpRequestException 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) 
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) 
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1+ConfiguredTaskAwaiter[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResult() at Telegram.Bot.TelegramBotClient+<SendWebRequestAsync>d__1091[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext() 

Exception Info: System.AggregateException 
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean) 
at System.Threading.Tasks.Task1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].GetResultCore(Boolean) at System.Threading.Tasks.Task1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_Result() 
at Mybot.BotForm.RunBot() 
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object) 
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) 
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) 
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) 
at System.Threading.ThreadHelper.ThreadStart() 
+0

只是''try' catch',而忽略錯誤,它的事業由長輪詢失敗 – Sean

+0

您reply.I @Sean由於改變了我的代碼,這是現在的工作,沒有錯誤。 – mona

votes
answers
33 views
+50

scrapy管道類的訪問實例

0

我想訪問變量self.cursor以利用活動的postgreSQL連接,但我無法弄清楚如何訪問scrapy的管道類實例。scrapy管道類的訪問實例

class ScrapenewsPipeline(object): 

    def open_spider(self, spider): 
     self.connection = psycopg2.connect(
     host= os.environ['HOST_NAME'], 
     user=os.environ['USERNAME'], 
     database=os.environ['DATABASE_NAME'], 
     password=os.environ['PASSWORD']) 
     self.cursor = self.connection.cursor() 
     self.connection.set_session(autocommit=True) 


    def close_spider(self, spider): 
     self.cursor.close() 
     self.connection.close() 


    def process_item(self, item, spider): 
     print ("Some Magic Happens Here") 


    def checkUrlExist(self, item): 
     print("I want to call this function from my spider to access the 
    self.cursor variable") 

請注意,我知道我可以用yield item得到process_item訪問,但該功能是做其他的東西,我想通過self.cursorcheckUrlExist連接的訪問??,並能夠從調用類的實例我蜘蛛隨意! 謝謝。

+0

'objectName.cursor'? – RottenCandy

+0

objectName在我不知道的時候,管道類會在蜘蛛自動啓動時調用,我想將一個實例掛接到該類的實例上! :) – atb00ker

+0

也許你應該考慮'getattr' https://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it#4076099 – RottenCandy

votes
answers
21 views
+50

如何刪除批量和模式與noteplad ++的文本

1

我想清理這個文件一點,並刪除無用的行 與記事本+ +。我知道有一個簡單的方法來做到這一點,但我忘了如何。如何刪除批量和模式與noteplad ++的文本

基本上我想要搜索並刪除所有與( - 默認) 相關的組,如下所示。我想刪除每一個uui /選項/名稱/組/權限 基本上任何球員數據是在組( - 默認),但它不是 容易與「替換」選項,你可以看到每個球員有不同的 名稱或uuid,因爲該文件超過了10萬行,所以很難將其批量移除。

  • 我記得曾與在記事本馬克選項做++ *

    -> Remove  00126374-2f71-438b-b30b-2aad7da6c169: 
    -> Remove  options: 
    -> Remove  name: NightCorePvP 
    -> Remove  group: 
    -> Remove  - Default <- (Keyword) 
    -> Remove  permissions: 
    -> Remove  - none 
    
        003fdb5d-b980-4761-88c8-34f0d7478755: 
        options: 
         name: XanderCole 
        group: 
        - iron 
        permissions: 
        - none 
        0006597c-625e-4e85-a0d9-fa125f44ad5d: 
        options: 
         name: JugendLammy 
        group: 
        - Default 
        permissions: 
        - none 008604cc-1e71-419a-b1c9-fd79e53cabc6: 
    

下面是該文件的一個形象是什麼,以保持和刪除 一個例子 - https://i.gyazo.com/4621d7151dbeb25a1855ffbd03f81e7d.png

votes
answers
26 views
+50

正則表達式NP ++不同的變化情況下,「本」到不同的字

0

我有幾個包含像在許多不同的線以下的文本文件:正則表達式NP ++不同的變化情況下,「本」到不同的字

this_is_THIS.doc 

我需要做到的是,以取代本前5次出現不同的物體,並忽略其餘的物體。

我想它出現類似如下:

this_is_TREE.doc 
this_is_CAR.doc 
this_is_CAT.doc 
this_is_DONKEY.doc 
this_is_ROCK.doc 

我將在未來的話改變,所以我覺得一個正則表達式,我可以在未來改變做了很多次會幫助我很多。我搜查了但沒有發現任何有用的東西謝謝你的幫助,你們這裏的人很棒。

+0

對於這樣的工作,特別是如果'THIS'的數量很大,您應該用最喜歡的腳本語言編寫腳本。 – Toto

votes
answers
22 views
+50

記事本++複雜的正則表達式

1

我有一個巨大的HTML文件,我想刪除所有的零件開始[sound:<div style='font-family: Arial; font-size: 15px;'></div>記事本++複雜的正則表達式

在這裏結束我的文檔樣本:

<div class=Answer> 
     <div style='font-family: Arial; font-size: 50px;'>你好</div> 
     <br />n? h?o<br />[sound:pronunciation_zh_你好.mp3] 
     <a href='javascript:py.link("ankiplaypronunciation_zh_你好.mp3");' title="pronunciation_zh_你好.mp3" class="replaybutton browserhide"> 
      <span> 
       <svg viewBox="0 0 32 32"> 
       <polygon points="11,25 25,16 11,7"/> 
       Replay 
       </svg> 
      </span> 
     </a> 
     <span style="display: none;">&#91;sound:pronunciation_zh_你好.mp3&#93;</span><br /> 
     <div style='color: DarkSlateGray; font-size: 25px;' ></div> 
     <br /> 
     <div style='font-family: Arial; font-size: 15px;'></div> 
    </div> 

預期結果:

<div class=Answer> 
     <div style='font-family: Arial; font-size: 50px;'>你好</div> 
     <br />n? h?o<br /> 
    </div> 

我試圖在記事本中使用正則表達式+ +,但我想不通這其中,尤其是因爲我總是得到「無效的表達式」可能是由於</,>字符。

在此先感謝您的幫助!

+1

顯示你的正則表達式。 –

+0

我試過這個:[聲音:*

Ilamoureuse

+0

有沒有可能讓你的html文件被縮小? – revo

votes
answers
21 views
+50

記事本++。將所有空格刪除到大括號[]

-1

如何使用Notepad ++和RegEx刪除所有空格轉換爲大括號?記事本++。將所有空格刪除到大括號[]

例如:

我有字符串[字1字2 WORD3] 我需要:[Word1Word2Word3]

由於

+0

所有空格或全部空格? –

votes
answers
11 views
+50

Is there a way to get a Haskell setup on Windows without an installation? (Copy + paste)

I am programming on a school-given computer. I need to have a Haskell setup that does no installation (one I can drop on a flash drive and copy on to the C drive or just use from the flash drive perhaps).

I already have Eclipse up and running, so if I could get it on Eclipse without leaving any impact on the system past the Eclipse directory, that would be very good as well.

By no installation, I mean I have to be able to easily remove the program and roughly all traces without any uninstaller tool. All uninstaller tools are likely blocked.

What are my options?

votes
answers
19 views
+50

爲什麼是柔性壓低頁腳未能

0

我試圖使用Flex箱技術,https://css-tricks.com/couple-takes-sticky-footer/來響應下推頁腳在我的網頁http://apple.mdsc1.com/test/爲什麼是柔性壓低頁腳未能

我用: -

<style> 
    #wrapper {flex: 1 0 auto;} 
    body, html {height: 100%} 
    body { 
     display: flex; 
     flex-direction: column; 
    } 
</style> 

但失敗了。我正在使用的現成佈局中的東西是破壞柔性版本

我如何使它工作?

votes
answers
26 views
+50

CSS Flex - 我有一個項目列表可以需要使他們水平滾動與溢出隱藏

0

我有一個div內的3項。CSS Flex - 我有一個項目列表可以需要使他們水平滾動與溢出隱藏

這個容器需要100%的小部件和水平滾動條。

所以就像一個旋轉木馬。

.wrapper { 
 
    display: flex; 
 
    flex: 1 1 0; 
 
    overflow-x: scroll; 
 
    overflow-y: hidden; 
 
} 
 

 
.content { 
 
    display: flex; 
 
    width: 500px; 
 
} 
 

 
.item { 
 
    height: 200px; 
 
    width: 100px; 
 
    margin-right: 10px; 
 
}
<div class='wrapper'> 
 
    <div class='content'> 
 
    <div class='item'></div> 
 

 
    <div class='item'></div> 
 

 
    <div class='item'></div> 
 
    </div> 
 
</div>

結果:我想買的東西去與水平滾動條。

目前上面的代碼打破了我的柔性佈局。 我可以做到這一點很容易沒有彎曲,但我正在尋找一個靈活的解決方案。

+0

不知道你要完成的任務。在你的代碼中,沒有溢出,因爲這些物品在容器內很舒適。 https://jsfiddle.net/L46qasdu/ –

+0

它的動態,因此他們可以有10個項目爲例。 – AngularM

+0

有兩個柔性容器。哪一個得到溢出? –

votes
answers
17 views
+50

CSS的Flex寬度上的文本

0

的線我不太清楚,如果這是可能的CSS,但沒有找到那個方向什麼,但我會搏一搏:CSS的Flex寬度上的文本

在(Flex的) - 容器我想要多個(2-3)框/列的文本。每一列都是它自己的文章,它有自己的標題,所以它不是一個文本繼續到下一列。

但是,我希望所述列的寬度是靈活的,以便沒有列浪費空白空間直到結束。如果一列有空行,它會嘗試減小寬度以爲自己創建更多換行符並填充該空白,而其他框獲得更多寬度以減少文本行數。

在任何情況下,所有列都應嘗試獲取相同數量的文本行,從而通過增加/減少寬度空間來獲得相同的內容高度。

/編輯:一個代碼示例,我迅速做了基於https://www.w3schools.com/css/tryit.asp?filename=trycss3_flexbox_flex-wrap_nowrap8

正如你將看到,無論是柔性盒將保持50%的寬度,即使其中一個比另一個更加豐滿。我希望他們自動重新排列寬度以避免文本下面的空白空間。寬度較小的第一個盒子會有更多的換行符,而寬度較大的第二個則會有較少的換行符。目標是儘可能少地區分文本行數。

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.flex-container { 
    display: flex; 
    background-color: DodgerBlue; 
} 

.flex-container>div { 
    background-color: #f1f1f1; 
    margin: 10px; 
    padding:20px; 
    font-size: 7px; 
} 
</style> 
</head> 
<body> 

<div class="flex-container"> 
    <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum..</div> 
    <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum..Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div> 
</div></body></html> 
+0

後,你已經嘗試過的代碼。當我們能夠重現問題時,我們可以更有效地幫助您。 –

+0

我添加了一個代碼示例來說明問題,但我還沒有嘗試過任何解決方法,因爲我不知道從哪裏開始(或者如果可能的話)。 –

+0

但你的問題中的代碼示例已經這樣做了:https://jsfiddle.net/sofybcge/ – LGSon

votes
answers
15 views
+50

Bootstrap 4垂直對齊中心無法在柔性佈局上工作

0

使用Bootstrap 4,我有一個響應式佈局,包含3列,(應該)在不同的屏幕尺寸上更改順序,寬度和水平對齊。它所有的工作,只是在屏幕大小< 768px的IMGS的水平居中對齊不正常工作。這裏是我的代碼:Bootstrap 4垂直對齊中心無法在柔性佈局上工作

.icon-xl-large { 
 
    width: 80px; 
 
} 
 

 
.w-400px { 
 
    max-width: 400px; 
 
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/> 
 

 
<div class="row justify-content-center justify-content-md-between"> 
 
    <div class="order-md-1 col-6 col-md-auto align-self-center"> 
 
    <img src="http://via.placeholder.com/350x350" alt="" class="icon-xl-large mx-auto" > 
 
    </div> 
 
    <div class="order-md-3 col-6 col-md-auto align-self-center"> 
 
    <img src="http://via.placeholder.com/350x350" alt="" class="icon-xl-large mx-auto" > 
 
    </div> 
 
    <div class="col-12 order-md-2 col-md-6 w-400px text-center"> 
 
    <h5>Sample text in center</h5> 
 
    </div> 
 
</div>

在我的例子代碼在2列IMGS都左對齊。預期的行爲應該是兩個imgs垂直居中排列在各自的列中。在大於768px的屏幕上,imgs的列自動浮動到左側和右側(col-md-auto)。這是預期的,不應該改變。

我該如何將imgs居中顯示在屏幕上的列中< 768px?

我發現了類似的問題,比如Vertical Align Center in Bootstrap 4和嘗試過各種建議的解決方案,例如設置mx-auto,使用d-flex對齊內容中心,設置固定寬度等等。沒有任何東西可以用於我。我錯過了什麼?

votes
answers
25 views
+50

Flexbox的欄佈局響應與列重新排序沒有固定的高度

0

我試圖用Flexbox的做到這一點=>Flexbox的欄佈局響應與列重新排序沒有固定的高度

桌面:

|   | | block 1 | 
| block 2 | 
|   | | block 3 | 

移動:

block 1 
block 2 
block 3 

我來到這個

.cont { 
    display: flex; 
    flex-direction: column; 
    flew-wrap: wrap-reverse; 
} 

.myblocks.block2 { 
    order: -1; 
} 

@media screen and (max-width: 640px) { 
    .cont { 
    display: block; 
    } 
} 

個但這不起作用,直到我設定一個固定的height.contflex-basis.block1


問題:

  • 有與Flexbox的辦法來做到這一點,沒有固定的身高?
  • 是flexbox的正確工具嗎?

注:我使用的是布爾瑪

+0

你知道塊2的寬度嗎? – Danield

+0

我這樣做,但% –

votes
answers
23 views
+50

使彈性項目展開懸停,縮小其兄弟姐妹

1

我試圖解決flexbox問題,我想每行有三個div,首先大小相等,但是當懸停div時,該增長和其他的在同一行收縮。以爲我已經解決了它,直到我嘗試了多行。使彈性項目展開懸停,縮小其兄弟姐妹

我想要的是當懸停第三個div時,它會縮小第一個和第二個div,並保持其餘不變。我無法弄清楚這一部分。

以下是我的單排工作解決方案。

此佈局是否也可以在多行上工作?

我是否必須將每行包裝在單獨的容器中,還是有辦法解決這個問題?

.container { 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
    width: 100%; 
 
} 
 

 
.box { 
 
    width: 33%; 
 
    flex: 1; 
 
} 
 

 
.box:hover { 
 
    flex-grow: 3; 
 
}
<div class="container"> 
 
    <div class="box"> 
 
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt 
 
     ut labore et dolore magna aliqua. </p> 
 
    </div> 
 

 
    <div class="box"> 
 
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt 
 
     ut labore et dolore magna aliqua. </p> 
 
    </div> 
 

 
    <div class="box"> 
 
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt 
 
     ut labore et dolore magna aliqua. </p> 
 
    </div> 
 
</div>

See it on CodePen

+0

你只想要第二列到懸停成長? – Kushtrim

+0

說我有6個盒子的div(每行3行2列),我把第二個div懸停,我想第二個div擴大,div 1&3縮小,而div 4-6保持不變。 – yayheartbeat

+0

這或多或少是不可能的,主要是因爲你需要檢測哪個行是histed元素,然後只在該行上增長/縮小元素,並且_previous sibling_沒有選擇器。 – LGSon

votes
answers
21 views
+50

Flexbox的佈局 - 沒有JS

0

共享專欄中,我想打一個holygrail般的佈局如下:Flexbox的佈局 - 沒有JS

flexbox layout fullscreen

將變成一個小屏幕上顯示如下:

flexbox layout small screen

有沒有CSS的方式來做到這一點,沒有JS黑客?

+0

的又一可能複製https://stackoverflow.com/questions/41790378/css-flexbox-group-2-flex-items?rq=1 – LGSon

+0

而另一個鏈接到一個問題,沒有一個公認的答案。也許我們這次可以找到答案,並在將來繼續關聯這個問題? :) – Aydin4ik

+0

只是因爲一個答案沒有接受,並不意味着它不能被鏈接,只要鏈接的答案(s)有一個解決方案:) – LGSon

votes
answers
21 views
+50

無法更改React-native中自定義組件的寬度和高度?

0

我有一個自定義的最小的無狀態組件是這樣的:無法更改React-native中自定義組件的寬度和高度?

const ViewBox = (props) => (
    <View style={ mainStyle : {backgroundColor: 'beige'} }> 
     {props.children} 
    </View> 
) 
export default ViewBox; 

所以我想導入和使用它的另一個組件中。

export default class Test extends React.Component { 

render() { 
    return (
     <View style={styles.containerView} > 
      <ViewBox style={styles.mainBox}> 
       <Text style={[styles.boxTitle, {color: '#8F468C'}]}>Lorem ipsum...</Text> 
      </ViewBox> 
     </View> 
    ); 
    } 
} 

const styles = {  
    containerView: { 
    flex: 1, 
    marginTop: 50, 
    alignItems: 'center', 
    backgroundColor: 'brown', 
    }, 
    mainBox: { 
    flex: 1, 
    width: 250, //No effect ! ! ! 
    height: 250 //No effect ! ! ! 
    }, 
    boxTitle: { 
    backgroundColor: 'pink', 
    fontSize: 17, 
    marginTop: 20 
    } 
}; 

在這裏,我們至少有2個莫名其妙的事實:
1),更重要的是你要在這裏使用視框的寬度和高度(或每定製組件)完全失控的!分配數字大小或Flex值不起作用,ViewBox保留呈現內部文本所需的最小寬度/高度。

enter image description here

2)刪除根視圖(因此視框成爲根)視框繼續任何規模大小忽視,但現在它填補所有可用空間....爲什麼???發生

enter image description here

所有提及的behavoirs使用自定義視圖(視框在這種情況下),如果不是用普通視圖代替這一切按預期工作。
我想知道React-native有足夠的flex和UI最佳實踐,但這兩種情況並未被docs覆蓋。希望有人能讓我感到驚訝!

+0

那麼你想要達到的究竟是什麼? –

votes
answers
26 views
+50

bootstrap導航欄沒有顯示正確

0

我已經開始bootstrap最近和trytrong文本做一個導航欄不起作用。所以我看了John Doe的視頻,並下載了它在那裏工作的源代碼!比我橫向複製和粘貼他的導航欄,它並沒有在我的工作。bootstrap導航欄沒有顯示正確

<!DOCTYPE html> 
 
<html lang="en"> 
 
    <head> 
 
    <meta charset="UTF-8"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> 
 
    <title>Form</title> 
 
    </head> 
 
    <body> 
 
    <nav class="navbar navbar-inverse"> 
 
     <div class="container"> 
 
     <div class="navbar-header"> 
 
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> 
 
      <span class="sr-only">Toggle navigation</span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      <span class="icon-bar"></span> 
 
      </button> 
 
      <a class="navbar-brand" href="#">Form</a> 
 
     </div> 
 
     <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> 
 
      <ul class="nav navbar-nav"> 
 
      <li class="active"><a href="#">Nav <span class="sr-only">(current)</span></a></li> 
 
      <li><a href="#">Random</a></li> 
 
      <li class="dropdown"> 
 
       <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> 
 
       <ul class="dropdown-menu"> 
 
       <li><a href="#">Action</a></li> 
 
       <li><a href="#">Another action</a></li> 
 
       <li><a href="#">Something else here</a></li> 
 
       <li role="separator" class="divider"></li> 
 
       <li><a href="#">Separated link</a></li> 
 
       <li role="separator" class="divider"></li> 
 
       <li><a href="#">One more separated link</a></li> 
 
       </ul> 
 
      </li> 
 
      </ul> 
 
     </div> 
 
     </div> 
 
    </nav> 
 
    <!-- JS --> 
 
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> 
 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> 
 
    </body> 
 
</html>

電流輸出:

enter image description here

votes
answers
18 views
+50

製作一個黑暗的崩潰的導航欄視覺上不同

0

我對網頁設計有點新,所以如果這太簡單的問題或錯誤的網站道歉。我使用Bootstrap 4來簡化我的靜態博客中的設計,並且我現在對設計感到非常滿意,但我不喜歡導航欄看起來平坦並且運行到後臺。我正在尋找一些關於如何讓它「流行」的想法,以便在視覺上截然不同,但不會爲設計增加太多複雜性。我嘗試調整顏色,添加漸變,並添加底部陰影,但我一直無法想出看起來不錯的東西。可能我正在尋找所有3個組合,我沒有足夠的技巧來識別。製作一個黑暗的崩潰的導航欄視覺上不同

下面是該網站的當前的開發版本的截圖: screenshot

而到了目前的生產站點的鏈接,導航欄是相同的: http://acwolff.xyz/

votes
answers
16 views
+50

A VBox with only one rounded corner and gradient background

I'm working with Flex 3.4 SDK.

I'm trying to programmatically(yep, must be this way) style/skin a VBox so that its top right corner is rounded, and it gets a two colors gradient brackground.

Modifying examples I found around I was able to accomplish both effects(corner and background) but only separately:

VBox with not all rounded corners: http://livedocs.adobe.com/flex/3/html/help.html?content=skinning_6.html

VBox with gradient background: http://butterfliesandbugs.wordpress.com/2007/06/08/generic-background-gradient-for-containers/

But what I need to do is to apply both at the same time. And all my coding attempts so far have failed silently.

Would anyone know how to go about doing this correctly?

votes
answers
19 views
+50

To check if an object is empty or not

I want to check in my function if a passed argument of type object is empty or not. Sometimes it is empty but still not null thus I can not rely on null condition. Is there some property like 'length'/'size' for flex objects which I can use here. Please help. Thanks in advance.

votes
answers
18 views
+50

Looping over elements inside an element in Flex

I have the following function in Flex 4:

protected function initEventHandlers():void
        {
            imageContainer.addEventListener(DragEvent.DRAG_ENTER, acceptDrag);
            imageContainer.addEventListener(DragEvent.DRAG_DROP, handleDrop);

            img_1.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_2.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_3.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_4.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
        }

I didn't like the look of this code though. The four images are declared inside my application as follows:

<s:HGroup y="10" width="650" horizontalAlign="center" horizontalCenter="6">
        <s:Image width="80" height="80" source="images/1.jpg" id="img_1" />     
        <s:Image width="80" height="80" source="images/2.jpg" id="img_2" />
        <s:Image width="80" height="80" source="images/3.jpeg" id="img_3" />
        <s:Image width="80" height="80" source="images/4.jpg" id="img_4" />
</s:HGroup>

Isn't there a way to loop over each image in the hgroup and add the eventhandler?

Something like this:

for(image in hgroup) { 
    image.addEventlistener(MouseEvent.MOUSE_DOWN, handleDrag); 

}

 My teacher told me this isn't possible but in case of 10+ images, I can't imagine doing it for every image separately. There has to be a better way to do this, no?

Thanks in advance!

votes
answers
28 views
+50

Load and play embedded SWF file in Flex / Actionscript

I'm trying to create / use a pre-loader in my flex application. The preloader is a SWF file which has 100 frames (1 for every percent of the loader progress). Basically I am trying to Embed this SWF file in my application, display it on screen and change the frame number being displayed as the progress completes.

The code I have so far is (which extends Canvas):

[Embed("/../assets/preLoader.swf")]
private var SWFClass:Class;

private var _preLoader:MovieClip;

private var _progress:Number;

public function set progress(value:Number) : void {
    _progress = value;

    if(progress < 100) {
        _preLoader.gotoAndPlay(progress, null);
    }else {
        _preLoader.gotoAndStop(0, null);
    }
}   

[Bindable]
public function get progress() : Number {
    return _progress;
}



(Called on creationComplete event)          
private function init() : void {
    _preLoader = MovieClip(new SWFClass());

    this.addChild(_preLoader);

    _preLoader.play();
}

The error I am getting is:

TypeError: Error #1034: Type Coercion failed: cannot convert widgets::PreLoader_SWFClass@30b3be51 to mx.core.IUIComponent.at mx.core::Container/http://www.adobe.com/2006/flex/mx/internal::addingChild()[C:autobuild3.2.0frameworksprojectsframeworksrcmxcoreContainer.as:3259]

Please help!

votes
answers
22 views
+50

how do I use the “in” operator? Flex/AS3

So the documentation has this nifty "in" operator which I like the idea of more that using a multiple step or statement (||). The documentation gives me this example.

trace("PI" in Math);         // true
trace("myProperty" in Math); // false

and

public var myArray:Array = ["zero", "one", "two"];
trace(0 in myArray); // true
trace(1 in myArray); // true
trace("two" in myArray); // true
trace(3 in myArray); // false

So I try to use it like this:

var quickArray:Array = ["@icd9_color","@icd9_icd9","@templateIcd9_name","@templateIcd9_name","@templateIcd9_templateIcd9ID"];
return (element.dataField in quickArray);

Now I can trace or Alert.show() the element.datafield and it will match exactly with an array item, but it never returns true. Can anyone help me figure out why?

The only thing I can get to work this ugly thing:

return (
  element.dataField == "@icd9_color" ||
  element.dataField == "@icd9_icd9"
  etc..
)
votes
answers
20 views
+50

Event Metadata: Using static variable for “name” attribute?

I want to use the Event metadata tags to show what types of event my control will dispatch. The syntax looks like:

<fx:Metadata>
    [Event(name="eventName", type="MyEvent")]
</fx:Metadata>

It seems like a best practice in Flex/Actionscript to define static variables that define event names like so:

public class MyEvent extends Event
{
    public static const EVENT_NAME:String = "eventName";
    // Other stuff..
}

It's a great practice since the event name can change easily and not have to be modified throughout the code. So my question is: Is there any way to use this static const in my metadata event tag? I can't seem to do something like this:

<fx:Metadata>
    [Event(name="{MyEvent.EVENT_NAME}", type="MyEvent")]
</fx:Metadata>

Am I just ignorant of the proper syntax to do this, or is it impossible? Seems like it's just asking for hard to find bugs if someone decides to change the const since it is not strongly typed here. Thanks in advance!

votes
answers
21 views
+50

How to get the visible items on a Spark List with virtual layout

I have:

  • an ArrayCollection of Numbers;
  • a List using the above ArrayCollection as it's dataprovider, and virtualLayout=true;
  • a custom ItemRenderer that shows a label with: a) the number b) an y position depending on the number AND the highest number visible

In another words, if I have 10 numbers in the AC, and only 5 appear on the screen, the y position of those 5 will depend on the value of the maximum number for those 5. When the user scrolls, of course those 5 elements change so the position of the label in item renderers will change.

My questions:

1) How can I get the list of items that are "currently" visible? 2) Which event/method to override will help me know that the List was scrolled/the visible items changed?

Thank you,

João Saleiro

votes
answers
26 views
+50

如何在C中創建臨時緩衝區?

0

我在我的程序中執行一些物理計算,其中輸出需要存儲到臨時緩衝區並通過管道。如何在C中創建臨時緩衝區?

緩衝區需要共享不同的數據類型:首先,我需要存儲我研究這一課題的名稱;其次是我的計算結果(全部爲float數字)。

的代碼看起來是這樣的:

initialdata.dat

Aston Martin Vantage V12|07.7|090 
Ferrari LaFerrari  |09.6|111 
Lamborghini Aventador |09.6|097 
Porsche 911 Turbo S  |09.6|092 
Tesla Model S P100D  |10.0|069 
Hennessey Venom GT  |10.3|120 
Bugatti Chiron   |11.2|114 
Koenigsegg Agera  |10.3|121 

MAIN.C:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <sys/time.h> 
#include <string.h> 
#include <time.h> 
#include <math.h> 

#define READ 0 
#define WRITE 1 
#define M 2 // Number of subjects. 

int main(){ 
    int pipeToChild[2]; 
    if (pipe(pipeToChild) < 0) { 
     fprintf(stderr,"Error in pipe!"); 
     return -1; 
    } 

    pid_t pid[M]; 
    srand (time(NULL)); 

    // Declares the file pointer with the information. 
    FILE * pFile; 
    char buffer[34]; // Buffer where subject info is sent to childs. 
    char tempBuffer[50]; // The buffer that causes problems. 
    pFile = fopen ("initialdata.dat","r"); 

    for(int i = 0; i < M; i++){ 
     pid[i] = fork(); 
     if (pid[i] < 0){ 
      printf("Fork error!
"); 
      return -1; 
     } 
     else if(pid[i]==0){ 
      // Creates the pipes (one per child) to pass the temporary buffer to the results process (still not created). 
      int pipeToResults[2]; 
      if (pipe(pipeToResults) < 0) { 
       fprintf(stderr,"Error in pipe!"); 
       return -1; 
      } 

      // Receives the car information from the file through a pipe. 
      char receivedValue[34]; 
      receivedValue[33] = ''; 
      close(pipeToChild[WRITE]); 
      read(pipeToChild[READ], receivedValue, sizeof(receivedValue)); 

     // Processes the information and tokenizes it. 
      char name[25]; 
      char CHARacceleration[6]; 
      char CHARmaxSpeed[4]; 
      strcpy(name, strtok(receivedValue, "|")); 
      strcpy(CHARacceleration, strtok(NULL, "|")); 
      strcpy(CHARmaxSpeed, strtok(NULL, "|"));  
      float acceleration = atof(CHARacceleration); 
      float maxSpeed = atoi(CHARmaxSpeed); 

      // Adds 0.0X to acceleration. 
      float randomNum = rand() % 5; 
      acceleration = acceleration + randomNum/100; 

      float distance = 0; 
      float TA = 0; // Time using Uniformly Accelerated Linear Motion. 
      float TB = 0; // Time using Linear Motion. 
      float TE = 0.5; // Time increment. 
      float currentVelocity = 0; // In m/s. 

      // Applies different physical calculations depending on the case. 
      while (distance <= 1000){ 
       TA += TE; 
       if (currentVelocity < maxSpeed){ // Acceleration > 0 
        distance = (acceleration*pow((TA),2))/2; 
        currentVelocity = acceleration*TA; 
        distance = 2*distance; 
       } 
       else{ // Acceleration = 0 
        TB += TE; 
        currentVelocity = maxSpeed; 
        distance += maxSpeed*TB; 
       } 
      } 

      // Debug purposes, just for ensuring everything gets processed the right way. 
      printf("Name: %s
", name); 
      printf("Distance: %.2f m
", distance); 
      printf("Time: %.2f s
", TA+TB); 
      printf("Max speed reached: %.2f km/h
", currentVelocity*3.6); 
      printf("Acceleration: %.2f m/s^2
", acceleration); 
      printf("
"); 

     // Comment this if you want to switch between the situations I talked about. 
     sprintf(tempBuffer, "%s %.2f %.2f %.2f %.2f", name, distance, TA+TB, currentVelocity, acceleration); 
      printf("Buffer: %s

", tempBuffer); 
      exit(0); 
     } 
     else if(pid[i]>0){ 
      // Generates a random subject from the list. Buggy section, fixed it the best way I could. 
      int randCar = rand() % 15 + 1; 
      if (randCar % 2 == 0) 
       randCar--; 
      for (int i = 1; i <= randCar; i++){ 
       if (pFile != NULL) 
        fgets (buffer, sizeof(buffer), pFile); 
       else 
        perror ("ERROR reading file!"); 
      } 
      char toSend[34]; //This will be passed through the `pipeToChild` pipe. 
      strcpy(toSend, buffer); 

      // Loads pipe. 
      close(pipeToChild[READ]); 
      write(pipeToChild[WRITE], toSend, strlen(toSend)); 
      close(pipeToChild[WRITE]); 
     } 
    } 
    for (int i=0;i<M;i++){ 
     waitpid(pid[i], NULL, 0); 
    } 
    fclose(pFile); 
    return 0; 
} 

輸出,雖然是不同的取決於如果我使用或者不是sprintf。例如,對於M = 2,輸出應該是:

案例1:沒有sprintf

I'm the child process 1 with PID 12304 
Name: Bugatti Chiron   
Distance: 1012.61 m 
Time: 9.50 s 
Max speed reached: 383.72 km/h 
Aceleration: 11.22 m/s^2 

I'm the child process 2 with PID 12305 
Name: Bugatti Chiron   
Distance: 1012.61 m 
Time: 9.50 s 
Max speed reached: 383.72 km/h 
Aceleration: 11.22 m/s^2 

案例2:sprintf

I'm the child process 2 with PID 12307 
I'm the child process 1 with PID 12306 
Name: Bugatti Chiron   
Distance: 1012.61 m 
Time: 9.50 s 
Max speed reached: 383.72 km/h 
Aceleration: 11.22 m/s^2 
Buffer: Bugatti Chiron 1012.61 9.50 383.82 11.22 

有什麼問題「衝刺」?爲什麼這條線將整個程序搞砸了?

編輯:該程序是一個簡單的飆車模擬器,其中M車在1000米的直線競爭。所述master過程創建m個隨機汽車(該功能未正確實施,雖然)和通過單個管通過存儲在.dat文件到M子進程的一些數據。

每一輛車都是一個子進程,它是在它那裏計算製成。一旦我們得到的值,每一個孩子通過自身的管一個results的過程,將它們存儲在輸出文件通過存儲在臨時緩衝區中的數據。請注意,此功能仍未實現,因爲首先我需要管理創建緩衝區。我的問題是只有關於緩衝區問題。

enter image description here

+0

沒有[最小,**完整**和可驗證示例](http:// stackoverflow。com/help/mcve)它很難說任何具體的東西,我們所能做的只是猜測*(可能猜得不好)。並請[請閱讀如何提出良好問題](http://stackoverflow.com/help/how-to-ask)。 –

+0

猜測雖然:這是因爲你無法控制調度程序的進程,並且額外的'sprintf'調用可能會導致調度程序意外切換進程?與輸出緩衝一起可能導致多進程程序中的輸出問題。 –

+0

帶有註釋'// printf'的'...'很可能是一個問題。如果您調用'printf'並且不刷新輸出緩衝區,然後調用fork,則將獲得重複的輸出。嘗試在循環結尾添加一個'flush'。 –

votes
answers
20 views
+50

ExternalInterface.call not working

I am attempting to ExternalInterface.call() from inside my SWF.

Note the call comes from inside a SWF I have embedded into another SWF (the _root SWF I have no control over).

Here is my JavaScript:

function player_DoFSCommand(command, args) 
{
    args = String(args);
    command = String(command);

    var arrArgs = args.split(g_strDelim);

    switch (command)
    {
        case "CC_ClosePlayer":

            console.log("yo");
            break;

        default:
            // alert(command);
            break;
    }
}

Here is my AS2 code:

import flash.external.ExternalInterface;

var quiz = _root;

quiz.g_mcFrame.mcFinish.swapDepths(quiz.getNextHighestDepth());
quiz.g_mcFrame.mcFinish._visible = false;
quiz.oSlide.m_oInteraction.m_oVariableMgr.m_arrBoolResumeData = false;

var arrVars:Object = quiz.oSlide.m_oActionHandler.m_oFrame.m_oVariableMgr.m_arrVariables;
var args:Array = [
    arrVars[2].m_nNumber, // Points awarded
    arrVars[3].m_nNumber, // Max points
    arrVars[5].m_nNumber, // Pass percentage
    arrVars[6].m_nNumber, // Pass points
    arrVars[7].m_nNumber, // Score percent
    arrVars[10].m_strString // Result
];

ExternalInterface.call('player_DoFSCommand("CC_ClosePlayer", args)');
ExternalInterface.call('console.log("hello")');

The problem is ExternalInterface.call('player_DoFSCommand("CC_ClosePlayer", args)') doesn't work, or atleast "yo" doesn't appear in the console as expected.

The script is definitely loaded by the time the ExternalInterface is called. The second call works and "hello" appears in the console, however the first function doesn't fire.

I can verify the function works by typing directly into the console player_DoFSCommand("CC_ClosePlayer", args) and it logs successfully.

votes
answers
27 views
+50

連接燒瓶recastai阿比

0

我使用recastai寫FB機器人,我下面這個樣本https://recast.ai/docs/api-reference/#request-text,我寫了這個代碼來分析文本連接燒瓶recastai阿比

from flask import Flask 
import recastai 

app = Flask(__name__) 

@app.route('/') 
def home(): 
    request = recastai.Request('TOKEN') 
    response = request.analyse_text('Hello') 
    return 'hello' 

輸出頁面顯示「內部服務器錯誤」和錯誤日誌顯示導入錯誤,但它僅出現後,我加入響應行

2017-12-03 05:41:16,767: 

*************************************************** 
2017-12-03 06:48:14,534: Error running WSGI application 
2017-12-03 06:48:14,555: requests.exceptions.ProxyError: HTTPSConnectionPool(host='api.recast.ai', port=443): Max retries exceeded with url: /v2/request (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden',))) 
2017-12-03 06:48:14,555: File "/var/www/tarekhassan_pythonanywhere_com_wsgi.py", line 16, in <module> 
2017-12-03 06:48:14,556:  from hello import app as application 
2017-12-03 06:48:14,556: 
2017-12-03 06:48:14,556: File "/home/tarekhassan/bot/hello.py", line 7, in <module> 
2017-12-03 06:48:14,556:  def home(): 
2017-12-03 06:48:14,556: 
2017-12-03 06:48:14,556: File "/home/tarekhassan/.local/lib/python3.5/site-packages/recastai/apis/request/analyse.py", line 27, in analyse_text 
2017-12-03 06:48:14,556:  headers={'Authorization': "Token {}".format(token)} 
2017-12-03 06:48:14,556: 
2017-12-03 06:48:14,556: File "/usr/local/lib/python3.5/dist-packages/requests/api.py", line 111, in post 
2017-12-03 06:48:14,557:  return request('post', url, data=data, json=json, **kwargs) 
2017-12-03 06:48:14,557: 
2017-12-03 06:48:14,557: File "/usr/local/lib/python3.5/dist-packages/requests/api.py", line 57, in request 
2017-12-03 06:48:14,557:  return session.request(method=method, url=url, **kwargs) 
2017-12-03 06:48:14,557: 
2017-12-03 06:48:14,557: File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 475, in request 
2017-12-03 06:48:14,557:  resp = self.send(prep, **send_kwargs) 
2017-12-03 06:48:14,558: 
2017-12-03 06:48:14,558: File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 585, in send 
2017-12-03 06:48:14,558:  r = adapter.send(request, **kwargs) 
2017-12-03 06:48:14,558: 
2017-12-03 06:48:14,558: File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py", line 465, in send 
2017-12-03 06:48:14,558:  raise ProxyError(e, request=request) 
2017-12-03 06:48:14,559: *************************************************** 
2017-12-03 06:48:14,559: If you're seeing an import error and don't know why, 
2017-12-03 06:48:14,559: we have a dedicated help page to help you debug: 
2017-12-03 06:48:14,559: https://help.pythonanywhere.com/pages/DebuggingImportError/ 
+0

請添加完整的錯誤追蹤您的問題! –

+0

添加了錯誤跟蹤 –

+0

您的代理存在問題。 –

votes
answers
14 views
+50

AS3 Components in Flash Designer

In an ActionScript 2 project I can create a new MovieClip, right-click on it on the library and select "Component Definition" to add parameters that can be referenced inside the MovieClip. This parameters can be easily changed in the MovieClips's properties.

Now, I'm working on an ActionScript 3 project but haven't been able to figure out a way to obtain the values passed in those parameters.

I defined a parameter named "textToDisplay" but when I write the following in the Actions for the first frame I get an error:

trace(textToDisplay);

This is the error:

1120: Access of undefined property textToDisplay.

Do you know how to capture the value of that parameter?

Thanks

PS: I'm using Adobe Flash CS3 Professional on Windows XP

votes
answers
33 views
+50

Datagrids on Flex Mobile

Adobe tells us to not use Datagrid on mobile devices. I'm creating a Blackberry Playbook application that has more screen space to potentially display a table of data. So a few questions arise!

  • If I shouldn't use DataGrid, what should I use? (List doesn't count because in my application I have 10's of tables each with different numbers of columns and column widths)

  • Ok, if I have to use a Datagrid, how can I set the size of it to show exactly all the data? For example, some tables have rows of different lengths, so requestedRowCount='-1' doesn't seem to work (See example below)

The Code

    <s:DataGrid  requestedRowCount="-1" requestedColumnCount="-1" variableRowHeight="true"  styleName="dataGrid" id="partiesGrid" dataProvider="{arr1}"  skinClass="skins.DataGridSkin" click="navigator.pushView(view.AssessmentInvolvementEditView)">
        <s:columns>
        <s:ArrayList>
            <s:GridColumn dataField="name" headerText="Name" width="150"/>
            <s:GridColumn dataField="role" headerText="Role" width="150"/>
            <s:GridColumn dataField="startdate" headerText="Start" width="100"/>
            <s:GridColumn dataField="enddate" headerText="End" width="100"/>
            <s:GridColumn dataField="presponsibility" headerText="Response" width="150"/>
            <s:GridColumn dataField="pcarer" headerText="Carer" width="110"/>
            <s:GridColumn dataField="kworker" headerText="Worker" width="110"/>
            <s:GridColumn dataField="kteam" headerText="Team" width="110"/>
        </s:ArrayList>
        </s:columns>
    </s:DataGrid>`

The Result (Notice how the height doesnt fit the 3 rows, it adds space at the bottom)!enter image description here

votes
answers
15 views
+50

Actionscript memory management, garbage collection

This blog (and others) state that you should set object references to null inside your dispose() methods when cleaning up objects.

However, Actionscript 3 (with Flash Player 9) uses mark and sweep to clear out circular references for you. So I am wondering: is there really any reason to null out your object references?

votes
answers
26 views
+50

existing swf mp4 player? [closed]

I have a mp4 file put in my website, say http://example.com/a.mp4, I want a swf player that can be embedded into my html, and play the mp4 file. I don't know how to write actionscript so I just want to have an existing swf file.

Requirement: small, fancy, full function, ad free.

Thanks.

votes
answers
19 views
+50

Is there a way to force apache to return 404 instead of 403?

Is there a way how I can configure the Apache web server to return a 404 (not found) error code instead of 403 (forbidden) for some specific directories which I want to disallow to be accessed?

I found some solutions suggesting the use of mod_rewrite, like e.g.

RewriteEngine On
RewriteRule ^.*$ /404 [L]

As the purpose of sending 404 instead of 403 is to obfuscate the directory structure, this solution is too revealing, because it redirects to some different location which makes it obvious that the directory originally accessed does in fact exist.

votes
answers
40 views
+50

Cloud Firestore - 請求變量未按預期工作

0

我有一個簡單的Firestore數據庫,只有少數國家和每個國家/地區的城市。考慮每個國家的文件,即法國。同時使用請求變量讀取文檔面臨PERMISSION_DENIED異常以下兩種情況。Cloud Firestore - 請求變量未按預期工作

,供大家參考分享以下幾點 1)公司的FireStore配置 2),這是不工作 3)相關日誌每次失敗 3)類文件創建和讀取公司的FireStore數據庫 4)方法調用下面的具體配置場景

方案1 - 2之後應許可工作中的至少一種,但兩者都沒有工作

allow read : if request.resource.__name__ != null ; 
allow read : if request.resource.__name__ == null ; 

錯誤日誌

I/System.out的:firestoreTest ACTION_READ onFailureListener E = com.google.firebase.firestore.FirebaseFirestoreException:PERMISSION_DENIED:缺少或權限不足。 I/System.out的:firestoreTest getOnCompleteListener不成功


方案2 - 儘管文件名 '法國' 在數據庫中存在,它不工作。

allow read : if request.resource.__name__ == /databases/$(database)/documents/Countries/france ; 

錯誤日誌

I/System.out的:FireStoreTest.firestoreTest動作= [2],國= [法國],hashmapCountry = [零] I/System.out的:firestoreTest ACTION_READ onFailureListener e = com.google.firebase.firestore.FirebaseFirestoreException:PERMISSION_DENIED:權限缺失或不足。 I/System.out的:firestoreTest getOnCompleteListener不成功


方案3 - 沒有問題,而且運作良好。只有提出,因爲類似的情景2不工作

allow read : if resource.__name__ == /databases/$(database)/documents/Countries/france ; 

錯誤日誌

I/System.out的:FireStoreTest.firestoreTest行動= [2],國= [法國],hashmapCountry = [空] I/System。出:firestoreTest getOnCompleteListener成功{城市=巴黎}


基本配置測試場景

service cloud.firestore { 
    match /databases/{database}/documents 
    { 
     match /Countries/{country} 
      { 

     allow write : if true ;  
     allow read : // replace as per below scenario 

      }  
    }  
} 

}


方法來創建集合,僅需要被稱爲試驗前一次

HashMap<String, String > hashMap = new HashMap<>() ; 
hashMap.put("city","paris") ; 
fireStoreTest.firestoreTest(fireStoreTest.ACTION_ADD,"france",hashMap); 

方法可用於測試所有以下3場景

fireStoreTest.firestoreTest(fireStoreTest.ACTION_READ,"france",null); 

下面類是用來測試上述3個場景

package com.firestoreTest ; 

import com.google.firebase.firestore.DocumentReference; 
import com.google.firebase.firestore.DocumentSnapshot; 
import com.google.firebase.firestore.FirebaseFirestore; 

import java.util.HashMap; 
import java.util.Map; 


public class FireStoreTest { 

public static final int ACTION_ADD = 1 ; 
public static final int ACTION_READ = 2 ; 
private FirebaseFirestore firebaseFirestore ; 

public FireStoreTest() { 
    firebaseFirestore = FirebaseFirestore.getInstance() ; 
} 

public void firestoreTest(int action, String country, HashMap hashmapCountry) 

{ 
    System.out.println("FireStoreTest.firestoreTest action = [" + action + "], country = [" + country + "], hashmapCountry = [" + hashmapCountry + "]"); 

    DocumentReference documentReference = firebaseFirestore.collection("Countries").document(country) ; 

    switch (action) 
    { 
     case ACTION_ADD: 



      documentReference.set(hashmapCountry) 
        .addOnFailureListener(e-> System.out.println("firestoreTest ACTION_ADD onFailureListener e = "+e) ) 
        .addOnCompleteListener(task -> { 

         if (task.isSuccessful()) 
         { 
          System.out.println("firestoreTest setOnCompleteListener Successful "); 
         } else 
         { 
          System.out.println("firestoreTest setOnCompleteListener Unsuccessful " +task.getException()); 
         } 

        }) ; 





      break ; 

     case ACTION_READ: 

      documentReference.get() 
        .addOnFailureListener(e-> System.out.println("firestoreTest ACTION_READ onFailureListener e = "+e)) 
        .addOnCompleteListener(taskDocumentSnapshot->{ 

         if (taskDocumentSnapshot.isSuccessful()) 
         { 
          DocumentSnapshot documentSnapshot = taskDocumentSnapshot.getResult() ; 

          if (documentSnapshot.exists()) 
          { 
           Map mapDocumentSnapshot = documentSnapshot.getData() ; 

           System.out.println("firestoreTest getOnCompleteListener Successful "+mapDocumentSnapshot); 

          } else 
          { 
           System.out.println("firestoreTest getOnCompleteListener no data found "); 
          } 

         } else 
         { 

          System.out.println("firestoreTest getOnCompleteListener Unsuccessful "); 
         } 

        }) ; 
      break ; 
    } 

} 

}所有

votes
answers
29 views
+50

Laravel 5/Form安全(需要澄清)

4

不完全有信心我已經理解了Laravel形式的安全性。例如,如果表單包含 <input type="hidden" name="user_id"> 那麼顯然黑客可以在提交更新之前更改該值。 雖然我在CSRF看了here,但我還沒有完全理解這是否足夠的保護?Laravel 5/Form安全(需要澄清)

E.g.考慮到上述情況,如果我訪問網站並打開表單以編輯記錄,我可以查看但不能更改,並惡意更改「user_id」,表單是否受{{ csrf_field() }}保護或我必須僱用一些進一步的安全性,如Crypt::encrypt($id)隱藏user_id(保存在數據庫中)和Crypt::decrypt($id)

在客戶端瀏覽器中顯示行標識(如用戶標識)是否被認爲是不良做法(即使所有內容都是通過https發送的)?

很多謝謝

+0

csrf並沒有真正幫助您提及的特定情況。你想要做的是檢查後端是否正在發送的ID是否與您所期望的相同。 您也可以對該用戶標識進行編碼,然後在後端對其進行解碼。 全部取決於你實際想要達到的目標嗎? – matiit

+0

在這裏,https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)閱讀了解csrf是什麼以及csrf令牌會爲你辯護。 – matiit

+0

如果'user_id'字段不會被用戶*和*在表單中看不到,爲什麼發送給客戶端?將'user_id'服務器端放在SESSION上,而不是客戶端上。 – ThoriumBR

votes
answers
40 views
+50

如何使用SpringSecurity和JDBI

0

我想用Spring配置服務器。我想同時使用Spring安全和JDBI。 所以我配置了我的服務器(?)的數據源並將其鏈接到JDBI。但是我無法在WebSecurityConfig中使用這個數據源。如何使用SpringSecurity和JDBI

這是我的主要配置的Java文件:

@SpringBootApplication 
    @EnableAutoConfiguration 
    public class Application extends WebMvcConfigurerAdapter { 

     private static DBI dbi = null; 

     public static void main(String[] args) { 
      SpringApplication.run(Application.class, args); 
     } 


     static DBI getDbi() { 
      if(dbi == null) { 
       DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test", "ndl", "ndl"); 
       dbi = new DBI(ds); 
      } 
      return dbi; 
     } 
    } 

這是出於安全春

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private DataSource dataSource; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
       .antMatchers("/", "/home").permitAll() 
       .anyRequest().authenticated() 
       .and() 
       .formLogin() 
       .loginPage("/login.html") 
       .permitAll() 
       .and() 
       .logout() 
       .permitAll(); 
     http.csrf().disable(); 
    } 

    @Autowired 
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
     auth.jdbcAuthentication().dataSource(dataSource) 
       .usersByUsernameQuery(
         "select username,password from users where username=?") 
       .authoritiesByUsernameQuery(
         "select username, role from users where username=?"); 
    } 

} 

我得到這個錯誤的文件。

Field dataSource in rest.WebSecurityConfig required a bean of type 'javax.sql.DataSource' that could not be found. 

我試圖在類(而不是方法)中寫入DataSource ds。並添加註釋@Bean。但我得到了一個其他錯誤

public static DataSource ds = JdbcConnectionPool.create("jdbc:h2:mem:test", "ndl", "ndl"); 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Bean 
    public static DataSource getDataSource(){ 
     return ds; 
    } 

和錯誤

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/core/support/JdbcDaoSupport 

我希望你有什麼想法? 感謝;)

+0

什麼是JDBI .. –

+1

它的存在http://jdbi.org/getting_jdbi/? 這是一個工具,可以幫助你與數據庫 –

+1

我不需要這種工具。 但是我用Spring在其他項目中使用它,它很酷,所以我已經有很多可以輕鬆重用的代碼。 但我有春季安全問題。 –

votes
answers
14 views
+50

How to send secure AJAX requests with PHP and jQuery

The problem

So for a while now I've been experimenting with different AJAX approaches in sending data to a server that will be processed and stored inside a MySQL database.

The page that the AJAX request hits api.php, uses PHP's PDO prepared statements to save the data, so MySQL injections aren't really a problem and the passwords or data that needs to be encrypted are also handled by api.php which isn't what I'm asking here. My question relates more to how to ensure the data is secure when being transferred from the client to the server.

The approaches

I currently have (for the login example I have included below):

  • SSL Cert/HTTPS running on the domain.
  • Certain AJAX request (obviously not this login request example as there is no session to begin with) will only work if the PHP Session is valid across the site (used on both login.php and api.php in this example).
  • Rate limiting on api.php when accessing functions.
  • PHP PDO prepared statements when interacting with the database inside api.php.
  • Encrypts sensitive data inside api.php (not relevant to the question).

The questions

Finally, my questions are:

  1. Is this approach to using asynchronous HTTP (Ajax) requests safe enough to use rather than just submitting data to a PHP page and redirecting onwards? (As this way improves the user's experience).
  2. How can I check to know that the data my user's are sending hasn't been tampered with?
  3. Am I reasonably doing enough to protect my user's data, if not, what else can I do?

The example

I understand everyone has different approaches to handling their site's data and transporting that data. I also understand that no matter what you do, you can never be 100% protected, as there may be vulnerabilities and ways around your system that you can't account for. I'm looking for feedback/improvements on my general approach in sending data securely rather than criticism of the specific code below as it is only an example. But any constructive answers are welcome. Thanks for taking the time to read/answer.

function loginUser() {
    var process = "loginUser";
    var data = $("form").serializeArray();
    data[1].value = SHA512(data[1].value); // sha then encrypt on api.php page 
    data = JSON.stringify(data);

    $("#loginButton").html('<i class="fa fa-spinner fa-pulse fa-lg fa-fw"></i> Login');
    $.ajax({
        type: "POST",
        url: "api.php",
        data: {"process": process, "data": data},
        success: function(data) {
            if (data.response.state == "success") {
                // if api.php returns success, redirect to homepage
            } else {
                // if api.php returns failure, display error
            }  
        },
        error: function(jqXHR, textStatus, errorThrown, data) {
            // error handling
        },
        dataType: "json"
    });
}
votes
answers
19 views
+50

Why is JsonRequestBehavior needed?

Why is Json Request Behavior needed?

If I want to restrict the HttpGet requests to my action I can decorate the action with the [HttpPost] attribute

Example:

[HttpPost]
public JsonResult Foo()
{
    return Json("Secrets");
}

// Instead of:
public JsonResult Foo()
{
    return Json("Secrets", JsonRequestBehavior.AllowGet);
}

Why isn't [HttpPost]sufficient?
Why the framework "bugs" us with the JsonRequestBehavior.AllowGet for every JsonResult that we have. If I want to deny get requests I'll add the HttpPost attribute.

votes
answers
23 views
+50

Using openssl to get the certificate from a server

I am trying to get the certificate of a remote server, which I can then use to add to my keystore and use within my java application.

A senior dev (who is on holidays :( ) informed me I can run this:

openssl s_client -connect host.host:9999

To get a raw certificate dumped out, which I can then copy and export. I receive the following output:

depth=1 /C=NZ/ST=Test State or Province/O=Organization Name/OU=Organizational Unit Name/CN=Test CA
verify error:num=19:self signed certificate in certificate chain
verify return:0
23177:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1086:SSL alert number 40
23177:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:

I have also tried with this option

-showcerts 

and this one (running on debian mind you)

-CApath /etc/ssl/certs/ 

But get the same error.

This source says I can use that CApath flag but it doesn't seem to help. I tried multiple paths to no avail.

Please let me know where I'm going wrong.

votes
answers
17 views
+50

對象的ArrayList通過級Java

2

我已經創建了一類的基團,其包含字符串和布爾對象的命名擴展「配件對象的ArrayList通過級Java

然後創建ArrayList類,然後將其添加到名爲「列表AccessoriesList「,從那裏輸入更多的數據。

然後我使用for循環創建了一個從ArrayList接收數據的附件對象。這仍然迴應爲空。

我環顧四周,發現最常見的問題是變量尚未初始化。所以,我想,仍然得到同樣的結果

所以這裏是配件

public static class Accessories { 

    Accessories(String Accessoriesname, boolean cold, boolean warm, boolean hot, boolean rain, boolean snow, boolean ice, boolean formal, boolean informal) { 
    } 
    String name =null ; boolean cold; boolean warm; boolean hot; boolean rain; boolean snow; boolean ice; boolean formal; boolean informal; 
} 

這裏是AccessoriesList

public ArrayList createAccessories() { 
    ArrayList<Accessories> Accessoriesist = new ArrayList<Accessories>(); 
    Accessoriesist.add(new Accessories("Bag", true, true, true, false, false, false, true, true)); 
    Accessoriesist.add(new Accessories("Gloves", true, false, false, true, true, true, true, true)); 
    Accessoriesist.add(new Accessories("Hat", true, false, false, true, true, true, false, true)); 
    Accessoriesist.add(new Accessories("Poncho", false, true, true, false, false, false, false, true)); 
    Accessoriesist.add(new Accessories("Scarf", true, true, false, true, true, true, true, true)); 
    Accessoriesist.add(new Accessories("Sunglasses", false, true, true, false, false, false, true, true)); 
    Accessoriesist.add(new Accessories("Tie", true, true, true, true, true, true, true, true)); 

    Accessories getAccessories =null; 
    String getname = null; 
    for (int i = 0; i < Accessoriesist.size(); i++) { 
     getAccessories = Accessoriesist.get(i); 
     getname = getAccessories.name; 
     System.out.println("this is the name : " + getname); 
     System.out.println("this is the Accessoriesist : " + Accessoriesist.get(i)); 
    } 
    return Accessoriesist; 
} 

取而代之的接收信息,我收到散列碼。

我想拋出一個配件對象(原始)從ArrayList,到另一個配件對象(新)。我試圖拉從附件對象(新)

votes
answers
43 views
+50

某些移動用戶的SSL安全錯誤

0

我最近將我的網站arvandkala.ir更改爲https。 問題是某用戶(特別是手機上)得到SSL pravicy Error 用戶手機時鐘沒問題, 在網站上沒有任何混音數據。 火狐錯誤代碼:某些移動用戶的SSL安全錯誤

SEC_ERROR_UNKNOWN_ISSUER 

發行人是Certum和Firefox的信賴。

enter image description here enter image description here

+0

請參閱https://www.ssllabs.com/ssltest/analyze.html?d=arvandkala.ir,其中顯示「證書鏈不完整」,然後單擊以在「證書路徑」下展開。一些瀏覽器可以使用AIA自己獲取丟失的證書,但有些則不能。 PS:時鐘錯誤會顯示爲'過期'或可能'無效',但從未'未知'。 –

+0

@ dave_thompson_085感謝評論,我看到連鎖是不完整的,但如何解決。我測試了幾種方式,但尚未解決yet.please幫助:) – Radian

votes
answers
31 views
+50

爲什麼媒體查詢中定義的字體顏色不起作用?

0

爲什麼媒體查詢中定義的字體顏色不起作用?例如,爲什麼媒體查詢中定義的字體顏色不起作用?

@media (min-width: 576px){ 
    html { 
     color: red !important; 
     font-size: 1.2rem; 
    } 
} 

字體大小有效,但不是顏色即使有!重要。

這是引導4

+0

[工作得很好(https://jsfiddle.net/dcfw8v70/)。 – Ivar

+0

嘗試使用Web瀏覽器中的開發人員工具來查看正在應用的樣式;另一種風格(比如p標籤或body)很可能會覆蓋應用於html的風格。 – KellyMarchewa

+0

他們是,你只是有別的東西否決了上述。 'min-width:576px'實際上與「* red」相同,如果其他地方沒有定義其他地方*「...!important;」在這裏沒有幫助,因爲您處於層次結構的最頂層。 – davidkonrad

votes
answers
27 views
+50

如何讓嵌入式視頻在縮小的瀏覽器中響應

0

因此,我在全寬瀏覽器中使用嵌入式視頻的方式,但是當它縮小到小尺寸瀏覽器和下面時,我無法確定找出響應的方式,所以它保持在瀏覽器的中心位置。如何讓嵌入式視頻在縮小的瀏覽器中響應

我正在使用Bootstrap的網格系統旁邊的文本進行響應。我希望當瀏覽器觸及中等大小以下時,將視頻疊加在文本下方,並且當它處於中等大小的瀏覽器中時,我已成功地將視頻集中在媒體查詢中,但無法將其集中在小和超小的瀏覽器大小。這有意義嗎?

.section1Text { 
 
    padding-top: 35px; 
 
} 
 

 
.section1Text h2 { 
 
    font-weight: 100; 
 
    font-size: 2.9em; 
 
    letter-spacing: 1px; 
 
} 
 

 
.section1Btn { 
 
    background-color: #2e3233; 
 
    border-style: solid; 
 
    border-width: 0px 0px 3px 0px; 
 
    border-color: #121313; 
 
    border-radius: 50px; 
 
    padding-top: 15px; 
 
    padding-bottom: 15px; 
 
    margin-top: 30px; 
 
    font-size: 1.45em; 
 
    color: #ffffff; 
 
    font-weight: 700; 
 
    transition: all 0.3s ease-in-out 0s; 
 
} 
 

 
.video-responsive { 
 
    padding-top: 45px; 
 
    padding-bottom: 45px; 
 
    float: right; 
 
} 
 

 
.video-responsive iframe { 
 
    width: 560px; 
 
    height: 315px; 
 
} 
 

 

 
/*section1 media queries*/ 
 

 
@media (max-width: 992px) { 
 
    .video-responsive { 
 
    padding-top: 45px; 
 
    padding-bottom: 45px; 
 
    margin-right: 35px; 
 
    } 
 
    .video-responsive iframe { 
 
    width: 672px; 
 
    height: 378px; 
 
    } 
 
}
<section class="section1"> 
 
    <div class="container"> 
 
    <div class="row"> 
 
     <div class="section1Text col-md-4"> 
 
     <h2 class="text-center">What We Have to Offer</h2> 
 
     <p class="text-center">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vel massa iaculis, posuere augue et, pharetra ipsum. Suspendisse metus ex, pellentesque id dolor in, vehicula varius tortor. Nam auctor ante nisi.</p> 
 
     <div class="col-xs-8 col-xs-offset-2"> 
 
      <a class="btn section1Btn btn-block" href="#">Learn More</a> 
 
     </div> 
 
     </div> 
 
     <div class="video-responsive"> 
 
     <iframe width="560px" height="315px" src="https://www.youtube.com/embed/bsY2GdBEvSA?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</section>

votes
answers
17 views
+50

$(window).width() not the same as media query

I am using Twitter Bootstrap on a project. As well as the default bootstrap styles I have also added some of my own

//My styles
@media (max-width: 767px)
{
    //CSS here
}

I am also using jQuery to change the order of certain elements on the page when the width of the viewport is less that 767px.

$(document).load($(window).bind("resize", checkPosition));

function checkPosition()
{
    if($(window).width() < 767)
    {
        $("#body-container .main-content").remove().insertBefore($("#body-container .left-sidebar"));
    } else {
        $("#body-container .main-content").remove().insertAfter($("#body-container .left-sidebar"));
    }
}

The problem I am having is that the width calculated by $(window).width() and the width calculated by the CSS doesn't seem to be the same. When $(window).width() returns 767 the css calculates it the viewport width as 751 so there seems to be a 16px different.

Does anyone know what is causing this and how I could solve the problem? People have suggested that the width of the scrollbar isn't being taken into considering and using $(window).innerWidth() < 751 is the way to go. However ideally I want to find a solution that calculates the width of the scrollbar and that is consistent with my media query (e.g where both conditions are checking against the value 767). Because surely not all browsers will have a scrollbar width of 16px?

votes
answers
32 views
+50

當窗口變小時,如何讓四個響應孩子變成2×2的網格?

0


我想創建四個彼此相鄰的子項。現在,當視口寬度變小時,這些應該會摺疊成兩兩兩格。 (不太重要:當它變得更小時,它們應該是父寬度的100%。)現在我的問題不是通過媒體查詢來創建這個問題。問題是第一個孩子的身高比第二個孩子的身高高。當他們倒向2×2網格時,第三個孩子總是放在第二個孩子下面,而不是第一個孩子(我想要它)。
我也嘗試過flexbox,但據我所知,沒有可能讓它變成4乘1,2乘2或1乘4.這個問題只發生在一些特定的視口寬度,因爲行數是(在某些情況下)在第一個和第二個孩子中是相等的。
要明白我的意思,這裏是一個片段:當窗口變小時,如何讓四個響應孩子變成2×2的網格?

*{ 
 
    padding: 0px; 
 
    margin: 0px; 
 
} 
 

 
#parent{ 
 
    width: 960px; 
 
    max-width: 90%; 
 
    font-size: 1rem; 
 
    margin: auto; 
 
    background-color: green; 
 
} 
 

 
.child{ 
 
    width: 23%; 
 
    margin: 0px 1%; 
 
    background-color: yellow; 
 
    float: left; 
 
} 
 

 
@media (max-width: 60rem){ 
 
    .child{ 
 
    width: 46%; 
 
    margin: 2%; 
 
    float: left; 
 
    } 
 
} 
 

 
@media (max-width: 30rem){ 
 
    .child{ 
 
    width: 100%; 
 
    margin: 0; 
 
    float: none; 
 
    } 
 
}
<div id="parent"> 
 
    <div class="child"> 
 
    <h1>Lorem ipsum</h1> 
 
    <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed</p> 
 
    </div> 
 
    <div class="child"> 
 
    <h1>Lorem ipsum</h1> 
 
    <p>Lorem ipsum dolor sit amet, consetetur sadipscing</p> 
 
    </div> 
 
    <div class="child"> 
 
    <h1>Lorem ipsum</h1> 
 
    <p>Lorem ipsum dolor sit amet, consetetur</p> 
 
    </div> 
 
    <div class="child"> 
 
    <h1>Lorem ipsum</h1> 
 
    <p>Lorem ipsum dolor sit amet</p> 
 
    </div> 
 
</div>

+1

使用內嵌塊代替浮點數。請參閱[DIV以非線性方式浮動](https://stackoverflow.com/q/47210837/1016716)。 –

votes
answers
32 views
+50

面對Go同步映射的併發問題

1

我遇到了Go的sync.Map問題。以下是詳細內容:面對Go同步映射的併發問題

我創建了一個全球同步的地圖,如:

var MySyncGlobalMap = sync.Map{} 

和事件我填充這個地圖與預期結構 map[int64]map[string]interface{}。所以基本上我想填充同步圖與關鍵作爲int64和價值作爲另一同步圖結構map[string]interface{}。下面是我如何填充地圖:

//below is the innerSync map. recSet is returned from DB call in the format : []map[string]interface{} 
var innerSyncMap = sync.Map{} 
for _, record := range recSet { 

    sKey := record["key"].(string) 
    value := record["value"] 
    innerSyncMap.Store(sKey, value) 
} 
MySyncGlobalMap.Store(jobID, innerSyncMap) 

現在會有多個線程將被訪問該地圖,並做一些操作。將會不斷更新內部同步映射。一旦內部同步映射的鍵完成處理,該鍵將從該映射中刪除。

一旦內部同步映射變爲空白,我就會知道一個作業完成。

現在,因爲有多個線程訪問該映射我收到了恐慌:

Fatal error: concurrent read and write

我還是想知道,即使使用同步映射後我面對這個問題。

任何人都可以指出我做錯了什麼?

+2

請提供顯示錯誤的代碼示例。看起來像你正在創建普通地圖(例如,使用'make(map [string] interface {}')並以同時的方式訪問它們。 –

+0

@ArmanOrdookhani更新了這個問題。 –

+1

一些goroutines之間有'recSet'共享嗎?試着像'go run -race main.go'那樣運行你的代碼來獲取你正在訪問地圖的地方的棧跟蹤。 –

votes
answers
24 views
+50

C++ qthread同時啓動2個線程

1

我有兩個線程一和兩個。由它們各自的類在頭文件中定義。我想在第一個線程啓動時啓動第二個線程。在第一個產生的意外結果的構造函數中創建並啓動第二個線程。 我的頭文件「header.h」C++ qthread同時啓動2個線程

#ifndef HEADER 
#define HEADER 
#include <QtGui> 
class One:public QThread 
{ 
public: 
    One(); 
    void run(); 

}; 

class Two:public QThread 
{ 
public: 
    Two(); 
    void run(); 
}; 
#endif 

我的類文件「的main.cpp」

#include "header.h" 
#include<iostream> 
using namespace std; 

One::One() 
{ 
/* the output just hangs at thread two and does not get to thread one run */ 
Two b; 
b.start(); 
b.wait(); 

} 
void One::run() 
{ 
    cout<<"One run
"; 
    int i=0; 
    for(;;) 
    { 

     i++; 
     cout<<"+++ "<<i<<endl; 
     if(i==10) 
      break; 
     sleep(3); 
    } 
} 

Two::Two() 
{ 

} 
void Two::run() 
{ 

    cout<<"Two run
"; 
    int i=0; 
    for(;;) 
    { 

     i--; 
     cout<<"----- "<<i<<endl; 
     sleep(3); 
    } 
} 
int main(int argc,char* argv[]) 
{ 
    One a; 
    // Two b; 
    a.start(); 
    // b.start(); 
    a.wait(); 
    // b.wait(); 
    return(0); 

} 

這是我多麼希望輸出運行工作代碼。

編輯:改變了代碼,因此現在 兩個線程都正確 獨立

如何啓動與第一線沿第二個線程,而不會在主即明確地調用兩個。

int main(int argc,char* argv[]) 
{ 
    One a; 
    Two b; 
    a.start(); 
    b.start(); 
    a.wait(); 
    b.wait(); 
    return(0); 
} 

螺紋兩者的調用和處理應該由一個線程來完成..

+0

目前我所擁有的是兩個獨立運行的線程,它們分開啓動。我想要做的是在線程啓動時調用第二個線程。 – 2011-03-08 10:58:18

+0

而這沒有意義。該線程在您啓動時調用。即使您可以從一個線程* object *調用另一個線程* context *到另一個線程,您也無法調用 – Erik 2011-03-08 11:03:51

+0

@Erick我已更改了代碼。移除一個線程上下文的調用。我試過在線程的構造函數中調用線程2,這是否是錯誤的?因爲我似乎看不到線程的運行輸出。 – 2011-03-08 11:21:02

votes
answers
24 views
+50

是否可以訪問鍵盤控制器的內部製作/中斷代碼緩衝區?

2

根據這個網頁:http://stanislavs.org/helppc/8042.html鍵盤控制器維護它自己的內部16字節的make/break代碼緩衝區。是否可以訪問鍵盤控制器的內部製作/中斷代碼緩衝區?

「鍵盤的內部控制器最多可緩衝16個字節的製造/中斷代碼信息,這在所有PC系統中都很常見,不應與BIOS維護的(32字節)鍵盤緩衝區混淆。

能夠訪問此緩衝區對我來說在我的8086彙編語言程序中非常有用(假設更新速度比BIOS維護的32字節緩衝區更快)。

除了輪詢端口60h之外,還有辦法從內部緩衝區中獲取這些製造/中斷代碼嗎?

+1

那麼最簡單的方法就是正常讀取掃描碼,不必輪詢,可以使用中斷處理程序將代碼放入RAM中的緩衝區,就像BIOS一樣。有文件記錄的控制器命令可以讓你讀取8042的RAM,在真實的8042上,它可能會在某處包含緩衝的掃描碼,但我不認爲標準的確切位置。現代的鍵盤控制器可能無法模擬這一點。 –

+0

但在內存中的其他地方使用它有什麼用處?你的意思是訪問掃描代碼會更快,而無需加載不同的段?我同意這一點。我只是真的希望將最後一個break/make代碼作爲輸入到我的程序中,這就是爲什麼我使用端口60h,但訪問緩衝區會很有用,因爲人爲錯誤通常會導致我的程序出現問題。通常,我會在讓前一個鍵覆蓋我的程序需要的代碼之前一秒鐘敲一個鍵,並用我希望忽略的中斷代碼。訪問緩衝區將允許我確定丟失的代碼。 –

+0

我已經忽略了與最後接受的make代碼不一致的中斷代碼,但我仍經常遇到與先前遇到的代碼相對應的亂序中斷代碼。例如,在我的遊戲中導致不希望的停止移動精靈。我應該提到的是,BIOS中的32字節緩衝區有時會錯過分割的第二個make代碼。我想象一個非常高頻率的中斷可以解決這個問題,但我仍然不知道如何編程這兩個PIC。我在業餘時間一直在研究它的最近幾天。 –

votes
answers
40 views
+50

如何從OpenCL代碼啓動另一個線程?

1

我的算法包含兩個步驟:如何從OpenCL代碼啓動另一個線程?

  1. 數據生成。在這一步中,我生成循環中的數據數組,作爲一些函數結果
  2. 數據處理。對於這一步,我編寫了處理在上一步中生成的數據數組的OpenCL內核。

現在第一步運行在CPU上,因爲它很難並行化。我想在GPU上運行它,因爲每一代都需要一些時間。我想立即爲已經生成的數據運行第二步。

我可以從當前運行的內核運行另一個opencl內核在單獨的線程中嗎?或者它在調用內核的某個線程中運行?

一些僞碼,說明我的觀點:

__kernel second(__global int * data, int index) { 
    //work on data[i]. This process takes a lot of time 
} 

__kernel first(__global int * data, const int length) { 
    for (int i = 0; i < length; i++) { 
     // generate data and store it in data[i] 

     // This kernel will be launched in some thread that caller or in new thread? 
     // If in same thread, there are ways to launch it in separated thread? 
     second(data, i); 
    } 
} 
votes
answers
22 views
+50

在不同的線程中啓動一個Java類

2

我在想如何從不同的線程調用一個類,並讓所有的調用在它自己的線程中運行?假設我有三個線程,每個線程都需要調用anotherClass.getBS(),但這些調用可能同時發生,並且沒有理由在當時執行它們。死鎖不是問題。在不同的線程中啓動一個Java類

謝謝!

votes
answers
18 views
+50

線程內線程的優先級

6

假設您有一個程序啓動兩個線程ab,並且b啓動另外10個線程。 a是否獲得了「關注」的一半,而b及其線索分享另一半,還是他們都平等分享?如果默認情況下答案是後者,你怎麼能達到前者?謝謝!線程內線程的優先級

votes
answers
34 views
+50

如何啓動不阻塞Java主線程的後臺線程?

3

我有以下的Java代碼:如何啓動不阻塞Java主線程的後臺線程?

public static void main(String[] args) 
{ 
    new Thread(new MyRunnable()).run(); 
    showGUI(); 
} 

我的問題是啓動MyRunnable塊爲主線,造成showGUI不叫,直到它完成運行。我想要做的程序是產生MyRunnable,並允許它在後臺獨立運行,使主線程忘掉它,然後繼續做它想做的事情(如致電showGUI)。

votes
answers
12 views
+50

如何讓線程等到另一個線程完成該方法執行

0

雖然這個問題看起來很基本,但是我的場景與其他帖子@stackoverflow完全不同。我使用JPA &運動衫(REST)實現彈簧。每當我打2個請求同時從捲曲到我的Java REST方法以更新數據庫資源,首先請求被成功執行,但第二個請求被失敗,樂觀鎖定異常:如何讓線程等到另一個線程完成該方法執行

javax.persistence.OptimisticLockException:異常 [ EclipseLink-5006](Eclipse持久性服務 - 2.5.2.v20140319-9ad6abd):org.eclipse.persistence.exceptions.OptimisticLockException異常 說明:該對象無法更新,因爲它已更改,或者自上次讀取以來已刪除 。

我已經嘗試把更新後的代碼放在同步塊中,但它沒有奏效。

我也試過聲明rest方法是同步的,但沒有工作。

現在我想讓我的方法被第一個請求執行,並希望第二個請求等到第一個請求完成它的執行。

我已經實現了這個使用static變量,但不想使用static由於代碼標準的變量。

有人可以給這個有效的解決方案嗎?

+1

使用synchronized執行同步塊內的數據庫操作應該工作,只要你同步上同一個實例。提供有關您用作鎖的更多細節以及您如何使用它。 – erickson

+0

什麼持久性告訴你,你的第二次更新有第一次更新的比賽(根據你的問題,這是真的)。因此,無論哪個更新第二次到達內部持久化的同步塊,都沒有看到第一個更新,並且因爲它們兩個的更新實體是相同的,所以第二次更新被拒絕,因爲它的數據是「過時的」。在這種情況下,理想情況下應該執行的操作是清除陳舊請求,並使用更新的實體重新啓動它,然後再次嘗試更新。 –

+0

你有映射類中有相應表列的'@ Version'字段嗎? – eg04lt3r

votes
answers
31 views
+50

Mutex不同步C++

0

我有2個進程。第一個將一些數據發送給另一個,同步每一步。 實際發送的數據如下:Mutex不同步C++