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

Monitoring Memcached with PHP script

I've written a PHP script that I've scheduled with CRON to run every minute. The goal of the script is to verify that the memcached server is online. My strategy is simply to attempt to connect to the memcached server. If I connect successfully, I close the connection. If I do not successfully connect, I send an email alerting that memcached is offline.

My question: is this a sufficient test that memcached is up and running, or is it common practice to do more than just connect to memcached? Should I also test that I can set and retrieve a key/value pair?

Also, in the future, we may want to do more extensive monitoring of memcached so we can track memory usage, connections, number of requests, etc. Are there open source libraries for doing this from PHP? If so, which ones have performed nicely in your experience?

votes
answers
53 views
+50

laravel預先加載()與創建父模型

2

我創建一個回覆模型,然後試圖返回的對象與它的主人關係後負荷()。這裏是一個返回一個空對象的代碼:laravel預先加載()與創建父模型

//file: Thread.php 
//this returns an empty object !!?? 
public function addReply($reply) 
{ 
    $new_reply = $this->replies()->create($reply); 
    return $new_reply->with('owner'); 
} 

然而,如果我交換用()爲負載()的方法方法加載所有者關係,我得到預期的結果。也就是說,返回它的回覆對象的相關所有者關係:

//this works 
{ 
    $new_reply = $this->replies()->create($reply); 
    return $new_reply->load('owner'); 
} 

我不明白爲什麼。尋找澄清。

感謝, Yeasir

+1

https://stackoverflow.com/questions/26005994/laravel-with-method-versus-load-method這裏有一個很好的問題 – Sohel0415

votes
answers
39 views
+50

將Ratchet WsServer與React SecureServer結合使用(WSS/SSL)

0

我們正試圖通過安全連接(WSS)實現websocket,並在我們的項目中實現了cboden/ratchet。所有Works正常連接罰款。環顧文檔和Github項目頁面,似乎新的React SecureServer類尚未在Ratchet中實現。將Ratchet WsServer與React SecureServer結合使用(WSS/SSL)

在我們發現的問題a post about it,它將不被支持,直到後來的版本,但是,我們現在需要它:D 在問題報告中,他們建議使用新的React SecureServer類與Ratchet類組合。我們嘗試並得到了一個致命的錯誤:

Catchable fatal error: Argument 1 passed to ReactSocketSecureServer::__construct() must be an instance of ReactSocketServer, instance of RatchetHttpHttpServer given.

部分地方出了問題:

$webServer = new RatchetServerIoServer(
    new ReactSocketSecureServer(// Using React class here as suggested 
     new RatchetHttpHttpServer(
      new RatchetWebSocketWsServer(
       new RatchetWampWampServer(
        $pusher 
       ) 
      ) 
     ) 
    ), 
    $webSock, 
    array(
     'local_cert' => 'xxxx.pem', 
     'allow_self_signed' => true, 
     'verify_peer' => false 
    ) 
); 

我們正在做一些愚蠢的事? :P

votes
answers
22 views
+50

我想獲取所有目錄名稱

0

我需要老年人幫助使根目錄下拉列表使用PHP。我幾乎創建了但有一個問題沒有得到根目錄。我想獲取所有目錄名稱

如家/ ABC /所有目錄我想

代碼示例

 <? 
$dirs = array_filter(glob('/*'), 'is_dir'); //this code getting main root folders 

print_r($dirs); // array showing root directory 
?> 

但我想從家裏所有的目錄/用戶名 這可能嗎?

+0

is iframe code is related to your current problem?我不認爲這是。另外再描述一下: - 「但有一個問題沒有得到根目錄」。還有,你在傳遞'home/abc /'來獲取所有子目錄? –

+0

我錯過了你的代碼。 – Neil

+0

讓我用簡單的語言來描述,並更新我的代碼 –

votes
answers
46 views
+50

mod_rewrite不能在Laravel 5

1

使用Laravel 5.5,試圖訪問http://127.0.0.1:8000/test/search/357我得到一個頁面無法找到錯誤。非其他解決方案已爲我工作。我的.htaccess文件駐留在根目錄下,看起來像這樣:mod_rewrite不能在Laravel 5

<IfModule mod_rewrite.c> 
<IfModule mod_negotiation.c> 
    Options -MultiViews 
</IfModule> 

Options +FollowSymLinks 
RewriteEngine On 

RewriteBase "/test/" 

# Redirect Trailing Slashes If Not A Folder... 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} !^/test/ # <=== NEW LINE!!!! 
RewriteRule ^(.*)/$ /$1 [L,R=301] 

# Handle Front Controller... 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule^index.php [L] 


RewriteRule ^/test/search/(.*)$ /test/search?m_id=$1&a=1 [QSA, L] 

# Handle Authorization Header 
RewriteCond %{HTTP:Authorization} . 
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] 

任何幫助,將不勝感激。謝謝。

+0

你有語法錯誤。您打開IfModule兩次,但只關閉一次。除此之外,我認爲在laravel中使用htaccess重定向而不是路由並正確設置虛擬主機並不是一個好主意。 – ElChupacabra

votes
answers
27 views
+50

How to reindex Sphinx with MySQL

I'm trying to figure out how I should be reindexing Sphinx. I'm using v 0.9.9, so I don't have the ability to do real-time updates of the index.

I think I read somewhere that this can be done using a cron job, and that the index does not need to be entirely rebuilt (so no stopping the daemon). That said, I've never written nor run any cron jobs, so no idea where to even start.

Any thoughts?

votes
answers
25 views
+50

從變量中添加參數以提取json數據

0

我正在使用API??來提取機場信息數據並以json的形式打印數據。從變量中添加參數以提取json數據

我使用json_decode()來存儲此JSON到數組(我用的是,真正的)

我有一個循環,檢查到達的飛機的數量並且取得了成功,因爲如果有15個進港航班也可以打印出一串文字15次。但是,解碼json時,我需要使用參數來獲取信息。例如,如果我想要得到多少來的,我需要做的是這樣的:

$jsonDecode = json_decode($json_file, true); 
print_r($jsonDecode['AirportBoardsResult']['arrivals']['num_flights']); 

這給了多少來港有,其結果可以被放置到一個變量是這樣的:

$arrivals = $jsonDecode['AirportBoardsResult']['arrivals']['num_flights']; 

如果我打印它,它將打印正確的整數。 然而,要獲得首飛FLIGHTNUMBER,你需要做的是這樣的:

$flightnumber = $jsonDecode['AirportBoardsResult']['arrivals']['flights']['0']['ident']; 

其中「0」是第一次飛行,「1」是第二等... 我試着創建一個for循環來獲取所有到達的flightnumber,這裏的代碼:

$initialCode = $jsonDecode['AirportBoardsResult']['arrivals']['flights']; 

for($arrivalInt = $arrivals; $arrivalInt > 0; $arrivalInt--) { 
    $flightnumbers = $initialCode . $arrivalInt . 'ident'; 
    echo $flightnumbers; 
} 

但這似乎並不奏效。我試圖使用array_push在最後添加$ arrivalInt和'ident',但是沒有。我試圖做這樣的:

for($arrivalInt = $arrivals; $arrivalInt > 0; $arrivalInt--) { 
    $flightnumbers = $initialCode . "[" . "'" . $arrivalInt . "'" . "]" . "[" . "'" . "ident" . "'" . "]"; 
    echo $flightnumbers; 
} 

但相同的結果:(結果我得到的是$ initialCode的只是回聲

基本上,我只是想將參數添加到json_decode結束。 。

任何幫助被讚賞:)

+0

我想你好想參數 –

+0

$抵港= $ jsonDecode [ 'AirportBoardsResult'] [ '到達'] [ '飛行']; –

+0

我想將參數['$ arrivalInt']添加到$ jsonDecode的末尾,基本上將變量或整數的數據添加到$ jsonDecode的末尾 – RAZERZ

votes
answers
15 views
+50

如何通過在函數中傳遞部分變量名稱來獲取變量名稱

0

我試圖創建一個函數,我將重複使用該函數以通過名稱獲取對象,將部分對象名稱傳入函數。如何通過在函數中傳遞部分變量名稱來獲取變量名稱

我嘗試過使用下面的代碼片段,它正在輸出undefined

如何通過將其部分名稱傳入此函數來獲取實際變量?

function writeObject(name){ 
 
    console.log(placeObjects[name+'Item']); 
 
} 
 

 
function placeObjects(){ 
 
    var availableObjects = new Array(); 
 

 
    availableObjects.push(new Object('image','kepler')); 
 
    availableObjects.push(new Object('image','lightning')); 
 
    availableObjects.push(new Object('image','tomato')); 
 
    availableObjects.push(new Object('image','us')); 
 
    
 
    var topItem = availableObjects[0]; 
 
    var leftItem = availableObjects[1]; 
 
    var bottomItem = availableObjects[2]; 
 
    var rightItem = availableObjects[3]; 
 

 
    writeObject('top'); 
 
    writeObject('left'); 
 
} 
 

 
placeObjects();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

@fubar感謝,但我會如何使用動態名稱指的是變量在其當前的範圍,因爲我想幹什麼? –

+1

通過拼接名稱部分來使用變量訪問的一般想法很糟糕。想象一下,你將使用代碼縮小,你所有的var變量將改變名稱,邏輯將變得不正確。我會建議使用名稱作爲某些對象的鍵。 –

+0

@SerejaNagin好的,我怎樣才能通過傳遞它的全名而不是連接它來引用變量?或者你能否舉一個你建議用名稱作爲對象鍵的例子?我認爲我的問題可能與查找變量的父項有關。 –

votes
answers
35 views
+50

執行雙AJAX調用

-1

我已經開始了我的第一個AJAX項目,並且我正在嘗試編寫雙AJAX函數,其中第一個函數的輸出字符串(「venue_ID」)被第二個AJAX函數用於輸出字符串(img_Url)。但我沒有取得任何成功。對於我的代碼下面的任何建議將不勝感激;執行雙AJAX調用

$(function(){ 
 
var api_url = 'https://api.foursquare.com/v2/venues/search?ll=4.89996,114.928457&client_id=DKVNHNM2I15Y0TF1RNAEF1FPQHJPCCUPHBMJKGFHXUQITWHC&client_secret=XLCPTHFDAVNTUUAOCMNDQLWAS4TXZOGAXV5A2L1AAK5QNJZS&v=20131016&query=bake+culture'; 
 
var $info = $('#info'); 
 

 
$.ajax({ 
 
    type: 'GET', 
 
    url: api_url, 
 
    data: {format: 'json'}, 
 
    dataType: 'json', 
 
    success: function (info) { 
 
     var response = info.response.venues[0]; 
 
     var venue_id = response.id; 
 
     console.log('success', info); 
 

 
     $info.append(venue_id); 
 
     var $pic = $('#pic'); 
 

 
     var baseUrl = 'https://api.foursquare.com/v2/venues/'; 
 
     var fsParam = '/?client_id=DKVNHNM2I15Y0TF1RNAEF1FPQHJPCCUPHBMJKGFHXUQITWHC&client_secret=XLCPTHFDAVNTUUAOCMNDQLWAS4TXZOGAXV5A2L1AAK5QNJZS&v=20131016'; 
 
     var picUrl = baseUrl + venue_id + fsParam; 
 

 
     $.ajax({ 
 
      type: 'GET', 
 
      url: picUrl, 
 
      data: {format: 'json'}, 
 
      dataType: 'json', 
 
      success: function (pic) { 
 
       var venue_data = pic.response.venue; 
 
       var img_url = venue_data.bestPhoto.prefix + '192x144' + venue_data.bestPhoto.suffix; 
 
       console.log('success', pic); 
 

 
       $pic.append(img_url); 
 
      } 
 
     }); 
 
    } 
 
}); 
 
});
<html lang='en'> 
 
    <head> 
 
    <title>AJAX Demo</title> 
 
    </head> 
 
    <body> 
 
    <div> 
 
     <h4>AJAX Demo</h4> 
 
     <div id="info"></div> <!-- To test 1st AJAX output --> 
 
     <div id="pic"></div> 
 
    </div> 
 
    <div><img src="pic"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<script type="text/javascript" src="js/source.js"></script> 
 
</body> 
 
</html>

+0

'var venue_id'只在回調中定義,所以它不能在外面訪問。但即使你解決了這個問題,它仍然無法工作,因爲Ajax請求是異步的。 –

+0

[爲什麼我的變量在函數內部修改後沒有改變? - 異步代碼引用](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –

+0

可能的重複[如何在.then()鏈中訪問先前的承諾結果?](https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-鏈) –

votes
answers
20 views
+50

按日期分類器對郵件進行排序

2

我正在構建基於jquery和firestore的聊天工具,並且設法按日期排序檢索onSnapshot上的郵件,但現在我試圖按日添加日期分隔符,因此當用戶打開聊天工具時他會爲每一天和每個分頻器發現一個分頻器,在這一天發生這些信息。按日期分類器對郵件進行排序

這是我的代碼:

firestore.collection("chat").orderBy("date","desc").limit(10).onSnapshot(function(snapshot) {  

      $(".messages").html(''); 

      var curUser = ''; 
      var curDate = ''; 
      var curDay = ''; 
      snapshot.forEach(function(doc) { 
       console.log("djsidjsdoisjdis"); 
       $(".chat-content").animate({ scrollTop: $('.chat-content').prop("scrollHeight")}, 100); 

       if(curDate!== doc.data().date.toLocaleDateString()){ 
        curDate=doc.data().date.toLocaleDateString(); 
        $(".messages").append('<h1>'+doc.data().date.toLocaleDateString()+'</h1>'); 
        } 

       if(doc.data().user_name != username){ 
        // My message 

        if(doc.data().user_name !== curUser) { 
         // SHOW USER NAME 
         curUser = doc.data().user_name; 
         $(".messages").append('<ul class="message message-received message-appear-from-bottom message-appeared message-first message-last message-with-tail"><li class="message-name">'+doc.data().user_name+'</li><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-text">'+doc.data().message+'</li></ul>'); 
        } else { 
         // SHOW MESSAGE WITHOUT USERNAME 
         $(".messages").append('<ul class="message message-received message-appear-from-bottom message-appeared message-first message-last message-with-tail"><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-text">'+doc.data().message+'</li></ul>'); 
        } 
       } else { 
        // other users messages 
        if(doc.data().user_name !== curUser) { 
         // Show messsgae with user name: 
         curUser = doc.data().user_name; 
         $(".messages").append('<ul class="message message-sent message-first message-last message-with-tail message-appear-from-bottom message-appeared"><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-name">'+doc.data().user_name+'</li><li class="message-text">'+doc.data().message+'</li></ul>'); 
        } else { 
         // Show message without user name: 
         $(".messages").append('<ul class="message message-sent message-first message-last message-with-tail message-appear-from-bottom message-appeared"><li id="message-date" class="hide">'+doc.data().date+'</li><li class="message-text">'+doc.data().message+'</li></ul>'); 

        } 
       } 


      }); 
      var list = $('.messages'); 
       var listItems = list.children('ul.message'); 
       list.append(listItems.get().reverse()); 

     }); 

下面是截圖,從我得到什麼,我每個人不分離該消息後得到的日期分隔。 chat

+0

你可以分享你的JSON的摘錄..在你的情況'快照' –

+0

@KresimirPendic我沒有包括在這個函數中,用戶名被定義爲靜態變量。因爲我只是想根據分隔日期 –

votes
answers
33 views
+50

Visual Studio 2017和WinJS - 「Windows」命名空間的自動完成

0

我正在用VS/2017中的html/javascript編寫UWP windows 10應用程序。當我在VS 2015中編寫Windows8應用程序時,「Windows」命名空間會自動完成對我來說,intellisense和所有這些,但現在不是。Visual Studio 2017和WinJS - 「Windows」命名空間的自動完成

例如,如果我有var vault = new Windows.Security.Credentials.PasswordVault();,我沒有得到任何與vault. autocomlete選項,但我會在VS2015。

怎麼回事?我怎樣才能添加任何必要的文件到我的項目,讓智能感知爲此工作?

+0

最好是直接發佈答案,而不是編輯你的問題。 –

+0

肯定沒問題 – TKoL

votes
answers
40 views
+50

的onclick()獲取地理位置是不行的

-1

請告訴我問題:的onclick()獲取地理位置是不行的

如果 (我環繞navigator.geolocation.getCurrentPosition(initMap, onError);蒙山function triger()然後調用它像: <button id="btn" class="btn btn-default" onclick="triger()">

然後

它什麼都不做!

其他

它的好!

這裏是我的代碼:

<script> 

    var map; 
    var infowindow; 
    var selecteditem="hospital"; 
    var radiusin=5000; 

    function triger() { 
     navigator.geolocation.getCurrentPosition(initMap, onError); 

} 

    function onError(error){ 
    alert("the code is " + error.code + ". 
" + "message: " + error.message); 
} 

    function initMap(position) { 

    selecteditem= $("#selector").val(); 
    radiusin= $("#radius").val();  
    alert(selecteditem+"in"+radiusin); 
    var longitude = position.coords.longitude; 
    var latitude = position.coords.latitude; 
    var latLong = new google.maps.LatLng(latitude, longitude); 
    var pyrmont = latLong;// {lat: -33.867, lng: 151.195}; 
    map = new google.maps.Map(document.getElementById('map'), { 
     center: pyrmont, 
     zoom: 14 
    }); 
    infowindow = new google.maps.InfoWindow(); 
    var service = new google.maps.places.PlacesService(map); 
    service.nearbySearch({ 
     location: pyrmont, 
     radius: radiusin, 
     type: selecteditem 
    }, callback); 
    } 
    function callback(results, status) { 
    if (status === google.maps.places.PlacesServiceStatus.OK) { 
     for (var i = 0; i < results.length; i++) { 
     createMarker(results[i]); 
     } 
    } 
    } 
    function createMarker(place) { 
    var placeLoc = place.geometry.location; 
    var marker = new google.maps.Marker({ 
     map: map, 
     position: place.geometry.location 
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent(place.name); 
     infowindow.open(map, this); 
    }); 
    } 
</script> 

和:

<div class="input-group-btn"> 
    <button id="btn" class="btn btn-default" onclick="triger()"> 
    <i class="glyphicon glyphicon-search"></i> 
    </button> 
</div> 
+1

爲什麼類型=提交?使用類型=按鈕 – mplungjan

+0

@mplungjan對不起,這是一個錯誤,順便說它不工作... –

+1

控制檯錯誤? – mplungjan

votes
answers
35 views
+50

我怎樣才能在沒有警告的情況下設置一個很長的長號碼?

-1

現在,我有我怎樣才能在沒有警告的情況下設置一個很長的長號碼?

long long x = 1 << 60; 
cout << x << endl; 

,我知道,很長很長的範圍可以是一路攀升至2^64,但由於某些原因,當我執行一段代碼,它給了我一個警告,說「left shift count >= width of type [-Wshift-count-overflow].

另外,0被打印到屏幕上,這顯然不是我想要的。

我試圖把文字「LL」之後,但我不知道我應該把它:

long long x = (1 << 60)ll; 
long long x = (1 << 60ll); 

和他們沒有工作

任何人都可以請告訴我如何解決這個問題?提前致謝!

+1

使用正確的文本類型:http://en.cppreference.com/w/cpp/language/integer_literal –

+0

@NeilButterworth我試過了,但我應該把它放在60之後? 1之後?括號之後? –

+0

因爲你似乎在隨意地嘗試一些事情,所以請注意,在(1 << 60)'中有** 3個**位置可以添加'll';你只試過其中兩個。 –

votes
answers
29 views
+50

清空包含char的結構數組*

-1

我有一個包含一組char *屬性的結構。清空包含char的結構數組*

struct gcp_values { 
char* srcX; 
char* srcY; 
char* dstX; 
char* dstY; 
}; 

好,我填補它在一個循環從集合Q對象

std::vector<GeoRefLibrary::gcp_values> gcpvalues(vl.size()); 

    for(int i=0;i<vl.size();i++) { 
     gcppoint_ *a = qobject_cast<gcppoint_ *>(vl.at(i).value<QObject *>()); 
     gcpvalues[i].srcX= strdup(QString::number(a->row()).toStdString().c_str()); 
     gcpvalues[i].srcY= strdup(QString::number(a->column()).toStdString().c_str()); 
     gcpvalues[i].dstX= strdup(QString::number(a->lon()).toStdString().c_str()); 
     gcpvalues[i].dstY= strdup(QString::number(a->lat()).toStdString().c_str()); 
    } 
當我運行Valgrind的測試結果,這些OUTPT

12 bytes in 4 blocks are definitely lost in loss record 813 of 19,623 
14 bytes in 4 blocks are definitely lost in loss record 889 of 19,623 
16 bytes in 1 blocks are definitely lost in loss record 3,621 of 19,623 
32 bytes in 4 blocks are definitely lost in loss record 8,851 of 19,623 
36 bytes in 4 blocks are definitely lost in loss record 9,134 of 19,623 

這些錯誤是在這些線路

的循環。我試圖delete [] gcpvalues,但它返回錯誤的刪除/免費錯誤。我搜索,發現這個職位太

delete[] an array of objects

,但不能找到解決方案,可有一個人請幫我解決這個問題?

我也試過

struct gcp_values { 
    QString srcX; 
    QString srcY; 
    QString dstX; 
    QString dstY; 
}; 

和返回同樣的錯誤


我改變了循環到這一點,似乎錯誤都沒有了

for(int i=0;i<vl.size();i++) { 
    gcppoint_ *a = qobject_cast<gcppoint_ *>(vl.at(i).value<QObject *>()); 

     char* srcX = strdup(QString::number(a->row()).toStdString().c_str()); 
     char* srcY = strdup(QString::number(a->column()).toStdString().c_str()); 
     char* dstX = strdup(QString::number(a->lon()).toStdString().c_str()); 
     char* dstY = strdup(QString::number(a->lat()).toStdString().c_str()); 
     gcpvalues[i].srcX=srcX; 
     gcpvalues[i].srcY= srcY; 
     gcpvalues[i].dstX= dstX; 
     gcpvalues[i].dstY= dstY; 
    if(srcX) { free(srcX);} 
    if(srcY) { free(srcY);} 
    if(dstX) { free(dstX);} 
    if(dstY) { free(dstY);} 
} 
+1

'strdup'文件特別指出:*必須將返回的指針傳遞給空閒以避免內存泄漏。* –

+2

只需將'QString's放入'struct'中即可避免此問題。手動內存管理是困難和不必要的。不要這樣做。 – nwp

+0

@nwp然後以後如何將Qstring轉換爲char *,因爲我在後面的函數中需要char *。 –

votes
answers
31 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
46 views
+50

使用Qt

2

無法生成具有可接受輸出質量的PDF我試圖在Windows下使用Qt5生成pdf。我的文檔包含文本,圖像和圖表。由於我熟悉Qt和Qwt,我相信最好的策略是創建一個帶有我的文檔佈局的QWidget,並將其打印出來。但是我面臨的問題並不能以可接受的結果結束。使用Qt

這是我的MCVE,用一個簡單的頁的文件:

  • 基於Qt document並用標題和圖像
  • 一塊文本
  • 的簡單圖表

的報頭How can I print a QWidget in Qt?,我結束了這段代碼:

main.cpp中:

#include <QApplication> 
#include <QIcon> 
#include <QDesktopServices> 
#include <QWidget> 
#include <QPrinter> 
#include <QPainter> 
#include <QPagedPaintDevice> 
#include <QUrl> 
#include "ui_report.h" 

#include "qwt_plot.h" 
#include "qwt_plot_curve.h" 
#include "qwt_plot_canvas.h" 
#include "qwt_point_data.h" 
#include "qwt_legend.h" 

#include <sstream> 
#include <memory> 

bool printWidget(QWidget& widget, bool highResolution, const std::string& fileName) 
{ 
    QPrinter printer(highResolution ? QPrinter::HighResolution : QPrinter::ScreenResolution); 

    printer.setOutputFormat(QPrinter::PdfFormat); 
    printer.setOrientation(QPrinter::Portrait); 
    printer.setPaperSize(QPrinter::A4); 
    printer.setPageMargins(15,15,15,15,QPrinter::Millimeter); 
    printer.setFullPage(true); 
    printer.setOutputFileName(fromSDEString(fileName.c_str())); 

    QPainter painter(&printer); 

    double xscale = printer.pageRect().width()/double(widget.width()); 
    double yscale = printer.pageRect().height()/double(widget.height()); 
    double scale = qMin(xscale, yscale); 
    painter.translate(printer.paperRect().x() + printer.pageRect().width()/2, 
         printer.paperRect().y() + printer.pageRect().height()/2); 
    painter.scale(scale, scale); 
    painter.translate(-widget.width()/2, -widget.height()/2); 

    widget.render(&painter, QPoint(), QRegion(), QWidget::DrawChildren); 

    return painter.end(); 
} 

bool generateReport(bool drawWithPrinterResolution, bool printHighResolution, const std::string& fileName) 
{ 
    QWidget widget; 
    Ui::Report ui; 
    ui.setupUi(&widget); 

    if (drawWithPrinterResolution) 
    { 
     QPrinter printer(printHighResolution ? QPrinter::HighResolution : QPrinter::ScreenResolution); 

     printer.setOrientation(QPrinter::Portrait); 
     printer.setPaperSize(QPrinter::A4); 
     printer.setPageMargins(15,15,15,15,QPrinter::Millimeter); 
     printer.setFullPage(true); 

     // force printer page size to be used: 
     QSize pageSize = printer.pageRect().size(); 
     widget.resize(pageSize); 
    } 

    ui.header->setFrameShape(QFrame::Shape::Box); 

    QHBoxLayout* headerLayout = new QHBoxLayout(ui.header); 

    QLabel* icon = new QLabel(ui.header); 
    QSize size = ui.header->size(); 
    icon->setPixmap(QPixmap(":/gui_test/mainframe.png").scaledToHeight(size.height())); 

    headerLayout->addWidget(icon); 
    headerLayout->addWidget(new QLabel("Document title",ui.header)); 

    headerLayout->setStretch(0, 0); 
    headerLayout->setStretch(1, 1); 

    ui.inputs->setText("<b>Info</b>: Information"); 

    QwtPlot* plot = new QwtPlot(&widget); 

    QwtPlotCurve* curve = new QwtPlotCurve("Plots"); 
    curve->setStyle(QwtPlotCurve::Lines); 

    QVector<QPointF> samples; 
    for (size_t i = 0; i != 100; ++i) 
    { 
     samples.push_back(QPointF(i,20*i+10)); 
    } 
    curve->setData(new QwtPointSeriesData(samples)); 

    curve->attach(plot); 
    plot->setTitle("Result"); 
    plot->setAxisScale(QwtPlot::xBottom, samples.front().rx(), samples.back().rx()); 

    plot->replot(); 

    ui.graphLayout->addWidget(plot); 

    if (printWidget(widget, printHighResolution, fileName)) 
    { 
     QDesktopServices::openUrl(QUrl::fromLocalFile(fileName.c_str())); 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    QApplication app(argc, argv); 
    app.setWindowIcon(QIcon(":/gui_test/mainframe.png")); 

    generateReport(false, false, "report_small_widget_to_screen.pdf"); 
    generateReport(false, true, "report_small_widget_to_high.pdf"); 
    generateReport(true, false, "report_big_widget_to_screen.pdf"); 
    generateReport(true, true, "report_big_widget_to_high.pdf"); 

    return 0; 
} 

report.ui:

<?xml version="1.0" encoding="UTF-8"?> 
<ui version="4.0"> 
<class>Report</class> 
<widget class="QWidget" name="Report"> 
    <property name="geometry"> 
    <rect> 
    <x>0</x> 
    <y>0</y> 
    <width>525</width> 
    <height>742</height> 
    </rect> 
    </property> 
    <property name="windowTitle"> 
    <string>Form</string> 
    </property> 
    <layout class="QVBoxLayout" name="verticalLayout" stretch="0,0,0,100,0"> 
    <item> 
    <widget class="QFrame" name="header"/> 
    </item> 
    <item> 
    <widget class="QLabel" name="inputs"> 
    <property name="text"> 
     <string>TextLabel</string> 
    </property> 
    </widget> 
    </item> 
    <item> 
    <spacer name="verticalSpacer"> 
    <property name="orientation"> 
     <enum>Qt::Vertical</enum> 
    </property> 
    <property name="sizeHint" stdset="0"> 
     <size> 
     <width>20</width> 
     <height>40</height> 
     </size> 
    </property> 
    </spacer> 
    </item> 
    <item> 
    <layout class="QVBoxLayout" name="graphLayout"/> 
    </item> 
    <item> 
    <widget class="QWidget" name="footer" native="true"/> 
    </item> 
    </layout> 
</widget> 
<resources/> 
<connections/> 
</ui> 

mainframe.png:的256×256像素A Qt的圖標:http://icons.iconarchive.com/icons/alecive/flatwoken/256/Apps-Qt-icon.png

正如你可以看到,這會產生4個文件:

  • report_small_widget_to_screen.pdf:其中插件與來自UI文件(252x742)小A4比創建,然後印有QPrinter::ScreenResolution
  • report_small_widget_to_high.pdf :在哪裏插件與來自UI文件(252x742)小A4比創建,然後印有QPrinter::HighResolution
  • report_big_widget_to_screen.pdf:其中插件被縮放到打印機的頁大小(793x1123),然後印有QPrinter::ScreenResolution
  • report_big_widget_to_high.pdf:當小部件擴展到打印機的頁面大小(9917x14033),然後印有QPrinter::HighResolution

沒有給我一個可以接受的結果:

  • report_small_widget_to_screen.pdf:文本,Qt的圖標QWT圖是像素化
  • report_small_widget_to_high.pdf:文字是確定的,但Qt的圖標和QWT圖是像素化
  • report_big_widget_to_screen.pdf:文本,Qt的圖標和QWT圖是像素化
  • report_big_widget_to_high.pdf:文本,Qt圖標和Qwt圖表非常小,幾乎不可讀。但現在Qwt的情節不再像素化了

我應該改變什麼來獲得一個不錯的輸出?

  • 使用高分辨率(非像素化)繪製的文本與report_small_widget_to_high中一樣。PDF
  • 隨着圖標具有高分辨率(未像素化)正在制定
  • 隨着圖被描繪具有高分辨率(未像素化)

report_small_widget_to_screen.pdf樣子(一切都是像素化) :

enter image description here

report_small_widget_to_high.pdf外觀像(只有文字沒有像素化):

enter image description here

report_big_widget_to_high.pdf樣子(一切都太小):

enter image description here


注:我只是跑相同的測試與更大的.ui資源(2100x2970),然後圖像分辨率看起來更好,但文字顯示非常小。我想知道QWidget打印在這裏是合適的解決方案,因爲它看起來像文本大小取決於用戶界面大小,所以你無法控制文本的大小(就像你在像Word這樣的文檔中使用字體大小......) )

+0

什麼分辨率是您圖標? – eyllanesc

+0

@eyllanesc:256x256像素 – jpo38

+0

您可以通過github或類似的工具共享您的項目,以節省時間。 – eyllanesc

votes
answers
31 views
+50

C++ boost線程ID和Singleton

4

對不起本週洪水這麼多問題。C++ boost線程ID和Singleton

我假設thread.get_id返回的線程索引是特定於實現的。 在pthreads的情況下,索引是否重用? IE,如果線程0運行並且加入,線程啓動後綴會有不同的ID?

我問這個問題的原因是需要實現一個帶有扭曲的Singleton模式:每個線程都有自己的實例。我知道這聽起來很瘋狂,但是線程控制硬件(cuda),即使在線程級別,它也不允許設備內存共享。
什麼是實現這種模式的好方法?

+2

你不能使用TLS的單身數據? – 2010-04-18 20:11:23

+0

@neil我不知道TLS是什麼。編輯:從來沒有,線程本地存儲 – Anycorn 2010-04-18 20:12:25

+0

TLS ==線程本地存儲 - 屬於特定線程的內存 – 2010-04-18 20:14:55

votes
answers
32 views
+50

如何讓一個線程等待另一個線程的一部分完成?

-1

在一個名爲Record的函數中,我創建了一個線程。讓線程函數被稱爲ThreadFn。 我希望Record等待,直到從ThreadFn開始的ThreadFn中的一段代碼完成。 我該怎麼做?我一直在與互斥體一起嘗試。但我不確定將CreateMutex放到哪裏以及放置ReleaseMutex的位置。如何讓一個線程等待另一個線程的一部分完成?

我嘗試以下。但它不起作用。 有一個全局變量

HANDLE ghMutex = NULL; 

內ThreadFn: 起初

ghMutex = CreateMutex(NULL, FALSE, NULL); 

當代碼塊已經完成,然後

ReleaseMutex(ghMutex); 

內錄:

Create the thread 
WaitForSingleObject(ghMutex, INFINITE); 
Close thread handle 
CloseHandle(ghMutex); 
+0

不工作。來電者不在等待。 – Avinash

+2

爲什麼開發者不斷嘗試誤用互斥?如果要發信號通知其他線程,請使用適當的同步對象。查看'Event'和/或'Semaphore'。要麼會做你看起來想要的。一個互斥對象就是這個錯誤的對象。 – ThingyWotsit

+1

@ThingyWotsit爲什麼你必須居高臨下?出於某種原因,他顯然在這裏張貼這個問題。要麼他只限於使用互斥體,或者他不瞭解'事件'和/或'信號量'。 –

votes
answers
37 views
+50

Firebase宣傳橫幅廣告顯示在左上角。我怎樣才能在屏幕的底部中心顯示它?

1

我想使用Firebase在屏幕底部顯示AdMob的橫幅廣告。 目前,橫幅廣告將顯示在屏幕左上方。 我發現以下可能與框架相關的類和值,但我不知道如何使用它。即使我看着Documentsample我也無法使用。Firebase宣傳橫幅廣告顯示在左上角。我怎樣才能在屏幕的底部中心顯示它?

火力:: AdMob廣告:: BannerView ::位置 火力:: AdMob廣告:: BannerView :: kPositionBottom

請告訴我如何在屏幕底部顯示橫幅廣告。

開發環境Xcode的 9.1 的cocos2d-x 3.16 火力CPP SDK 4.2.0

[bool HelloWorld::init(){ 
if (!Layer::init()) 
    { 
     return false; 
    } 

// Intitialize Firebase AdMob. 
    firebase::admob::Initialize(*firebase::App::GetInstance(), kAdMobAppID); 

firebase::admob::BannerView* banner_view = new firebase::admob::BannerView(); 
firebase::admob::AdSize ad_size; 
    ad_size.ad_size_type = firebase::admob::kAdSizeStandard; 
    ad_size.width = 320; 
    ad_size.height = 50; 
banner_view->Initialize(getAdParent(), kAdViewAdUnit, ad_size); 
this->scheduleUpdate(); 

return true; 
} 


void HelloWorld::update(float delta) 
{ 
    // Check that the banner has been initialized. 
    if (banner_view->InitializeLastResult().status() ==firebase::kFutureStatusComplete) 
    { 
     // Check that the banner hasn't started loading. 
     if (banner_view->LoadAdLastResult().status() == firebase::kFutureStatusInvalid) 
     { 
      // Make the banner visible and load an ad. 
      CCLOG("Loading a banner."); 
      banner_view->Show(); 
      firebase::admob::AdRequest my_ad_request = {}; 
      banner_view->LoadAd(my_ad_request); 
     } 
    } 
}] 

Screenshot

votes
answers
42 views
+50

使用C++中的運算符重載的複數的增加

1

無法理解下面給定程序中的一段代碼。 特別是變量,具有返回類型作爲複雜(類名稱),當我們返回變量,臨時返回到哪裏的溫度? 這就是程序中的return(temp);使用C++中的運算符重載的複數的增加

方案

#include <iostream> 
using namespace std; 
class complex 
{ 
public: 
    complex();//default constructors 
    complex(float real, float imag)//constructor for setting values 
    { 
     x = real; 
     y = imag; 
    } 
    complex operator +(complex); 
    void display(void); 
    ~complex(); 

private: 
    float x; 
    float y; 

}; 

complex::complex() 
{ 
} 
//////////////////////////////////////////////////////////////////////////////////// 
//////////////////////////////////////////////////////////////////////////////////// 
complex complex::operator+(complex c) 
{ 
    complex temp; 
    temp.x = x + c.x; 
    temp.y = y + c.y; 
    return(temp); 
} 
///////////////////////////////////////////////////////////////////////////////////// 
///////////////////////////////////////////////////////////////////////////////////// 
void complex::display(void) { 
    cout << x << "+j" << y << "/n"; 

} 

complex::~complex() 
{ 
} 


int main() 
{ 
    complex C1, C2, C3,C4; 
    C1 = complex(1, 3.5);//setting of first number 
    C2 = complex(2,2.7);//setting of second number 
    C4 = complex(2, 5); 

    C3 = C1 + C2+C4;//operator overloading 
    cout << "C1 = "; 
    C1.display(); 
    cout << "
 C2 = "; 
    C2.display(); 
    cout << "
 C4 = "; 
    C4.display(); 
    cout << "
 C3 = "; 
    C3.display(); 

    system("pause"); 

    return 0; 


} 
+0

無關您的問題

C5=C1.operator+(C2) 

,但與[普遍不好'使用命名空間std; '](HTT ps://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)那麼你應該考慮*不*命名您的類相同[標準的'std :: complex 'class template](http://en.cppreference.com/w/cpp/numeric/complex)。 –

+0

至於你的問題,如果我們看看'+'操作符的用法,可以說我們有(更簡單的)'C3 = C1 + C2',那麼就和'C3 = C1.operator +(C2) '。這對你有幫助嗎? –

votes
answers
26 views
+50

What is the difference between g++ and gcc?

What is the difference between g++ and gcc? Which ones should be used for general c++ development?

votes
answers
36 views
+50

JMeter JavaSampler:如何從外部瓶子調用方法?

0

只給你什麼,我想實現一個情境:JMeter JavaSampler:如何從外部瓶子調用方法?

我的功能測試團隊有一個Java庫,包括HTTP調用,根據出REST架構的。我基本上想要以更高的併發性重新使用jar和調用方法。我只是想知道如何使用JMeter的JavaSampler來實現這一點?

例如:假設我想進行100次用戶登錄和註銷測試,並且我的jar爲我提供了登錄和註銷功能,那麼我的測試將如何?任何指針都會對我開始很有幫助。

votes
answers
24 views
+50

如何安裝一個新的調試 - apk,而無需手動卸載舊版調試-MAP與不匹配的簽名?

0

我有一個用戶無法退出的應用程序的硬件產品。當有新的更新時,用戶可以更新到應用程序中的最新版本。我們發佈debug-apk,而不是簽名的。如何安裝一個新的調試 - apk,而無需手動卸載舊版調試-MAP與不匹配的簽名?

我讀到Android Studio自動簽署了debug-apk。我有一個我想要發佈的應用程序的新版本,但舊的apk的簽名與新的apk簽名不匹配。用戶無法卸載應用程序並重新安裝新應用程序,因爲他們無法離開應用程序。我無法在世界各地手動更新Everyones產品。

問題:如果用戶不需要手動卸載並安裝新的apk,最好的方法是卸載舊的apk並安裝新的apk。

建議:有沒有辦法找出舊apk的自動生成的簽名,並更改新的匹配?或者有沒有辦法創建一個服務,可以卸載舊的apk並安裝新的?

+0

http://www.hugestreet.info/install-unsigned-apk-on-android-device/ –

+0

https://android.stackexchange.com/questions/132374/how-do-i-force-reinstallation- apk-with-different-signature-on-rooted-andro –

+0

如果你有root權限,請嘗試這些解決方案 –

votes
answers
11 views
+50

想在給定的時間間隔後動態地打印字母,錯誤:[$ rootScope:infdig] 10 $ digest()迭代到達。中止(...)

0
var str = "get_data_httpaja.php?un=" + $scope.uName; 
var avail=["a","v","a","i","l","a","b","l","e"]; 
var i=0; 
$http.get(str).then(function (dt) { 
    alert(dt.data); 
    //  $scope.uPlace = dt.data; 
    if(dt.data==0){ 
     var myvar=$window.setInterval(function() { 
      $scope.$watch("uAvailable",function (nv,ov) { 
       $scope.uAvailable+=avail[i]; 
      }) 
      i++;      
     },500) 
     if(i>8)$window.clearInterval(myvar); 
    } 
} 

我取出由服務器的結果,以後如果result==0然後我想打印的字母「可用」動態信,但收到錯誤:(

votes
answers
13 views
+50

Subclipse and JavaHL installation headache

I've run into problems installing the latest Subclipse plug in. I saw this post: subclipse: Unable to load default SVN Client, but the answer appears to be specific for Subclipse 1.6.x, and I think 1.8.x is presenting new issues. I'm on a mac, 10.6.8, with Eclipse Indigo. I have Subclipse 1.8.4 installed, with the Subversion JavaHL Native Library Adapter 1.7.3 installed, which is the correct version of JavaHL for Subclipse 1.8, according to http://subclipse.tigris.org/wiki/JavaHL#head-5ccce53a67ca6c3965de863ae91e2642eab537de

When I tried to add a new SVN repository, it says "operation in progress", then gives me this error:

Failed to load JavaHL Library.
These are the errors that were encountered:
no libsvnjavahl-1 in java.library.path
no svnjavahl-1 in java.library.path
no svnjavahl in java.library.path
java.library.path = .:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java

I also tried uninstalling all the subclipse plugins, and instead installing the openCollabNet subversion package, as recommended here: http://subclipse.tigris.org/wiki/JavaHL#head-5bf26515097c3231c1b04dfdb22c036bc511926b

But when I tried to add a new SVN repository, I received the error: "Unable to load defaul SVN client"

Any ideas what I'm doing wrong?

Thanks

votes
answers
40 views
+50

RejectedExecutionException來自單線程執行程序

0

下面是我的方法,我有單線程執行程序來執行run方法中的某個任務。RejectedExecutionException來自單線程執行程序

private void trigger(final Packet packet) { 

    // this line is throwing exception 
    Executors.newSingleThreadExecutor().execute(new Runnable() { 
     @Override 
     public void run() { 
     // some code here 
     } 
    }); 
    } 

下面是我得到的例外,我不知道爲什麼?解決這個問題的最好方法是什麼?

error= java.util.concurrent.RejectedExecutionException: Task [email protected] rejected from [email protected][Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] 
    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2048) 
    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:821) 
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1372) 
    at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:628) 

如果我的trigger方法被調用許多次,它仍然是在我以前的線程的run方法的工作,會發生什麼?它會啓動多個線程,還是等待一個線程完成,然後啓動另一個線程?

+0

是的,這是完整的代碼,我也提到了它拋出異常的地方。 – user1950349

+0

您使用的是哪個版本的JDK? –

+0

我正在使用JDK7。 – user1950349

votes
answers
37 views
+50

圖中的每日總金額

-1

請允許我找不到我的問題的答案。我不知道要尋找什麼。圖中的每日總金額

我用時間保持日誌。它包含我工作了多久的信息。我需要製作一張圖表,顯示我總共完成的工作量。

例如,第1天我工作1小時,第2天工作2小時。 我填寫A列中的日期和B列中的人工。在我的圖表中,我需要看到我在第1天總共工作了1小時,並且在第2天總共工作了3小時(基本上我需要總結所有內容)

我已經嘗試通過在新列中添加列的總和來解決這個問題,但這僅僅是太多的工作來做我需要的行數。 我這樣做是爲了通過行14列E中的每一個細胞,直到我決定從堆棧溢出問幫助

+1

在SO上,您應該嘗試**自己編寫代碼**。後** [做更多的研究](//meta.stackoverflow.com/questions/261592)**如果你有問題,你可以**發佈你已經嘗試**與清楚的解釋是什麼是'工作**並提供** [最小,完整和可驗證示例](// stackoverflow.com/help/mcve)**。 – Rob

+0

這個問題是[Stack Overflow的主題](https://stackoverflow.com/help/on-topic),你可能會在[SuperUser](https://superuser.com/)上找到更多幫助。 – hnefatl

+1

@hnefatl我的猜測是SU會反彈它。也許你是指Web應用程序? – pnuts

votes
answers
43 views
+50

Rails Tutorial: nokogiri-1.5.2 error on bundle install

After working through the RVM setup, rspec and guard sections of chapter 3 of the Ruby on Rails Tutorial, whenever I run bundle install I get the following error dump:

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb 
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- mkmf (LoadError)
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from extconf.rb:5:in `<main>'


Gem files will remain installed in /home/dan/.bundler/tmp/17577/gems/nokogiri-1.5.2 for inspection.
Results logged to /home/dan/.bundler/tmp/17577/gems/nokogiri-1.5.2/ext/nokogiri/gem_make.out
An error occured while installing nokogiri (1.5.2), and Bundler cannot continue.
Make sure that `gem install nokogiri -v '1.5.2'` succeeds before bundling.

In the gem_make.out:

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb 
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file --mkmf (LoadError)
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from extconf.rb:5:in `<main>'

I've been debugging for a while now and I think I'm stuck. Help would be GREATLY appreciated!

votes
answers
49 views
+50

如何以非root用戶身份運行官方Tensorflow Docker鏡像?

0

我目前正在與NVIDIA技術的碼頭工人運行官Tensorflow泊塢集裝箱(GPU):如何以非root用戶身份運行官方Tensorflow Docker鏡像?

不過,我不能找到一種方法來設置默認爲用戶集裝箱。此容器的默認用戶是「root」,這在安全性方面很危險,並且存在問題,因爲它允許根訪問共享文件夾

假設我的主機與用戶「CNNareCute」一起運行,有什麼方法可以用同一個用戶啓動我的容器嗎?

votes
answers
31 views
+50

Bootstrap導航欄無法正常工作與wordpress

1

我正在使用Bootstrap的WordPress自定義主題4.我檢查了所有的連接,即引導CSS和js連接。另一個引導代碼,如果我將它添加到主題工作正常。Bootstrap導航欄無法正常工作與wordpress

問題出在導航enter image description here。導航無法正確顯示。 如果你看看上面的圖像,它顯示的導航不是正確的設計。

我使用的是給出

<header class="site-header" role="banner"> 
     <div class="navbar-wrapper"> 
      <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> 
       <div class="container"> 
        <div class="navbar-header"> 
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> 
          <span class="sr-only">Toggle navigation</span> 
          <span class="icon-bar"></span> 
          <span class="icon-bar"></span> 
          <span class="icon-bar"></span> 
         </button> 
         <?php if (get_theme_mod('theme_wordpress_logo')): ?> 
         <a href="<?php echo esc_url(home_url('/')); ?>"> 
          <img src="<?php echo esc_attr(get_theme_mod('theme_wordpress_logo')); ?>" alt="<?php echo esc_attr(get_bloginfo('name')); ?>"> 
         </a> 
        <?php else : ?> 
         <a class="site-title" href="<?php echo esc_url(home_url('/')); ?>"><?php esc_url(bloginfo('name')); ?></a> 
        <?php endif; ?> 
        </div> <!-- navbar-header --> 

        <div class="navbar-collapse collapse"> 
        <?php 
         wp_nav_menu(array(
          'theme_location' => 'primary', 
          'container'  => 'nav', 
          'container_class' => 'navbar-collapse collapse', 
          'menu_class'  => 'nav navbar-nav navbar-right', 
          'fallback_cb'  => 'wp_bootstrap_navwalker::fallback', 
          'walker'   => new wp_bootstrap_navwalker() 
         )); 
        ?> 
        </div><!-- navbar-collapse --> 
       </div> 
      </div> 
     </div><!-- navbar-wrapper --> 
    </header><!-- Header --> 
+0

引導'摺疊崩潰', 'menu_class'=>'nav navbar-nav navbar-right',你必須使用bootstrap中可用的類。 – maulik

+0

嗨maulik,我使用可用的類nav navbar-nav。這不會工作? – ziaullahzia

votes
answers
27 views
+50

找不到目標「單」與Maven運行MVN包

0

我試圖編譯一些Java類與Maven生成一個可執行的JAR文件,它是獨立找不到目標「單」與Maven運行MVN包

<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/xsd/maven-4.0.0.xsd"> 
<modelVersion>4.0.0</modelVersion> 
<groupId>grids</groupId> 
<artifactId>grids</artifactId> 
<version>0.0.1-SNAPSHOT</version> 
<name>MainMap_Challange</name> 
<description>Tickets and Events System</description> 
<build> 
<sourceDirectory>src</sourceDirectory> 
<plugins> 
    <plugin> 
    <artifactId>maven-compiler-plugin</artifactId> 
    <version>3.5.1</version> 
    <configuration> 
     <descriptorRefs> 
     <descriptorRef>jar-with-dependencies</descriptorRef> 
     </descriptorRefs> 
    </configuration> 
    <executions> 
     <execution> 
     <id>make-assembly</id> <!-- this is used for inheritance merges --> 
      <phase>package</phase> <!-- bind to the packaging phase --> 
      <goals> 
      <goal>single</goal> 
      </goals> 
     </execution> 
    </executions> 
    </plugin> 
</plugins> 

我想產生一個獨立的jar文件一樣解釋在這裏 https://maven.apache.org/plugins/maven-assembly-plugin/usage.html

錯誤我得到的是:

[INFO] Scanning for projects... 
[INFO] 
[INFO] ------------------------------------------------------------------------ 
[INFO] Building MainMap_Challange 0.0.1-SNAPSHOT 
[INFO] ------------------------------------------------------------------------ 
[INFO] ------------------------------------------------------------------------ 
[INFO] BUILD FAILURE 
[INFO] ------------------------------------------------------------------------ 
[INFO] Total time: 0.335 s 
[INFO] Finished at: 2017-12-02T20:08:49Z 
[INFO] Final Memory: 5M/15M 
[INFO] ------------------------------------------------------------------------ 
[ERROR] Could not find goal 'single' in plugin org.apache.maven.plugins:maven-compiler-plugin:3.5.1 among available goals compile, help, testCompile -> [Help 1] 
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. 
[ERROR] Re-run Maven using the -X switch to enable full debug logging. 
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles: 
[ERROR] [Help 1] 
http://cwiki.apache.org/confluence/display/MAVEN/MojoNotFoundException 

在命令行上運行 「MVN包」 時

votes
answers
21 views
+50

如何禁用自動排序的DataTables?

1

我的數據表初始化腳本是如何禁用自動排序的DataTables?

$('#table').DataTable(); 

我想禁用自動排序表列的

+0

嘗試' 「bSortable」:FALSE',看這個的jsfiddle:http://jsfiddle.net/jhfrench/ptr63fxt/ –

+0

感謝您前面回答 –

+1

正確的答案是'命令:[]'...這維持訂單能力,但不設置默認訂單,即'[[0,'asc']]'對第一列進行升序排序。 – davidkonrad

votes
answers
48 views
+50

Spark Streaming Kafka初始偏移量

0

我正在使用Java Spark API,對於KafkaUtils.createDirectStream,我想跟蹤偏移量。 有一個名爲fromOffset的參數,它記錄了Kafka主題分區中的偏移量。對於第一次運行,我不知道將有多少個分區,那麼如何設置此參數? 並且我是否需要在Kafka參數中設置「auto.offset.reset」? 如果是,它會影響我的代碼從已知的偏移中恢復嗎?Spark Streaming Kafka初始偏移量

+0

如果您不知道分區數量,您如何知道每個分區的起始偏移量? – Mariusz

+0

如果我將「auto.offset.reset」設置爲最小或最大,我仍然可以從每個紅色獲得分區和偏移信息 – peng

votes
answers
48 views
+50

什麼是超級作曲作曲家的$美元符號?

-1

在查詢語言中頻繁使用_ $符號,這是什麼意思,並且每個類關鍵字都有一個美元前綴。 $和_ $符號的意義/含義是什麼?

votes
answers
29 views
+50

Running the new Intel emulator for Android

Lately Google and Intel have published a new way to run the emulator, which should work much better than the previous version (which has emulated ARM CPU). Here are some links about it: this and this.

However, after installing the new components and creating a new emulator configuration as instructed, I get an error and I also can't see any improvements. I've tried both API 10 and API 15, and with GPU enabled and disabled. None of those configurations helped. I've also tried it on two different computers and didn't get any boost (and got the same errors).

It seems that on the posts I've read about it, nobody had any problems with it and all report a much faster emulator.

The error it shows is:

emulator: Failed to open the HAX device!
HAX is not working and emulator runs in emulation mode
emulator: Open HAX device failed

Why is it happening, and is there a way to fix it? Is there anyone else who gets those errors or vice versa?

By the way, I have an Intel CPU, if that could be a problem.


EDIT:

here's what I see in the BIOS, so it should be available... :

enter image description here

votes
answers
24 views
+50

將文件連接到phpMyAdmin錯誤

1

這個問題我遇到了麻煩,現在我一直在看它幾個小時。所以基本上我的工作登記表上我的網站,而在PHP的工作,我把它連接到MySQL和數據庫與這行代碼(這是代碼6號線):將文件連接到phpMyAdmin錯誤

$mysqli = new mysqli('localhost:8080', 'root', 'mypass123', 'accounts');

我使用XAMPP在Mac上,當我嘗試註冊它只是不完全是這樣,問題是,它顯示了這個錯誤:

Warning: mysqli::__construct(): (HY000/2002): Connection refused in /opt/lampp/htdocs/form.php on line 6

如果沒有足夠的信息,我很抱歉,但我新。

+0

您在第6行發佈的代碼是?那麼,你的代碼的一部分,它給出了錯誤? – Geshode

+0

是的。由於我試圖連接它,但它沒有工作。 – skelet0n

votes
answers
48 views
+50

錯誤試圖分裂圖像顏色:numpy.ndarray」對象有沒有屬性‘面具’

1

這是我的Python代碼:錯誤試圖分裂圖像顏色:numpy.ndarray」對象有沒有屬性‘面具’

from PIL import Image 

labels = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'] 

from keras.datasets import cifar10 

(X_train, Y_train), (X_test,y_test) = cifar10.load_data() 



index = int(input('Enter an image index: ')) 
display_image = X_train[index] 
display_label = Y_train[index][0] 

from matplotlib import pyplot as plt 

red_image = Image.fromarray(display_image) 
red,green,blue = red_image.split() 

plt.imshow(red, cmap="Reds") 
plt.show() 

print(labels[display_label]) 

那是錯誤返回

File "/Users/mcarvalho/PycharmProjects/SimpleImageRecognition/venv/lib/python3.6/site-packages/matplotlib/image.py", line 419, in _make_image if A.mask.shape == A.shape: AttributeError: 'numpy.ndarray' object has no attribute 'mask'

+0

更新numpy和matplot lib到最新版本後,我有同樣的問題。不過,不知道那裏會發生什麼...... – Dmytro

votes
answers
27 views
+50

在線程中啓動作業從其他線程的隊列中讀取

1

我遇到了一個我無法弄清楚的問題。這可能不容易解釋。在線程中啓動作業從其他線程的隊列中讀取

我有這個私有構造一個單例類:

private BarcodeMonitor() 
{ 
    processors[Machines.H1] = new BarcodeProcessor { Queue = new BlockingQueue<BarcodeData>("H1") }; 
    processors[Machines.H2] = new BarcodeProcessor { Queue = new BlockingQueue<BarcodeData>("H2") }; 
    processors[Machines.M] = new BarcodeProcessor { Queue = new BlockingQueue<BarcodeData>("M") }; 
    processors[Machines.HP] = new BarcodeProcessor { Queue = new BlockingQueue<BarcodeData>("HP") }; 

    foreach (KeyValuePair<Machines, BarcodeProcessor> pair in processors) 
    { 
     Thread t = new Thread(t1 => pair.Value.StartProccesingQueue()); 
     t.Name = pair.Key.ToString() + "Processor"; 
     t.Start(); 
     threads.Add(t); 
    } 
} 

一個新的和獨特的BlockingQueue是考慮到BarcodeProcessor,並採取了名字。

BarcodeMonitor具有此方法:

public BlockingQueue<BarcodeData> GetQueue(Machines machine) 
{ 
    var processor = processors[machine]; 
    return processor.Queue; 
} 

使得傳入的條形碼被放在正確的機器的隊列中。這工作正常。

條形碼在StartProccesingQueue()(其中4個實例正在運行)中出列。在出隊方法,我有:

System.Console.WriteLine(string.Format("Thread {0} is taking from queue {1}", Thread.CurrentThread.Name, name)); 

Dequeue()使用Monitor.Wait(_internalQueue)當隊列是空的。 Enqueue()使用Monitor.PulseAll(_internalQueue)繼續等待出隊。

發生什麼情況是StartProccesingQueue()方法從其他隊列中獲取,即使它只是訪問Queue屬性,該屬性被分配了新的BlockingQueue。事實上,到目前爲止,我只看到隊列「M」中的項目被採用,並且只有H1和H2線程正在執行它。

我真的不明白爲什麼會發生這種情況。

+1

您正在訪問閉包中的foreach-iterator變量。這很危險,行爲依賴於編譯器。這可能是原因。只需做一個'var value = pair.Value;'並在lambda中使用,看看是否有幫助。 – Dirk 2015-02-06 12:27:53

+0

@Dirk哇,這樣做。所有這一切都花了我的時間找到答案......作爲接受答案:) – Halfgaar 2015-02-06 12:38:43

+0

它已經被回答了幾次,這只是一個不同的背景。我會發佈一個副本。 – Dirk 2015-02-06 12:39:26

votes
answers
36 views
+50

我的JSONObject發送空值到服務器

0

我想發送文本值到服務器,這是名稱,電話,位置,備註,但每次每個值都丟失 第一次名稱不會,下次撥打電話和下一個位置。 ..我的JSONObject發送空值到服務器

更新:

Jsoncode:

public static String POST(String url, Persoenter code heren person){ 
    InputStream inputStream = null; 
    String result = ""; 
    try { 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     String json = ""; 
     JSONObject jsonObject = new JSONObject(); 
     jsonObject.accumulate("name",person.getName()); 
     jsonObject.accumulate("phone", person.getPhone()); 
     jsonObject.accumulate("remarrks",person.getRemarks()); 
     jsonObject.accumulate("credated_dt", person.getCreatedat()); 

     jsonObject.accumulate("emp_code", person.getCreatedby()); 

     jsonObject.accumulate("location", person.getLocation()); 
     jsonObject.accumulate("add_fld1", "Test"); 
     jsonObject.accumulate("add_fld2", "Test"); 
     jsonObject.accumulate("add_fld3", "Test"); 




     json = jsonObject.toString(); 
     StringEntity se = new StringEntity(json); 
     Log.e("sent",""+json); 
     httpPost.setEntity(se); 
     httpPost.setHeader("Accept", "application/json"); 
     httpPost.setHeader("Content-type", "application/json"); 

     HttpResponse httpResponse = httpclient.execute(httpPost); 

     inputStream = httpResponse.getEntity().getContent(); 
     if(inputStream != null) 
      result = convertInputStreamToString(inputStream); 
     else 
      result = "Did not work!"; 
    } catch (Exception e) { 
     Log.d("InputStream", e.getLocalizedMessage()); 
    } 
    return result; 
} 

Httppost

private class sync extends AsyncTask<String, String, String> { 


    InputStream inputStream = null; 
    OutputStream outputStream = null; 

    protected String doInBackground(String... urls) { 

     person = new Person(); 

     person.setName(eName.getText().toString()); 
     person.setPhone(ePhonenumber.getText().toString()); 
     person.setLocation(eLocation.getText().toString()); 
     person.setRemarks(eRemarks.getText().toString()); 
     person.setCreatedby(eCreatedby.getText().toString()); 
     person.setCreatedat(eCreatedat.getText().toString()); 
     return POST(urls[0],person); 
    } 
@Override 
    protected void onPreExecute() { 
     progress.setTitle("Connecting to server"); 
     progress.setMessage("Sending Data.... Please wait!"); 
     progress.setCanceledOnTouchOutside(false); 
     progress.show(); 
    } 

    @Override 
    protected void onPostExecute(String s) { 
       progress.dismiss(); 
       Intent Homeintent = getIntent(); 
Homeintent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
finish(); 
startActivity(Homeintent); 

    } 

輸出 1:{ 「名稱」: 「beta33」, 「電話」: 「33」, 「remarrks」: 「33」, 「credated_dt」:「2017年12月20日11 :56:32「,」emp_code「:」[email protected]「,」location「:」33「} 2:{」name「:」beta33「,」phone「:」33「,」remarrks「: 「33」,「credated_dt」:「2017-12-20 11:56:43」,「emp_code」:「[email protected]」,「location」:「33」} 3:{「name」:「 「,」電話「:」34「,」remarrks「:」34「,」credated_dt「:」2017-12-20 11:56:52「,」emp_code「:」[email protected]「,」位置「 :「34」}

在嘗試了一兩次嘗試之後,名字不會出現,我不知道爲什麼......請別人幫我解決這個問題

+2

我建議你使用一個網絡庫,如排球或改造來處理這些類型的操作。這種程序已過時,並且隨着項目擴展而變得難以維護。 – KBJ

+0

是的,我想使用凌空..但截至目前這是必需的 – Flash

+0

在調試模式下檢查'JSONObject joj = getonline();'的值。你是否獲得預期的價值。 –

votes
answers
29 views
+50

使用Redux作爲初始組件狀態

0

我使用Redux作爲用於編輯當前選定項目(包含這些屬性:「name」和「selected」)的名稱的組件中的初始狀態。它用作本地初始狀態,因爲我只想在點擊保存按鈕(我還沒有實現)時更新Redux全局狀態。使用Redux作爲初始組件狀態

constructor(props) { 
    super(props) 
    this.state = { 
     item: this.props.item 
    } 
} 

我的渲??染功能包括編輯名稱輸入:

<TextField 
    id={"name"} 
    value={this.state.item.name} 
    onChange={e => this.updateName(e.target.value)} 
/> 

的updateName()函數是:

updateName = (value) => { 
    var newItem = this.state.item 
    newItem.name = value 
    this.setState({item: newItem}) 
} 

在這裏,我可以選擇的項目,對默認的值在所選項目的名稱後面輸入更改(當我選擇一個項目時,Redux的狀態會更新,組件的狀態和輸入中的文本也會更新)。一切都按照計劃進行。

當我寫入輸入時,寫入的文本會改變,但是選擇項目的操作不會再更新輸入的文本(它應該跟隨從Redux中選擇的項目的名稱,就像我輸入文本之前一樣)。

是否因爲使用this.setState()更新組件狀態後,對this.props.item的引用(以及後來的Redux更新)就會丟失?但是我怎樣才能糾正這個問題呢?

votes
answers
19 views
+50

JavaScript語法反應路線

0

我要在這裏做出反應路由器代碼:modal-galleryJavaScript語法反應路線

和跨越這句法

const Modal = ({ match, history }) => { 
    const image = IMAGES[parseInt(match.params.id, 10)] 
    if (!image) { 
    return null 
    } 
    const back = (e) => { 
    e.stopPropagation() 
    history.goBack() 
    } 
    return (
    <div 
     onClick={back} 
     style={{ 
     position: 'absolute', 
     top: 0, 
     left: 0, 
     bottom: 0, 
     right: 0, 
     background: 'rgba(0, 0, 0, 0.15)' 
     }} 
    > 
     <div className='modal' style={{ 
     position: 'absolute', 
     background: '#fff', 
     top: 25, 
     left: '10%', 
     right: '10%', 
     padding: 15, 
     border: '2px solid #444' 
     }}> 
     <h1>{image.title}</h1> 
     <Image color={image.color} /> 
     <button type='button' onClick={back}> 
      Close 
     </button> 
     </div> 
    </div> 
) 
} 

我的問題是,什麼樣的語法是這樣來的?並且如何將其轉換爲ES6 React.Component class

+1

這就是所謂的解構賦值。 – Li357

+0

請注意,這不是JavaScript;並且可能還需要使用[tag:jsx]添加標籤(即使您最終要詢問的現象在JavaScript和JSX中都可用)。 – Amadan

votes
answers
33 views
+50

Codename One - rim.obfuscation生成提示

1

關於混淆,「rim.obfuscation」的含義是什麼?我沒有在互聯網上找到什麼是「rimc編譯器」。Codename One - rim.obfuscation生成提示

votes
answers
30 views
+50

谷歌地圖:正確的位置創建點後更新我的地圖

-1

我嘗試繪製谷歌地圖,我有問題。當我編輯位置創建點谷歌地圖重複我的觀點,我得到兩點:新舊。谷歌地圖:正確的位置創建點後更新我的地圖

let pointCord = [];  
function createRoute(e) { 
const lat = e.latLng.lat(); 
const lng = e.latLng.lng(); 

pointCord.push(new google.maps.LatLng(lat, lng)); 

const flightPathOptions = { 
    path: pointCord, 
    editable: true, 
    draggable: true, 
    strokeColor: '#000', 
    strokeOpacity: 1.0, 
    strokeWeight: 5, 
    map 
}; 

flightPath = new google.maps.Polyline(flightPathOptions); 
const getPath = flightPath.getPath(); 

map.addListener('click', createRoute); 

我嘗試使用這個代碼

google.maps.event.addListener(getPath, 'set_at', function(){ 
    pointCord = getPath.getArray(); 
    createRoute(e); 
}); 

但不幫我。如何刪除舊點並更新我的地圖?

votes
answers
24 views
+50

How can I “pretty” format my JSON output in Ruby on Rails?

I would like my JSON output in Ruby on Rails to be "pretty" or nicely formatted.

Right now, I call to_json and my JSON is all on one line. At times this can be difficult to see if there is a problem in the JSON output stream.

Is there way to configure or a method to make my JSON "pretty" or nicely formatted in Rails?

votes
answers
21 views
+50

圖片瀏覽類改變鼠標點擊圖片

0

我想創建一個有圖片的類,並通過鼠標點擊更改爲下一個類。我是oop的新手,我的想法是使類相似到現實生活中每個新圖片都有新的類實例,是否可以這樣做?這是我的代碼圖片瀏覽類改變鼠標點擊圖片

import tkinter as tk 
from PIL import Image,ImageTk 
class Picture(): 
    _count=1 
    def __init__(self,window): 
     self.id=Picture._count 
     Picture._count+=1 
     self.img=Image.open(r'C:ImgArchiveimg%s.png' % self.id) 
     self.pimg = ImageTk.PhotoImage(self.img) 
     self.lab=tk.Label(window,image=self.pimg) 
     self.lab.pack() 
     self.lab.bind('<1>',self.click) 
    def click(self,event): 
     self.lab.destroy() 
     self=self.__init__(window) 
window = tk.Tk() 
window.title('Album') 
window.geometry('1200x900') 
pic=Picture(window) 
window.mainloop() 

它工作正常,但我不知道我的課的舊實例被刪除,他們?我用self.lab.destroy(),因爲如果我不新圖片顯示了下來,像這樣

#

,而不是這個

#

那麼爲什麼會發生?什麼是高雅它的方式?

+0

命令'自我=自我.__的init __(...)'是代碼的最不尋常的線 - 這意味着你必須更好地組織代碼並將一些代碼從'__init__'移動到分離的方法 - 然後運行這個方法insife'__init__'而不是'self = self .__ init __()' – furas

+0

更好地使用'self。 lab [「image」] = new_image'來替換現有標籤中的圖像。 – furas

+0

我試過這個'def click(self,event): self.lab.destroy() Picture._count + = 1 self.img = Image.open(r'C: ImgArchive img%s.png'%圖片._count) self.newImg = ImageTk.PhotoImage(self.img) self.lab [「image」] = self.newImg',但得到錯誤'_tkinter.TclError:invalid command name「。!label」'I「對於OOP來說,我的想法是讓類與現實生活類似,每個新圖片都有新的類實例,是否可以做某種方式? –

votes
answers
28 views
+50

只允許在Google地圖中使用一個標記

-1

我知道存在一些關於此主題的線索,但我認爲這有點不同,因爲所有線索都是關於點擊地圖上的一個標記,但這是唯一標記每一次。看看下面只允許在Google地圖中使用一個標記

... 
var x = map.setCenter(new google.maps.LatLng(lat, lng), 17); 
     marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(lat, lng), 
     center: new google.maps.LatLng(lat, lng), 
     map: map, 
     title: 'Map Tracker', 
}); 
... 

在每次30秒這段代碼,這段代碼被稱爲具有不同的[緯度]和[經度]值,但所有舊標誌仍清晰可見,我不知道如何刪除它們,我每個結果只需要一個標記。此外,我已經嘗試map.clearOverlays(),但仍然無法工作。

你能幫我嗎?

+0

答案與其他問題相同。從地圖上移除標記,然後用新標記覆蓋標記或將其移至新位置。 – geocodezip

+0

我已經試過了!仍然沒有工作,沒有錯誤:) – Clarice

+0

洪水持續:http://prntscr.com/hib0s6 – Clarice

votes
answers
37 views
+50

javascript scroll event for iPhone/iPad?

I can't seem to capture the scroll event on an iPad. None of these work, what I am doing wrong?

window.onscroll=myFunction;

document.onscroll=myFunction;

window.attachEvent("scroll",myFunction,false);

document.attachEvent("scroll",myFunction,false);

They all work even on Safari 3 on Windows. Ironically, EVERY browser on the PC supports window.onload= if you don't mind clobbering existing events. But no go on iPad.

votes
answers
36 views
+50

我的Android應用程序中的SQLite選擇與排錯

-3

我需要從SQLite數據庫中選擇數據。但是,我有一個搜索字段,用戶可以在其中輸入位置的名稱。因爲他們可能錯誤地輸入這個名字,我需要能夠根據這個從數據庫中提取相關的記錄。我的Android應用程序中的SQLite選擇與排錯

例如:

輸入:摩天Whrrl

實際:摩天輪

應該儘管錯字正確定位的摩天輪項目。我意識到editdist3沒有在Android SQLite中實現。我寧願不選擇整個數據庫到RAM中並遍歷所有字符串,並手動計算Levenshtein距離,因爲這將是超級資源密集型的。

任何幫助將不勝感激! :)

+0

嘗試使用LIKE運算符。 –

+0

LIKE運算符並不能幫助您逼近拼寫錯誤:/ – ashiswin

+1

您可以使用LIKE運算符來快速減少潛在匹配,然後使用更小的集合,這正是@BernoulliGate可能會遇到的問題。 –

votes
answers
54 views
+50

OpenSSL BN_exp()用法

0

我有一個小程序,它在64字節的大整數(通過BN_generate_prime_ex()生成)上使用BIGNUM函數BN_exp()和BN_mod_exp()。OpenSSL BN_exp()用法

每次我編譯並運行時,程序會在計算第??一次調用BN_exp()時永遠暫停。我知道問題是BN_exp(),因爲我在函數調用之前和之後都有打印語句。我對計算BN_exp()時程序停滯的原因感到困惑。 64字節的大整數對於函數來說太大了嗎?計算是否花了很長時間?任何幫助表示讚賞。

目標:計算(bn_one^bn_two)*(bn_two^bn_one)mod bn_mod。我的方式是不正確的,所以關於如何計算這個的任何建議都會很棒。

這裏是我的程序:

#include <stdio.h> 

/* OpenSSL headers */ 
#include <openssl/bn.h> 

void main() 
{ 
    BIGNUM *bn_one, *bn_two, *bn_one2two, *bn_two2one, *bn_mod, *bn_result; 
    BN_CTX *ctx; /* used internally by the bignum lib */ 

    ctx = BN_CTX_new(); 
    bn_one = BN_new(); 
    bn_two = BN_new(); 
    bn_one2two = BN_new(); 
    bn_two2one = BN_new(); 
    bn_mod = BN_new(); 
    bn_result = BN_new(); 

    // Generate two 64 byte integers 
    BN_generate_prime_ex(bn_one,512,0,NULL,NULL,NULL); 
    BN_generate_prime_ex(bn_two,512,0,NULL,NULL,NULL); 
    BN_generate_prime_ex(bn_mod,512,0,NULL,NULL,NULL); 

    printf("BIGNUM One:	"); 
    BN_print_fp(stdout, bn_one); 
    printf("
"); 

    printf("BIGNUM Two:	"); 
    BN_print_fp(stdout, bn_two); 
    printf("
"); 

    // Compute bn_one to the power of bn_two and store in bn_one2two 
    if(BN_exp(bn_one2two , bn_one , bn_two, ctx) == 0) { 
     printf("Error in BN_exp
"); 
    } 

    printf("BIGNUM One2Two:	
"); 
    BN_print_fp(stdout, bn_one2two); 
    printf("
"); 

    // Compute bn_two to the power of bn_one and store in bn_two2one 
    if(BN_exp(bn_two2one , bn_two , bn_one, ctx) == 0) { 
     printf("Error in BN_exp
"); 
    } 

    printf("BIGNUM Two2One:	
"); 
    BN_print_fp(stdout, bn_two2one); 
    printf("
"); 

    // Compute bn_one2two * bn_two2one mod bn_mod and store the remainder in 
    //bn_result 
    if(BN_mod_mul(bn_result , bn_one2two , bn_two2one, bn_mod , ctx) == 0) { 
     printf("Error in BN_mod_exp
"); 
    } 
    printf("BIGNUM Mod Result:	
"); 
    BN_print_fp(stdout, bn_result); 
    printf("
"); 

    BN_CTX_free(ctx); 
    BN_clear_free(bn_one); 
    BN_clear_free(bn_two); 
    BN_clear_free(bn_one2two); 
    BN_clear_free(bn_two2one); 
    BN_clear_free(bn_mod); 
    BN_clear_free(bn_result); 
} 

程序攤位前,我的輸出(這64個字節的值,每次運行時更改):

BIGNUM一:CE06C8663AB65AA2BF7C6B30273C5E002552CFB8548A6B8EC7204A23F6A8892FEA9EF315777660C5B4FD97EABB7703FCFB5B1C2D495A1863B5F9D290F72CF8A5

BIGNUM二:CB4A929D982670B77F2544E7D5A990DEE76958CBEC5BEB638B8DA9D44880C46817D1D7616C58AF79378215368C76962FA88D08A215331019599945CAF933E417

+0

除非我誤會,否則結果將有512 * 2^512個二進制數字。這比適合任何計算機內存。 –

+0

我的目標是計算(bn_one^bn_two)*(bn_two^bn_one)mod bn_one,所以關於如何計算這個比我當前的方法更多的建議?謝謝。 –

+0

bn_one^bn_two是bn_one的倍數,所以結果應該爲零。 –

votes
answers
41 views
+50

- 產品標誌導致沒有顯示鍵盤在Android 7的Ionic 3應用程序中

1

當我運行時:ionic cordova run android --device一切都很好,但是當我嘗試使用--prod標誌時。即使我認爲我使用<ion-input>(onFocus)屬性,輸入點擊也不會顯示鍵盤。- 產品標誌導致沒有顯示鍵盤在Android 7的Ionic 3應用程序中

這裏是我的離子信息:

cli packages: (C:UsersHoussemAppDataRoaming
pm
ode_modules) 

    @ionic/cli-utils : 1.19.0 
    ionic (Ionic CLI) : 3.19.0 

global packages: 

    cordova (Cordova CLI) : 7.1.0 

local packages: 

    @ionic/app-scripts : 3.1.4 
    Cordova Platforms : android 6.3.0 
    Ionic Framework : ionic-angular 3.9.2 

System: 

    Android SDK Tools : 26.1.1 
    Node    : v8.9.3 
    npm    : 5.5.1 
    OS    : Windows 10 

Environment Variables: 

    ANDROID_HOME : C:UsersHoussemAppDataLocalAndroidsdk 

Misc: 

    backend : pro 
votes
answers
21 views
+50

Can I safely delete contents of Xcode Derived data folder?

I am running low on disk space and checked through a third party utility that among other things that ~/Library/Developer/Xcode/DerivedData directory is taking about 22GB of disk space.

I searched stackoverflow and found this post

How can I safely delete in my ~/Library/Developer/Xcode/DerivedData directory?

The accepted answer to this question suggests that I should not touch / remove folders from this directory. so what I did was

  • Found an existing build project folder for an app that I have available on Appstore
  • Deleted the folder from derived dir
  • launched XCode 5
  • Open that project
  • Clean Build
  • Tested and compiled it on a simulator
  • ReArchived
  • Everything worked. Nothing was broken.

Unless I missed something in that posts answer I want to make sure by asking experienced developers that if I delete all the folders from DerivedData it will not hurt me in building, testing and compiling those projects.

votes
answers
60 views
+50

Syntax-highlight Python in a vim fold line

I have found that code-folding helps me organize my files better. Thus, at the bottom of my ~/.vimrc, I enable vim code folding by default:

""Folding
set foldmethod=indent
set foldnestmax=2
nnoremap <space> za
vnoremap <space> zf
"set nofoldenable       "set this to disable folding on file open

This has the advantages of using SPACE to toggle folds at the cursor, or if they start to annoy me I can use zR to unfold everything.

However, I'm also addicted to syntax highlighting. I use Dmitry Vasiliev's python.vim, but it doesn't highlight syntax in a fold line:

vim folded, no syntax highlighting

The lack of syntax highlighting for Field('id', type='integer', unique=True, notnull=True), makes it hard on my eyes when I'm used to seeing the highlight colors

What I'm looking for is a python.vim that supports syntax highlighting on a fold summary... if it Dmitry's did, it would highlight the strings in green something like this:

desired folding highlights

I want to continue using foldmethod=indent, if possible. Is there a way to get syntax highlights on fold summaries? Perhaps another python.vim?

votes
answers
22 views
+50

Javascript:我如何才能影響我試圖觸發的特定ID?

-1

例如,當我點擊一個按鈕時,它會以某種方式影響頁面上的每個按鈕。我只是想影響我點擊的那個。Javascript:我如何才能影響我試圖觸發的特定ID?

下面是腳本:

// when the user clicks on like 
    $('.icon-wrapper').on('click', function(){ 
     var postid = $(this).data('id'); 
      $post = $(this); 

     $.ajax({ 
      url: 'user_profiles.php', 
      type: 'post', 
      data: { 
       'liked': 1, 
       'postid': postid 
      }, 
      success: function(response){ 
       $post.parent().find('span.likes_count').text(response); 

       $post.addClass('hide'); 
       $post.siblings().removeClass('hide'); 
       $post.siblings().addClass('anim'); 
       $post.removeClass('anim'); 


      } 
     }); 
    }); 

HTML:

$sql = "SELECT * FROM user_images WHERE username = '$username' ORDER BY id DESC"; 
     $result = mysqli_query($db, $sql); 
      echo '<div class="hero">'; 
      echo '<div class="hero-content">'; 
      echo '<div class="row">'; 

    while ($row = mysqli_fetch_array($result)) { 
     echo '<div class="social-img hide-750">'; 
     echo '<div class="social-content">'; 
     echo '<a style="outline: none;" href="../profiles/uploads/'.$row["images"].'" data-fancybox="quote" data-caption="Uploaded by: '.$row["username"].'" >'; 
     echo  '<img src="../profiles/uploads/'.$row["images"].'">'; 
     echo  '</a>'; 
     echo  '<div class="share">'; 
     echo    '<form enctype="multipart/form-data" action="../update_note" method="post">'; 
     echo    '<i class="fa fa-comment-o" aria-hidden="true"></i>'; 
     echo    '<a href="../delete.php?id='.$row["id"].'"><i style="float:right;" class="fa fa-times" aria-hidden="true"></i></a>'; 
     echo    '<input type="hidden" name="id" value="'.$row["id"].'"/>'; 
     echo   '<input type="hidden" name="img" value="'.$row["images"].'"/>'; 
     echo    '<input type="hidden" name="submitOne" />'; 
     echo    '<div class="col-3">'; 
     echo    '<input name="note" class="effect-2" type="texxxt" placeholder="Update your note..." /> '; 
     echo    '<span class="focus-border"></span>'; 
     echo    '</div>'; 
     echo    '</form>'; 
     echo  '</div>'; 
     ?> 
     <?php 
     $ssql = "SELECT * FROM likes WHERE userid =".$_SESSION['user_id']." AND postid=".$row['id'].""; 
     $rresult = mysqli_query($db,$ssql); 
     $lrow = mysqli_fetch_array($rresult); 
     ?> 
     <?php 
     if ($lrow['userid']==$_SESSION['user_id'] && $lrow['postid']==$row['id']) { 
      // user has already liked quote 
      echo'<div data-id="'.$row['id'].'" class="icon-appear"> 
       <span class="icon"><i style="color: #FFD700;" class="fa fa-star"></i></span> 
       <div class="border"><span></span></div> 
       <div class="satellite"> 
       <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
       </div> 
       <span class="likes_count">'.$row['likes'].'</span> 
       </div>'; 
       echo'<div data-id="'.$row['id'].'" class="icon-wrapper hide"> 
       <span class="icon"><i class="fa fa-star"></i></span> 
       <div class="border"><span></span></div> 
       <div class="satellite"> 
       <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
       </div> 
       <span class="likes_count">'.$row['likes'].'</span> 
       </div>'; 

     } else {} 

動畫腳本:

var $iconWrapper = $(".icon-wrapper"); 
$iconWrapper.on('click', function() { 
    var _this = $iconWrapper; 
    if (_this.hasClass('anim')) _this.removeClass('anim'); 
    else { 
    _this.addClass('anim'); 
    _this.css('pointer-events', 'none'); 
    setTimeout(function() { 
     _this.css('pointer-events', ''); 
    }, 1200); 
    } 
}) 

注:其實我有這樣的早期類似的問題,因爲一切都被打印出來mysqli_fetch_array裏面,我通過重新排列一些lin來解決這個問題ES。

+0

我想我們會結婚,看看您呈現的HTML代碼,看看這裏發生了什麼。您是否可以使用受影響按鈕的HYML代碼進行更新? –

+0

你也應該顯示HTML – 2017-11-11 15:34:49

+0

我加了HTML –

votes
answers
26 views
+50

Xcode 6儀器凍結

14

在Xcode 6中對我的iOS 8應用程序進行剖析儀器將運行該應用程序約5秒鐘,然後凍結。分析器仍然會在該點後運行,但該應用程序已凍結且無法使用。在設備和模擬器上發生,無論我正在使用哪個分析器(計時器,泄漏等)Xcode 6儀器凍結

從調試器運行應用程序或臨時構建工作正常。使用iOS 7進行分析也很好。

任何想法爲什麼會發生這種情況?儀器壞了嗎?

+0

如果你有一個問題,我建議提交錯誤報告。 – 2014-09-24 22:49:13

+0

感謝聖誕老人 – 2014-09-24 22:54:02

+0

我有同樣的問題,有沒有人發現任何解決方案? – 2014-11-26 12:10:09

votes
answers
77 views
+50

Vue公司2.X + Laravel 5.4在資源管理器

0

我正在寫在Laravel 5.4和Vue的2 +紗 我得到的IE錯誤以下JS錯誤的一個項目不工作(版本9-11)Vue公司2.X + Laravel 5.4在資源管理器

  1. 語法錯誤(行,其中有在常量和箭頭功能的使用)
  2. 對象不支持屬性或方法「startsWith」

我缺少什麼?我想知道我是否在濫用babel或者其他的東西不見了。我在這裏完全感到沮喪,因爲我已經花了這麼多時間來研究爲什麼在涉及Vue 2組件時IE無法正常工作。任何幫助或建議在這裏將不勝感激!

app.js:

require('./bootstrap'); 

var Promise = require('es6-promise').Promise; 
require('babel-polyfill') 
Promise.polyfill(); 
window.Vue = require('vue'); 
import Vue2Filters from 'vue2-filters' 
import BootstrapVue from 'bootstrap-vue' 

我webpack.mix.js(試圖安裝巴貝爾)

mix.js('resources/assets/js/app.js', 'public/js') 
    .sass('resources/assets/sass/app.scss', 'public/css') 
    .babel('out.es6.js', 'out.js') 
    .options({ 
     polyfills: [ 
      'Promise' 
    ] 
}); 

我的package.json

{ 
    "private": true, 
    "scripts": { 
     "dev": "npm run development", 
     "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "watch-poll": "npm run watch -- --watch-poll", 
     "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "prod": "npm run production", 
     "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", 
     "build": "babel src -d lib" 
    }, 
    "devDependencies": { 
     "accounting": "^0.4.1", 
     "axios": "^0.15.3", 
     "babel-cli": "^6.26.0", 
     "babel-core": "^6.26.0", 
     "babel-loader": "^7.1.2", 
     "babel-polyfill": "^6.26.0", 
     "babel-preset-env": "^1.6.1", 
     "babel-preset-vue-app": "^1.3.1", 
     "bootstrap-sass": "^3.3.7", 
     "cross-env": "^3.2.3", 
     "jquery": "^3.1.1", 
     "laravel-mix": "0.*", 
     "lodash": "^4.17.4", 
     "vue": "^2.4.2", 
     "vue-template-compiler": "^2.4.2", 
     "webpack": "^3.8.1" 
    }, 
    "dependencies": { 
     "bootstrap-vue": "^1.0.0-beta.7", 
     "es6-promise": "^4.1.1", 
     "vee-validate": "^2.0.0-beta.17", 
     "vue-events": "^3.0.1", 
     "vue-strap": "^1.1.37", 
     "vue2-filters": "^0.1.9", 
     "vuelidate": "^0.5.0" 
    } 
} 
+0

我使用IE和AFAIK的Vue應用程序,Vue只需要Promises填充。但是如果您使用箭頭功能,請確保您使用正確的babel設置。我認爲你需要babel-preset-es2015 - 即。 – WaldemarIce

+0

['startsWith'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)在IE中不可用,您需要對它進行填充。 Transpiling不會自動填充缺少的函數,只爲您翻譯語法。 – apokryfos

votes
answers
37 views
+50

Composer - The requested package exists as but these are rejected by your constraint

When I run my install from composer, I have this error :

λ composer install You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages.

Error :

Problem 1 - The requested package antoineb1/smoney_bundle 1.0 exists as antoineb1/smoney_bundle[dev-master] but these are rejected by your constraint.

My composer.json

{
    "name": "project",
    "license": "proprietary",
    "type": "project",
    "minimum-stability": "dev",
    "prefer-stable" : true,
    "autoload": {
        "psr-4": {
            "": "src/"
        }
    },
    "config": {
        "preferred-install": "dist"
    },
    "repositories": [
        {
            "url": "bitbucket url",
            "type": "vcs"
        }
    ],
    "require": {
        "php": ">=5.5.9",
        "antoineb1/smoney_bundle": "1.0"
    }
}
votes
answers
68 views
+50

使用iOS在WKWebView中自動播放YouTube視頻11

1

我想在我的應用中使用小型YouTube播放器。我發現推薦的唯一方法是將帶有YouTube播放器的網頁嵌入到我的應用程序中。所以我用WKWebView並加載嵌入YouTube播放器頁面自動播放參數:https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1使用iOS在WKWebView中自動播放YouTube視頻11

代碼將是這樣的:在桌面Safari瀏覽器

let webConfiguration = WKWebViewConfiguration() 
let webView = WKWebView(frame: .zero, configuration: webConfiguration) 
let youtubeURL = URL(string: "https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1") 
webView.load(URLRequest(url: youtubeURL!)) 

這個嵌入播放器自動播放的網址,但在移動Safari或WKWebView不會自動播放。我可以強制WKWebView以某種方式自動播放視頻嗎?或者使用其他YouTube播放器網址?

+0

並不在視頻的蘋果阻止自動播放? –

+0

是的,在Safari中,但我認爲你應該可以在你的應用中自動播放。 – Ondra

votes
answers
66 views
+50

使用iOS在WKWebView中自動播放YouTube視頻11

1

我想在我的應用中使用小型YouTube播放器。我發現推薦的唯一方法是將帶有YouTube播放器的網頁嵌入到我的應用程序中。所以我用WKWebView並加載嵌入YouTube播放器頁面自動播放參數:https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1使用iOS在WKWebView中自動播放YouTube視頻11

代碼將是這樣的:在桌面Safari瀏覽器

let webConfiguration = WKWebViewConfiguration() 
let webView = WKWebView(frame: .zero, configuration: webConfiguration) 
let youtubeURL = URL(string: "https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1") 
webView.load(URLRequest(url: youtubeURL!)) 

這個嵌入播放器自動播放的網址,但在移動Safari或WKWebView不會自動播放。我可以強制WKWebView以某種方式自動播放視頻嗎?或者使用其他YouTube播放器網址?

+0

並不在視頻的蘋果阻止自動播放? –

+0

是的,在Safari中,但我認爲你應該可以在你的應用中自動播放。 – Ondra

votes
answers
20 views
+50

解析來自json.loads()的數據,在python中

0

我試圖分析來自網站的數據。我解析了HTML以使用json.loads()獲取json數據。解析來自json.loads()的數據,在python中

??3210

所以現在我留下了數據,如下所示:

data = """ 
{'aggregateRating': {'reviewCount': 1691, 
        '@type'  : 'AggregateRating', 
        'ratingValue': 4.0}, 
'review': [{'reviewRating' : {'ratingValue': 5}, 
       'datePublished': '2017-10-31', 
       'description' : "I had a chance to see the Lakers ...", 
       'author'  : 'Andre W.'}] 
} 
"""" 

我感興趣的是「檢討」數組中返回從reviewRating的「ratingValue」整數。當我運行此腳本:

pd.DataFrame(data['review'], columns = ['reviewRating']) 

我得到這個:

reviewRating 
0 {'ratingValue': 5} 

相反,我在尋找的形式來獲取數據:

ratingValue 
0 5 

我已經嘗試各種變體如

pd.DataFrame(data['review'], columns = ['reviewRating']['ratingValue']) 
pd.DataFrame(data['review'], columns = ['reviewRating'][['ratingValue']]) 
pd.DataFrame(data['review']['reviewRating'], columns = ['ratingValue']) 

但我是s我不明白數據或大熊貓的下層結構。

因此,我最好清理{'ratingValue':5}作爲字符串以保留感興趣的整數,還是有一種簡單的方法來創建具有整數值'ratingValue的DataFrame 「?

謝謝。

+0

你使它看起來像如果'數據'是'json'字符串,而它可能是一個字典。 –

votes
answers
27 views
+50

禁用彈出鍵盤android-studio

3

我在我的項目開發android工作室有EdiText禁用彈出鍵盤android-studio

android:id="@+id/Number" 
    android:layout_width="match_parent" 
    android:layout_height="100dp" 
    android:textSize="24dp" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 

我需要找到一種方法來禁用鍵盤,當我點擊編輯文本,這意味着,當我在EditText點擊鍵盤不應開啓。

+1

的可能的複製[如何在EditText上時禁用鍵盤彈出?(https://stackoverflow.com/questions/10611833/how-to-disable-keypad-popup-when-on-edittext) –

votes
answers
22 views
+50

爲什麼要編寫一個腳本來檢查一些軟件包是否安裝在Linux中,如果沒有,然後安裝它?

-5

假設我從github上下載了一個bash腳本,然後運行後,在我的SYS運行它,然後它顯示爲什麼要編寫一個腳本來檢查一些軟件包是否安裝在Linux中,如果沒有,然後安裝它?

檢查XYZ包{發現]

檢查ABC包[未發現]

安裝ABC ...

他們是怎麼做到的?

+0

你有沒有嘗試過,或看過?這很容易在谷歌上找到... https://askubuntu.com/questions/519/how-do-i-write-an-application-install-shell-script –

+3

查看腳本! –

votes
answers
37 views
+50

Can you take a Javascript library and run it in Flash?

Lets say I pick up a pure Javascript library... one that doesn't rely on the DOM in any way.

Now, lets say I want to take that library and us it in Flex. Is there any good way to do this? I can't simply include the Javascript, as it is not close enough to ActionScript to compile... but is there a good converter that will do it for me? Take the Javascript prototype style classes and convert it to ActionScript classes?

Lastly, I don't want to use the Browser for this. I know that I can always use ExternalInterface to access the browser, but I am not always running my Flex app in the browser... sometimes it is Air, and sometimes it is in a PDF.

Any thoughts on this?

votes
answers
68 views
+50

使用iOS在WKWebView中自動播放YouTube視頻11

1

我想在我的應用中使用小型YouTube播放器。我發現推薦的唯一方法是將帶有YouTube播放器的網頁嵌入到我的應用程序中。所以我用WKWebView並加載嵌入YouTube播放器頁面自動播放參數:https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1使用iOS在WKWebView中自動播放YouTube視頻11

代碼將是這樣的:在桌面Safari瀏覽器

let webConfiguration = WKWebViewConfiguration() 
let webView = WKWebView(frame: .zero, configuration: webConfiguration) 
let youtubeURL = URL(string: "https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1") 
webView.load(URLRequest(url: youtubeURL!)) 

這個嵌入播放器自動播放的網址,但在移動Safari或WKWebView不會自動播放。我可以強制WKWebView以某種方式自動播放視頻嗎?或者使用其他YouTube播放器網址?

+0

並不在視頻的蘋果阻止自動播放? –

+0

是的,在Safari中,但我認爲你應該可以在你的應用中自動播放。 – Ondra

votes
answers
39 views
+50

代表給定的LSB/V的正弦波

-2

我創建了一個電壓信號的正弦波。 如何用128 LSB/Volts的比例表示? 振幅爲180伏。 Obs:我猜LSB是「低顯着位」。代表給定的LSB/V的正弦波

我的代碼:

int main(int argc, char **argv) { 
    int i = 0; 
    short value; 
    double amp = 180, freq = 60, freq_samp; 

    freq_samp = atof(argv[2]); 
    printf("
** Sample frequency: %f **",freq_samp); 
    while(1) { 
     value = amp*sin(2*i*PI*freq/freq_samp); 
     printf("
Value = %d",value); 
     i = i + 1; 
     sleep(1); 
    } 

    return 0; 
} 
votes
answers
25 views
+50

如何從JSON數組

0

打印單場數據我一直在使用laravel DB門面運行一個查詢,它是返回一個JSON數組對象,但是當我想從JSON數組訪問單個字段值是顯示錯誤。如何從JSON數組

這是我的查詢部分。

$dsale=DB::table('directsales') 
      ->join('clients','directsales.client_id','=','clients.id') 
      ->join('products','directsales.product_id','=','products.id') 
      ->select('clients.client_name','clients.addr','directsales.*','products.name') 
      ->where('directsales.client_id','=',$client_id) 
      ->whereBetween('directsales.issue_date',[$fromdate,$todate]) 
      ->distinct() 
      ->get(); 

      return $dsale; 

這是我的結果。

[{"client_name":"client one","addr":"jdkdhjfkhdkshfds","id":1,"transaction_code":"IN--00000001","client_id":1,"product_id":1,"product_code":"P0007","unitperctn":20,"unitprice":100,"ctn":4,"pcs":5,"total":4500,"deliverd_by":"nazim","issue_date":"2017-12-01","created_at":"2017-11-28 13:55:29","updated_at":"2017-11-28 13:55:33","name":"Dano Instant 2.5 Kg Packet 6"},{"client_name":"client one","addr":"jdkdhjfkhdkshfds","id":2,"transaction_code":"IN--00000002","client_id":1,"product_id":1,"product_code":"P0001","unitperctn":12,"unitprice":100,"ctn":1,"pcs":1,"total":2,"deliverd_by":"majed","issue_date":"2017-12-01","created_at":null,"updated_at":null,"name":"Dano Instant 2.5 Kg Packet 6"},{"client_name":"client one","addr":"jdkdhjfkhdkshfds","id":3,"transaction_code":"IN--00000002","client_id":1,"product_id":4,"product_code":"P0004","unitperctn":12,"unitprice":90,"ctn":1,"pcs":3,"total":6,"deliverd_by":"majed","issue_date":"2017-12-01","created_at":null,"updated_at":null,"name":"All time bread"},{"client_name":"client one","addr":"jdkdhjfkhdkshfds","id":5,"transaction_code":"IN--00000004","client_id":1,"product_id":1,"product_code":"P0001","unitperctn":12,"unitprice":100,"ctn":1,"pcs":0,"total":1,"deliverd_by":"majed","issue_date":"2017-12-12","created_at":null,"updated_at":null,"name":"Dano Instant 2.5 Kg Packet 6"},{"client_name":"client one","addr":"jdkdhjfkhdkshfds","id":6,"transaction_code":"IN--00000005","client_id":1,"product_id":4,"product_code":"P0004","unitperctn":12,"unitprice":90,"ctn":3,"pcs":3,"total":3510,"deliverd_by":"add","issue_date":"2017-12-03","created_at":null,"updated_at":null,"name":"All time bread"},{"client_name":"client one","addr":"jdkdhjfkhdkshfds","id":10,"transaction_code":"IN--00000007","client_id":1,"product_id":4,"product_code":"P0004","unitperctn":12,"unitprice":90,"ctn":1,"pcs":6,"total":1620,"deliverd_by":"majed","issue_date":"2017-11-01","created_at":null,"updated_at":null,"name":"All time bread"}] 

當我打印CLIENT_NAME $ dsale - > [ 'CLIENT_NAME'] [0]這樣它的顯示錯誤。

+0

嘗試:'$ dsale [0] [ 'CLIENT_NAME']' - HTTPS://3v4l.o RG/nCQuV –

+0

不是JSON,這是一個集合或數組的對象stdClass已經......只有當你試圖用「echo」他們會看到JSON – lagbox

votes
answers
33 views
+50

What is the difference between PreserveReferencesHandling and ReferenceLoopHandling in Json.Net?

I am looking at one WebAPI application sample that has this coded:

json.SerializerSettings.PreserveReferencesHandling 
   = Newtonsoft.Json.PreserveReferencesHandling.Objects;

and another with this coded:

json.SerializerSettings.ReferenceLoopHandling 
   = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Neither explain why each is chosen. I'm very new to WebAPI, so can someone help by explaining to me in simple terms what the differences are and why I might need to use one over the other.

votes
answers
19 views
+50

如何在同一個表格中設置最小和最大值?

-2

如何在同一個表格中設置最小和最大值?

<table> 
 
    <thead> 
 
    <tr> 
 
    <th><div>Agent ID</div></th> 
 
    <th><div>Country</div></th> 
 
    <th><div>Address</div></th> 
 
    <th>Date</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
     <tr *ngFor="let item of resolvedAgents"> 
 
      <td>{{item.agent}}</td> 
 
      <td>{{item.country}}</td> 
 
      <td>{{item.address}}</td> 
 
      <td>{{item.date}}</td> 
 
     </tr> 
 
    </tbody> 
 
    <tfoot> 
 
    <tr> 
 
    <td colspan="4"> 
 
     {{ resolvedAgents?.length }} missions 
 
    </td> 
 
    </tr> 
 
    </tfoot> 
 
</table>

import { Component, OnInit } from '@angular/core'; 
 
import { Agent } from '../shared/model/agent'; 
 
import { AgentsService } from '../shared/services/agents.service'; 
 

 

 

 
@Component({ 
 
    selector: 'nga-agents-list', 
 
    templateUrl: './agents-list.component.html', 
 
    styleUrls: ['./agents-list.component.scss'] 
 
}) 
 
export class AgentsListComponent implements OnInit { 
 
    resolvedAgents: Agent[]; 
 

 
    constructor(private agentService: AgentsService) { 
 
    } 
 

 
    ngOnInit() { 
 
    this.agentService.getAllAgents().subscribe((agents: Agent[]) => { 
 
     agents.sort((x: Agent, y: Agent) => 
 
     Number(new Date(x.date)) - Number(new Date(y.date))); 
 
     this.resolvedAgents = agents; 
 
     this.getIsolatedAgents(); 
 
    }); 
 
    } 
 

 
    setMinMax(agent: Agent) { 
 
    return this.pipe.transform(this.resolvedAgents, 'distance'); 
 
    } 
 

 
} 
 

 

 

 
0 
 
: 
 
{agent: "005", country: "Brazil", address: "Rua Roberto Simonsen 122, Sao Paulo", date: "May 5, 1986, 8:40:23 AM", distance: 9496.361799166812} 
 
1 
 
: 
 
{agent: "007", country: "Brazil", address: "Avenida Vieira Souto 168 Ipanema, Rio de Janeiro", date: "Dec 17, 1995, 9:45:17 PM", distance: 9285.800150412106} 
 
2 
 
: 
 
{agent: "011", country: "Poland", address: "swietego Tomasza 35, Krakow", date: "Sep 7, 1997, 7:12:53 PM", distance: 1415.508180342706} 
 
3 
 
: 
 
{agent: "007", country: "Morocco", address: "27 Derb Lferrane, Marrakech", date: "Jan 1, 2001, 12:00:00 AM", distance: 2301.0971356885716} 
 
4 
 
: 
 
{agent: "013", country: "Poland", address: "Zlota 9, Lublin", date: "Oct 17, 2002, 10:52:19 AM", distance: 1569.274444863945} 
 
5 
 
: 
 
{agent: "008", country: "Brazil", address: "Rua tamoana 418, tefe", date: "Nov 10, 2005, 1:25:13 PM", distance: 8589.24697562705} 
 
6 
 
: 
 
{agent: "005", country: "Poland", address: "Rynek Glowny 12, Krakow", date: "Apr 5, 2011, 5:05:12 PM", distance: 1415.2498838353406} 
 
7 
 
: 
 
{agent: "003", country: "Morocco", address: "Rue Al-Aidi Ali Al-Maaroufi, Casablanca", date: "Aug 29, 2012, 10:17:05 AM", distance: 2080.2380214223626} 
 
8 
 
: 
 
{agent: "009", country: "Morocco", address: "atlas marina beach, agadir", date: "Dec 1, 2016, 9:21:21 PM", distance: 2470.703534438294} 
 
9 
 
: 
 
{agent: "002", country: "Morocco", address: "Riad Sultan 19, Tangier", date: "Jan 1, 2017, 5:00:00 PM", distance: 1804.7796192553526}

votes
answers
29 views
+50

How to mark a method as obsolete or deprecated?

How do I mark a method as obsolete or deprecated using C#?

votes
answers
21 views
+50

如何使用XML解析childrenNodes javascript

0

我正在嘗試採取此示例xml響應並解析此xml的子節點和子節點。 Prin和Role對象將用於創建相關記錄,其中主記錄的PrinID將設置爲相關子記錄的角色。如何使用XML解析childrenNodes javascript

我遇到的挑戰是循環通過子對象,然後立即解析子記錄。我寫的代碼已經單獨執行,不允許我爲每個角色創建相關記錄。

如果我採用相同的邏輯並將getElementsByTagName更改爲Role,它只是簡單地解析那些與其父對象沒有任何關係的記錄。

我該如何寫第二個循環或迭代器,以便在循環其子記錄的角色的同時獲取主記錄的PrinID

<Prin> 
    <PrinName>John</PrinName> 
    <PrinID>12345</PrinID> 
    <Role> 
     <Code>1111</Code> 
    </Role> 
    <Role> 
     <Code>2222</Code> 
    </Role> 
</Prin> 

<Prin> 
    <PrinName>James</PrinName> 
    <PrinID>45678</PrinID> 
    <Role> 
     <Code>3333</Code> 
    </Role> 
    <Role> 
     <Code>4444</Code> 
    </Role> 
</Prin> 

var prinID=""; 
var prinList=prinDoc.getDocumentElement().getElementsByTagName("Prin"); 

for (var i=0;i<prinList.getLength();i++){ 
    var childList=prinList.item(i).getChildNodes(); 
    for (var j=0;j<childList.getLength();j++){ 
     var childNode=childList.item(j); 
     if (childNode.getNodeName()=="PrinName"){ 
      prinID=childNode=getTextContent(); 
     } 
    } 
} 
votes
answers
35 views
+50

Where are ${EXECUTABLE_NAME} and ${PRODUCT_NAME} defined

Where can I find information on how to modify these

  • ${EXECUTABLE_NAME}
  • ${PRODUCT_NAME}

These are only displayed in .plist file but where are the actual values.

If we can directly modify what ever we want in .plist why we need these.

I am new that's why I'm having problem understanding these, I also looked into apple information Property list key reference but didn't find these ${} values.

votes
answers
41 views
+50

未經認證的用戶也可以登錄。

0

我有一個簡單的表單來註冊和登錄,使用firebase存儲和驗證。註冊用戶可以通過Firebase收到確認郵件。但未經驗證的用戶也可以登錄,這裏做錯了什麼。未經認證的用戶也可以登錄。

登錄-page.component.ts

import { Component, OnInit } from '@angular/core'; 
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms'; 
import * as firebase from 'firebase'; 

@Component({ 
    selector: 'app-login-page', 
    templateUrl: './login-page.component.html', 
    styleUrls: ['./login-page.component.css'] 
}) 
export class LoginPageComponent implements OnInit { 
    signin:FormGroup; 
    constructor(private fb: FormBuilder) { 
    this.signin = fb.group({ 
     email : [null, Validators.compose([Validators.required, this.nospaceValidator])], 
     password : [null, Validators.required] 
    }); 
    } 

    ngOnInit() { 
    } 

signUp(){ 
    let values = this.signin.value; 
    console.log(values.email,values.password) 
    firebase.auth().createUserWithEmailAndPassword(values.email,values.password) 
    .then(
     function(user){ 
     if(user && user.emailVerified === false){ 
     user.sendEmailVerification() 
     .then(function(){ 
      console.log("email verification sent to user"); 
     }); 
     } 
    } 
    ) 
    .catch(
     function(error) { 
    var errorCode = error.code; 
    var errorMessage = error.message; 
    console.log(errorMessage) 
}); 
} 
signIn(){ 
firebase.auth().onAuthStateChanged(
    function(user) { 
    if (user.emailVerified) { 
    console.log('Email is verified'); 
    } 
    else { 
    console.log('Email is not verified'); 
    } 
}); 
} 
} 
+0

我看到您創建用戶的位置,但您實際上在哪裏簽名? – DoesData

votes
answers
43 views
+50

服務器vsFTPd連接失敗

-1

我試圖在ftp localhost上連接,但登錄名/密碼總是失敗。 我已經安裝了vsFTPd。 我想我必須修改passwd.conf。但我該如何處理? 我有這條線:服務器vsFTPd連接失敗

paul:x:1000:1000:paul,,,:/home/paul:/bin/false 

謝謝!

+1

請將您的問題移到[su]或[sf](在這裏刪除,重新發布)。這是[off-topic here](// stackoverflow.com/help/on-topic)。 –

votes
answers
51 views
+50

如何從backgroundWorker線程創建通用控件?

0

我在使用後臺工作人員創建我的對象模型時遇到了麻煩。如何從backgroundWorker線程創建通用控件?

據我瞭解爲什麼,我無法找到解決方法。

這裏是僞邏輯:

  • 呼叫web服務異步

  • 接收。當,在Load方法背景

  • 打開背景工人,和數據裝載到控制,搜索現有對象,如果找不到,則創建一個新對象。

所有創建的對象都從Control繼承(具有透明抽象層)。

雖然我在主線程創建控件,功能,做工精細:

public static T Find<T>(ObservableCollection<T> collection, int objectId) 
     where T : FormaliteBaseControl, new() 
    { 
     foreach (T item in collection) 
     { 
      if (item.ObjectId == objectId) 
       return item; 
     } 

     return new T(); 
    } 

當然,從後臺線程調用時,一個跨線程異常的「新T()」 發生在Silverlight ,無法同步調用Dispatcher.Invoke。

雖然我以這種方式創建了大約450個對象,但我希望將對象模型創建保留在後臺而不會降低Thread.Sleep或其他「好」方法的性能。

感謝您的回答。

+0

將450個UI控件放入什麼類型的容器?一個ItemsControl或列表框?什麼是虛擬化? – WiredPrairie 2010-08-17 12:22:16

+0

由於您使用的是線程,因此您可能會遇到與您正在使用的集合有關的問題 - 如果您是從另一個線程修改集合(而另一個線程正在使用枚舉器,則通過foreach)。 – WiredPrairie 2010-08-17 12:23:39

votes
answers
41 views
+50

MVC4 Less Bundle @import Directory

I'm trying to use MVC4 bundling to group some of my less files, but it looks like the import path I'm using is off. My directory structure is:

static/
    less/
        mixins.less
        admin/
            user.less

In user.less, I'm attempting to import mixins.less using this:

@import "../mixins.less";

This used to work for me before when using chirpy with dotless, but now I noticed ELMAH was getting mad at me, saying this:

System.IO.FileNotFoundException: 
    You are importing a file ending in .less that cannot be found.
File name: '../mixins.less'

Am I supposed to use a different @import with MVC4?

Some additional info

Here's the less class and global.asax.cs code I'm using to attempt this:

LessMinify.cs

...
public class LessMinify : CssMinify
{
    public LessMinify() {}

    public override void Process(BundleContext context, BundleResponse response)
    {
        response.Content = Less.Parse(response.Content);
        base.Process(context, response);
    }
}
...

Global.asax.cs

...
DynamicFolderBundle lessFB = 
    new DynamicFolderBundle("less", new LessMinify(), "*.less");

BundleTable.Bundles.Add(lessFB);

Bundle AdminLess = new Bundle("~/AdminLessBundle", new LessMinify());
...
AdminLess.AddFile("~/static/less/admin/user.less");
BundleTable.Bundles.Add(AdminLess);
...
votes
answers
45 views
+50

Rails Devise: after_confirmation

Is there a way to create a after_confirmation :do_something ?

The goal is to send an e-mail after the user confirms using Devise :confirmable.

votes
answers
19 views
+50

線程等待監視器

1

約我在我的公司開發的應用的性能提升有過會談。此應用程序包含執行大量xml解析的計劃任務。在某個小時內,當很多此類任務被觸發時,應用程序變得很慢。我一直在查看在某個高峯時間收集的線程轉儲,以查看可能會發生什麼成爲問題..但是,對於這種練習的新手,我無法理解它。下面是線程轉儲的摘錄。線程等待監視器

"JMSThread(5)-7635" daemon prio=10 tid=0x000000004fb5b800 nid=0x71e in Object.wait() [0x0000000048de8000] 
    java.lang.Thread.State: TIMED_WAITING (on object monitor) 
    at java.lang.Object.wait(Native Method) 
    - waiting on <0x00002aaabf41fe38> (a java.lang.Object) 
    at EDU.oswego.cs.dl.util.concurrent.BoundedLinkedQueue.poll(BoundedLinkedQueue.java:253) 
    - locked <0x00002aaabf41fe38> (a java.lang.Object) 
    at EDU.oswego.cs.dl.util.concurrent.PooledExecutor.getTask(PooledExecutor.java:723) 
    at org.jboss.util.threadpool.MinPooledExecutor.getTask(MinPooledExecutor.java:106) 
    at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExecutor.java:747) 
    at java.lang.Thread.run(Thread.java:619) 
    Locked ownable synchronizers: 
    - None 


JMSThread(5)-7634" daemon prio=10 tid=0x000000004ed5c800 nid=0x716 in Object.wait() [0x0000000044eb2000] 
    java.lang.Thread.State: TIMED_WAITING (on object monitor) 
    at java.lang.Object.wait(Native Method) 
    - waiting on <0x00002aaabf41fe38> (a java.lang.Object) 
    at EDU.oswego.cs.dl.util.concurrent.BoundedLinkedQueue.poll(BoundedLinkedQueue.java:253) 
    - locked <0x00002aaabf41fe38> (a java.lang.Object) 
    at EDU.oswego.cs.dl.util.concurrent.PooledExecutor.getTask(PooledExecutor.java:723) 
    at org.jboss.util.threadpool.MinPooledExecutor.getTask(MinPooledExecutor.java:106) 
    at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExecutor.java:747) 
    at java.lang.Thread.run(Thread.java:619) 
    Locked ownable synchronizers: 
    - None 

有幾個這樣的條目鎖定和等待在同一個對象上。任何人都可以幫我理解他們的意思嗎?這是否表明有任何問題?

votes
answers
28 views
+50

How to remove node from elasticsearch cluster on runtime without down time

Suppose I had 5 nodes in cluster and I had to remove 2 node on run-time. So how it can be done without affecting the indices?

I had continuous stream of data coming at nearly 10 Gbphour which is getting indexed continuously.

Is rebalancing will do any help in this? Thanks in advance

votes
answers
28 views
+50

How to remove node from elasticsearch cluster on runtime without down time

Suppose I had 5 nodes in cluster and I had to remove 2 node on run-time. So how it can be done without affecting the indices?

I had continuous stream of data coming at nearly 10 Gbphour which is getting indexed continuously.

Is rebalancing will do any help in this? Thanks in advance

votes
answers
29 views
+50

OpenCV not working properly with python on Linux with anaconda. Getting error that cv2.imshow() is not implemented

This is the exact error that I am getting. My OS is Ubuntu 16.10.

OpenCV Error: Unspecified error (The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script) in cvShowImage, file /feedstock_root/build_artefacts/work/opencv-3.1.0/modules/highgui/src/window.cpp, line 545 Traceback (most recent call last): File "untitled.py", line 7, in cv2.imshow('image',img) cv2.error: /feedstock_root/build_artefacts/work/opencv-3.1.0/modules/highgui/src/window.cpp:545: error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function cvShowImage

my code is:

import numpy as np
import cv2

# Load an color image in grayscale
img = cv2.imread('0002.png',0)

cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

0002.png is an image in the same directory as the program. I first installed anaconda with python 3.5, then I installed opencv by using the command

conda install -c conda-forge opencv

I installed libgtk2.0-dev just as the error said to but I still get the same error. Any help would be much appreciated. I've been trying to solve this for several hours.

votes
answers
24 views
+50

如何擴展jQuery評論?

0

我使用jquery-comments來允許在我的網站上發表評論。這工作正常,但我想對它的工作原理做一些改變。如何擴展jQuery評論?

但是,我不想直接在jquery-comments.js中對jquery註釋進行更改,而是想將它們放在不同的文件中,並儘可能使用我自己的函數擴展/修改Comments對象。

例如,我想改變函數createCommentingFieldElement中發生的情況。

我該怎麼做?

votes
answers
41 views
+50

你將如何調用這個變量「direct3Ddevice」或「direct3dDevice」?

1

我下面的命名約定規則:你將如何調用這個變量「direct3Ddevice」或「direct3dDevice」?

  • 混合的情況下開始的小寫字母(例如theDevice
  • 不使用多個大寫字母縮略語/首字母(例如的,而不是XmlDeviceXMLDevice)以提高可讀性。

我遇到的問題是,我是否應該寫我的變量direct3dDevicedirect3Ddevicedirect3DDevice

direct3dDevice

  • 的「3」可以被看作是一個大寫字母(因爲它是類似的尺寸),或者只是作爲一個縮寫的一部分,因此,「d」它應該是一個後小寫字母。特別是因爲'Direct3D'是一個名字。

direct3Ddevice

  • 的「3」是一個數字,而不應被視爲一個大寫字母,因此第一個字母之後,「d」應當大寫。 'device'中的下一個'd'應該是小寫字母,因爲不應該有兩個大寫字母。

direct3DDevice

  • 的「3」是一個數字,而不應被視爲一個大寫字母,因此第一個字母之後,「d」應當大寫。 'device'中的下一個'd'應該是大寫字母,以遵循用大寫字母開始新詞的混合大小寫慣例。
+1

您使用哪種語言?如果你使用的是.NET語言,那麼最後一個是推薦的命名約定,至少根據ReSharper。 –

+0

@MoonMoo我正在使用C++。 –

votes
answers
25 views
+50

啓動新活動時沒有後退按鈕

0

使用意圖啓動新活動時,活動頂部的欄會自動提供後退按鈕嗎?我認爲這是它的工作原理,但沒有看到它。如果它沒有自動出現,需要什麼來使其顯示?啓動新活動時沒有後退按鈕

+2

你甚至嘗試過搜索嗎?關於這個問題已經有很多答案,例如:http://stackoverflow.com/questions/14545139/android-back-button-in-the-title-bar – Squeazer 2014-11-08 21:11:26

+0

@Squeazer謝謝你指點我!我確實嘗試過搜索,但奇怪的是沒有什麼有用的。這完全回答了我的問題。 – user2345093 2014-11-08 21:36:06

votes
answers
53 views
+50

運行時錯誤1004 - BeforePrint - 避免打印如果單元格爲空

0

我想創建一個宏以防止用戶打印表單,如果他們不填寫所有單元格。不過,我得到一個錯誤信息:運行時錯誤1004 - BeforePrint - 避免打印如果單元格爲空

enter image description here

Private Sub Workbook_BeforePrint(Cancel As Boolean) 
If Application.Sheets("Form").Range("B4,C4,D4,E4,F4,G4,H4,I4,J4,K4,L4,M4,B5,C5,D5,E5,F5,G5,H5,I5,J5,K5,L5,M5,B6,C6,D6,E6,F6,G6,H6,I6,J6,K6,L6,M6,B7,C7,D7,E7,F7,G7,H7,I7,J7,K7,L7,M7,B8,C8,D8,E8,F8,G8,H8,I8,B9,C9,D9,E9,F9,G9,H9,I9,B11,C11,D11,E11,F11,G11,H11,I11,B12,C12,D12,E12,F12,G12,H12,I12,B13,C13,D13,E13,F13,G13,H13,I13,B14,C14,D14,E14,F14,G14,H14,I14,B16,C16,D16,E16,F16,G16,H16,I16,B17,C17,D17,E17,F17,G17,H17,I17").Value = "" Then 
Cancel = True 
MsgBox "Fill out all the cells" 
End If 
End Sub 

我有具有較少細胞的另一種形式的另一個宏和一個工作得很好:我能做些什麼

Private Sub Workbook_BeforePrint(Cancel As Boolean) 
If Application.Sheets("Form 2").Range("C4,C5,C6,D4,D5,D6,F4,F5,F6,B8,B9,B10,B11,C8,C9,C10,C11,D8,D9,D10,D11,E8,E9,E10,E11,C13,D13,C16,C17,C18,F16,F17,F18,C22,D22").Value = "" Then 
Cancel = True 
MsgBox "Fill out all the cells" 
End If 
End Sub 

解決這個問題?

+0

這第二個真正的作品? (B4:M7「)與範圍(」B4,C4,D4,E4,F4,G4,H4,I4,J4,K4,L4,M4,B5,C5,D5,E5 ,F5,G5,H5,I5,J5,K5,L5,M5,B6,C6,D6,E6,F6,G6,H6,I6,J6,K6,L6,M6,B7,C7,D7,E7,F7 ,G7,H7,I7,J7,K7,L7,M7「) –

+0

謝謝,我用更好的範圍編輯了我的答案,我應該注意到... – garbb

+0

[Range limit conundrum](https:// stackoverflow.com/questions/1663264/range-limit-conundrum) – YowE3K

votes
answers
38 views
+50

如何在TypeScript中使用React,Redux進行API調用

0

我使用typescript-fsatypescript-fsa-reducers包簡單地在TypeScript React應用程序中創建動作和縮減器。如何在TypeScript中使用React,Redux進行API調用

const actionCreator = actionCreatorFactory(); 

export function signInHandler(state: UserState, action: Action): UserState { 
    // ???? 

    return { ...state }; 
} 

export const signIn = actionCreator.async<SignInRequest, RequestResponse<SignInResponse>>("USER_SIGNIN"); 

export const UserReducer = reducerWithInitialState({ signedIn: false } as UserState) 
    .casesWithAction([signIn.started, signIn.done], signInHandler) 
    .build(); 

用法在組件:

export default connect<StateProps, DispatchProps>(
    (state: RootState) => ({} as StateProps), 
    (dispatch: Dispatch<RootState>) => { 
    return { 
       signIn: (userName: string, password: string) => dispatch(signIn.started(new SignInRequest(userName, password))) 
    }; 
    } 
)(SignIn); 

現在我卡住了。我不知道如何對我的API進行HTTP調用,以便在API響應到達時,組件分派調度下一個動作時發送請求。我想用承諾。 如何解決?

+0

你見過'typescript-fsa'中的異步操作文檔嗎? https://github.com/aikoven/typescript-fsa#async-action-creators –

+0

是的,但我不知道應該在哪裏進行API調用。行動,行動創造者還是減速器?我想看一個例子 – micnyk

votes
answers
17 views
+50

Laravel Passport API測試不起作用

1

我正在嘗試第一次使用Laravel護照。我已經安裝護照,併成立了一個客戶。我正在使用發佈人進行測試。我在標題內容類型和授權中給了兩件事,但它將我重定向回登錄頁面。我試圖通過這條路線Laravel Passport API測試不起作用

Route::get('articles', '[email protected]')->middleware('auth:api'); 

讓所有的物品//我已經改變了所有的東西在後臺從laravel DOC

use HasApiTokens, Notifiable; 

     Passport::routes(); 

'api' => [ 
     'driver' => 'passport', 
     'provider' => 'users', 
    ], 

my postman capture

+0

你把這個''>中間件('auth:api')'放在哪個文件中? web.php或api.php? – C2486

+0

我把它放在web.php –

+0

改變所有路由到api.php而不是web.php並嘗試? – C2486

votes
answers
16 views
+50

How to filter logcat in Android Studio?

In my logcat there is too much output, so I'd like to filter it using some keywords, basically displaying only the output containing the keyword(s). Is there a way to do that in Android Studio through the UI?

votes
answers
46 views
+50

重新啓動計時器

0

由於暫停按鈕被暫停音頻文件,所以時間無效以暫停更新視圖。重新啓動計時器

-(void)playpauseAction:(id)sender 
{ 

if 

    ([audioPlayer isPlaying]){ 

[sender setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateSelected]; 

    [audioPlayer pause]; 

[timer invalidate]; 

    } else { 

[sender setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal]; 

    [audioPlayer play]; 

    self.timer = [NSTimer scheduledTimerWithTimeInterval:11 target:self selector:@selector(displayviewsAction:) userInfo:nil repeats:NO]; 

    } 

} 

- (void)displayviewsAction:(id)sender 
{ 
FirstViewController *viewController = [[FirstViewController alloc] init]; 

viewController.view.frame = CGRectMake(0, 0, 320, 480); 

[self.view addSubview:viewController.view]; 

[self.view addSubview:toolbar]; 

self.timer = [NSTimer scheduledTimerWithTimeInterval:23 target:self selector:@selector(secondViewController) userInfo:nil repeats:NO]; 

[viewController release]; 

} 

-(void)secondViewController { 
SecondViewController *secondController = [[SecondViewController alloc] init]; 

secondController.view.frame = CGRectMake(0, 0, 320, 480); 

[self.view addSubview:secondController.view]; 

[self.view addSubview:toolbar]; 

self.timer = [NSTimer scheduledTimerWithTimeInterval:27 target:self selector:@selector(ThirdviewController) userInfo:nil repeats:NO]; 

[secondController release]; 
} 

它是這樣的多個視圖。根據應用程序邏輯,用戶可以在任何視圖上點擊暫停以暫停音頻文件,定時器無效語句也會暫停視圖更新。當用戶再次暫停以恢復音頻文件時,它應該從該點開始更新視圖。所以,我遇到的問題是如何重新啓動計時器,以便不管用戶在哪個視圖中暫停,都會繼續更新視圖。

Anyideas我該怎麼做。

votes
answers
61 views
+50

如何從文件中讀取文本到ruby中的數組

0

有沒有辦法將net-ssh gem中的HOST,USER,PASS varibales視爲一個數組,並且有多個值?如何從文件中讀取文本到ruby中的數組

我目前有一個帶有HOST,USER和PASS值的外部文本文件,但是我需要將這些內容傳遞給net-ssh gem中的上述變量。

任何幫助和編輯來澄清問題,我們感謝! :)

votes
answers
33 views
+50

Freeze on thinking sphinx stop(ts:stop) in capistrano

When I trying to deploy my app via capistrano, on ts:stop command there is infinity freeze, so deploy proccess can't finish well. Any ideas?

enter image description here

Here is a trace log:

** Invoke ts:stop (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute ts:stop
votes
answers
11 views
+50

想在給定的時間間隔後動態地打印字母,錯誤:[$ rootScope:infdig] 10 $ digest()迭代到達。中止(...)

0
var str = "get_data_httpaja.php?un=" + $scope.uName; 
var avail=["a","v","a","i","l","a","b","l","e"]; 
var i=0; 
$http.get(str).then(function (dt) { 
    alert(dt.data); 
    //  $scope.uPlace = dt.data; 
    if(dt.data==0){ 
     var myvar=$window.setInterval(function() { 
      $scope.$watch("uAvailable",function (nv,ov) { 
       $scope.uAvailable+=avail[i]; 
      }) 
      i++;      
     },500) 
     if(i>8)$window.clearInterval(myvar); 
    } 
} 

我取出由服務器的結果,以後如果result==0然後我想打印的字母「可用」動態信,但收到錯誤:(

votes
answers
41 views
+50

MVC4 Less Bundle @import Directory

I'm trying to use MVC4 bundling to group some of my less files, but it looks like the import path I'm using is off. My directory structure is:

static/
    less/
        mixins.less
        admin/
            user.less

In user.less, I'm attempting to import mixins.less using this:

@import "../mixins.less";

This used to work for me before when using chirpy with dotless, but now I noticed ELMAH was getting mad at me, saying this:

System.IO.FileNotFoundException: 
    You are importing a file ending in .less that cannot be found.
File name: '../mixins.less'

Am I supposed to use a different @import with MVC4?

Some additional info

Here's the less class and global.asax.cs code I'm using to attempt this:

LessMinify.cs

...
public class LessMinify : CssMinify
{
    public LessMinify() {}

    public override void Process(BundleContext context, BundleResponse response)
    {
        response.Content = Less.Parse(response.Content);
        base.Process(context, response);
    }
}
...

Global.asax.cs

...
DynamicFolderBundle lessFB = 
    new DynamicFolderBundle("less", new LessMinify(), "*.less");

BundleTable.Bundles.Add(lessFB);

Bundle AdminLess = new Bundle("~/AdminLessBundle", new LessMinify());
...
AdminLess.AddFile("~/static/less/admin/user.less");
BundleTable.Bundles.Add(AdminLess);
...
votes
answers
38 views
+50

Subversion repository statistics, other than StatSVN?

Are there other open source/free packages for producing repository statistics for a Subversion repository?

I've tried StatSVN but it seems to be incompatible with the logfiles for Subversion 1.5 and above.

Note, I know that TortoiseSVN has some statistics built into its dialogs and repository browsing code, but this is not what I'm looking for.

What I'm looking for is a tool that can analyze the repository, and its logs, and produce statistics like these:

  • Who checked in the most code
  • Code growth over time
  • Busy files (changed often)
votes
answers
36 views
+50

使用高級函數中的參數/ s調用lambda

1

我是java/kotlin中函數式編程的新手,並進行一些練習。 只是想知道如何在調用lambda時傳遞參數。例如,在這裏調用someMethod我需要傳遞一個Int參數。使用高級函數中的參數/ s調用lambda

fun lambdaTest(someMethod: (Int) -> Boolean){ 
    someMethod() 
} 

這怎麼辦?答案可能很簡單,我只是沒有在任何地方找到它,在文檔中有隻列出的例子,如果其中的答案是明確的:

fun <T, R> List<T>.map(transform: (T) -> R): List<R> { 
    val result = arrayListOf<R>() 
    for (item in this) 
     result.add(transform(item)) 
    return result 
} 
votes
answers
40 views
+50

的onclick()獲取地理位置是不行的

-1

請告訴我問題:的onclick()獲取地理位置是不行的

如果 (我環繞navigator.geolocation.getCurrentPosition(initMap, onError);蒙山function triger()然後調用它像: <button id="btn" class="btn btn-default" onclick="triger()">

然後

它什麼都不做!

其他

它的好!

這裏是我的代碼:

<script> 

    var map; 
    var infowindow; 
    var selecteditem="hospital"; 
    var radiusin=5000; 

    function triger() { 
     navigator.geolocation.getCurrentPosition(initMap, onError); 

} 

    function onError(error){ 
    alert("the code is " + error.code + ". 
" + "message: " + error.message); 
} 

    function initMap(position) { 

    selecteditem= $("#selector").val(); 
    radiusin= $("#radius").val();  
    alert(selecteditem+"in"+radiusin); 
    var longitude = position.coords.longitude; 
    var latitude = position.coords.latitude; 
    var latLong = new google.maps.LatLng(latitude, longitude); 
    var pyrmont = latLong;// {lat: -33.867, lng: 151.195}; 
    map = new google.maps.Map(document.getElementById('map'), { 
     center: pyrmont, 
     zoom: 14 
    }); 
    infowindow = new google.maps.InfoWindow(); 
    var service = new google.maps.places.PlacesService(map); 
    service.nearbySearch({ 
     location: pyrmont, 
     radius: radiusin, 
     type: selecteditem 
    }, callback); 
    } 
    function callback(results, status) { 
    if (status === google.maps.places.PlacesServiceStatus.OK) { 
     for (var i = 0; i < results.length; i++) { 
     createMarker(results[i]); 
     } 
    } 
    } 
    function createMarker(place) { 
    var placeLoc = place.geometry.location; 
    var marker = new google.maps.Marker({ 
     map: map, 
     position: place.geometry.location 
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
     infowindow.setContent(place.name); 
     infowindow.open(map, this); 
    }); 
    } 
</script> 

和:

<div class="input-group-btn"> 
    <button id="btn" class="btn btn-default" onclick="triger()"> 
    <i class="glyphicon glyphicon-search"></i> 
    </button> 
</div> 
+1

爲什麼類型=提交?使用類型=按鈕 – mplungjan

+0

@mplungjan對不起,這是一個錯誤,順便說它不工作... –

+1

控制檯錯誤? – mplungjan

votes
answers
65 views
+50

Django模型表單設置了外鍵下拉的可能值

0

我有一個表格ReviewForm,它擴展ModelFormReviewForm的模型是Review,它具有以下字段:Django模型表單設置了外鍵下拉的可能值

class Review(models.Model): 
    message = models.TextField(max_length = 4000) 
    created_at = models.DateTimeField(auto_now_add = True) 
    updated_at = models.DateTimeField(null = True) 
    rating = models.IntegerField(
     default = 5, 
     validators = [MaxValueValidator(5), MinValueValidator(0)] 
    ) 
    prof = models.ForeignKey(Prof, related_name = 'reviews') 
    course = models.ForeignKey(Course, related_name = 'reviews') 
    user = models.ForeignKey(User, related_name = 'reviews') 

forms.py

class ReviewForm(ModelForm): 
    rating = CharField(widget=TextInput(attrs={'type': 'number','value': 5, 'min': 0, 'max': 5})) 

    class Meta: 
     model = Review 
     fields = ['message', 'rating', 'prof', 'course', 'user'] 

我試圖渲染它之前的初始值傳遞到表單。這是我對views.py

def review(request, prof_id=None): 
    """ Review a prof """ 
    # If there's an input prof, return review page for that prof 
    if prof_id: 
     user = User.objects.get(pk=request.user.id) 
     prof = prof_views.prof(prof_id) 
     course = prof.course_set.all() 
     data = {'user': user, 'prof': prof, 'course': course} 
     review_form = ReviewForm(initial=data) 

     return render(request, 'reviews/review_form.html', {'review_form': review_form}) 
    review_form = ReviewForm() 
    return render(request, 'reviews/review_form.html', {'review_form': review_form}) 

profuser成功設置的初始值的代碼。我試圖傳入profcourses,並以表單顯示queryset。但是,Django似乎並不接受它。

我不知道如何編碼此功能。設置profuser的初始值可以工作,因爲它選擇初始值。我確信獲得教授課程的代碼:course = prof.course_set.all()正常工作,我已經在shell中測試過它。所以我需要做的是根據queryset輸入設置表格的課程的值可能的值。

+0

喲意思是「Django似乎不接受它」。您是否期望被渲染爲下拉菜單但它不是? –

votes
answers
41 views
+50

運行時錯誤6069

0

你好傢伙我有爲我打開的循環內聯形狀(doc文件附加的xlsx文件)。它工作正常,但有時我得到一個錯誤:運行時錯誤6069

Run-time error 6069

它會通知我嘗試打開Excel應用程序,也許它沒有安裝(WOW)。

當我調試它突出了一個車道

wddoc.InlineShapes(lShapeCnt).OLEFormat.Activate 

我按下「運行」,它正常工作,就像沒有錯誤。 但這是令人沮喪的,因爲我需要干預和誰將使用此工具的用戶不能這樣做。

votes
answers
53 views
+50

uwsgi失敗的建築輪子

0

我得到一個錯誤,失敗的建築輪子uwsgi。 我的環境是Ubuntu的,現在我想安裝uwsgi,所以我運行命令pip install uwsgi。但錯誤發生uwsgi失敗的建築輪子

Traceback (most recent call last): 
 
    File "<string>", line 1, in <module> 
 
    File "/tmp/pip-build-9t06jm4_/uwsgi/setup.py", line 126, in <module> 
 
     distclass=uWSGIDistribution, 
 
    File "/home/ubuntu/anaconda3/lib/python3.5/distutils/core.py", line 148, in setup 
 
     dist.run_commands() 
 
    File "/home/ubuntu/anaconda3/lib/python3.5/distutils/dist.py", line 955, in run_commands 
 
     self.run_command(cmd) 
 
    File "/home/ubuntu/anaconda3/lib/python3.5/distutils/dist.py", line 974, in run_command 
 
     cmd_obj.run() 
 
    File "/home/ubuntu/anaconda3/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 215, in run 
 
     self.run_command('install') 
 
    File "/home/ubuntu/anaconda3/lib/python3.5/distutils/cmd.py", line 313, in run_command 
 
     self.distribution.run_command(command) 
 
    File "/home/ubuntu/anaconda3/lib/python3.5/distutils/dist.py", line 974, in run_command 
 
     cmd_obj.run() 
 
    File "/tmp/pip-build-9t06jm4_/uwsgi/setup.py", line 77, in run 
 
     conf = uc.uConf(get_profile()) 
 
    File "/tmp/pip-build-9t06jm4_/uwsgi/uwsgiconfig.py", line 742, in __init__ 
 
     raise Exception("you need a C compiler to build uWSGI") 
 
    Exception: you need a C compiler to build uWSGI 
 

 
    ---------------------------------------- 
 
    Failed building wheel for uwsgi 
 
    Running setup.py clean for uwsgi 
 
Failed to build uwsgi 
 
Installing collected packages: uwsgi 
 
    Running setup.py install for uwsgi ... error 
 
    Complete output from command /home/ubuntu/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-9t06jm4_/uwsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('
', '
');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-oxbyg6gk-record/install-record.txt --single-version-externally-managed --compile: 
 
    /home/ubuntu/anaconda3/lib/python3.5/distutils/dist.py:261: UserWarning: Unknown distribution option: 'descriptions' 
 
     warnings.warn(msg) 
 
    running install 
 
    using profile: buildconf/default.ini 
 
    detected include path: ['/usr/include', '/usr/local/include'] 
 
    Traceback (most recent call last): 
 
     File "/tmp/pip-build-9t06jm4_/uwsgi/uwsgiconfig.py", line 734, in __init__ 
 
     gcc_version_components = gcc_version.split('.') 
 
    AttributeError: 'NoneType' object has no attribute 'split' 
 

 
    During handling of the above exception, another exception occurred: 
 

 
    Traceback (most recent call last): 
 
     File "<string>", line 1, in <module> 
 
     File "/tmp/pip-build-9t06jm4_/uwsgi/setup.py", line 126, in <module> 
 
     distclass=uWSGIDistribution, 
 
     File "/home/ubuntu/anaconda3/lib/python3.5/distutils/core.py", line 148, in setup 
 
     dist.run_commands() 
 
     File "/home/ubuntu/anaconda3/lib/python3.5/distutils/dist.py", line 955, in run_commands 
 
     self.run_command(cmd) 
 
     File "/home/ubuntu/anaconda3/lib/python3.5/distutils/dist.py", line 974, in run_command 
 
     cmd_obj.run() 
 
     File "/tmp/pip-build-9t06jm4_/uwsgi/setup.py", line 77, in run 
 
     conf = uc.uConf(get_profile()) 
 
     File "/tmp/pip-build-9t06jm4_/uwsgi/uwsgiconfig.py", line 742, in __init__ 
 
     raise Exception("you need a C compiler to build uWSGI") 
 
    Exception: you need a C compiler to build uWSGI 
 

 
    ---------------------------------------- 
 
Command "/home/ubuntu/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-9t06jm4_/uwsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('
', '
');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-oxbyg6gk-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-9t06jm4_/uwsgi/

我運行命令:sudo apt-get的-y安裝python-dev的,但同錯誤發生。我真的不明白爲什麼會發生這些錯誤。我應該如何解決這個問題?爲什麼我告訴我需要在uWSGI中使用C編譯器?我應該如何解決這個問題?

votes
answers
44 views
+50

獲取列名並對數據表中的值求和c#

0
for (int i = 9; i < dt.Columns.Count; i++) 
{ 
    string dtcolumn = dt.Columns[i].ColumnName.ToString(); 

    dt.Rows[dt.Rows.Count - 1][i] = Convert.ToInt32(dt.Compute("SUM(" + dtcolumn + ")", " " + dtcolumn + " > 0")); 
} 

它在列值不爲空時正在工作。但有時拋出invalidcastexception和顯示對象不能從DBNULL轉換到其他types.how以避免invalidcastexception獲取列名並對數據表中的值求和c#

+0

沒有什麼不對您的代碼,至少無法與已發佈的部分。您需要告訴我們如何重現您的問題。 – CodingYoshi

+0

你可以嘗試'dt.Compute(「SUM(IsNull([」+ dtcolumn +「],0))」'https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression – Slai

votes
answers
48 views
+50

Git Option不再顯示在Android Studio中

1

我錯過了Android Studio - > VCS中的git選項。一會兒,幾分鐘後它就消失了,我不知道爲什麼會發生這種情況。Git Option不再顯示在Android Studio中

你能幫我嗎?

這是我所看到的:

enable version control Integration

和:

Checkout from Version control

votes
answers
21 views
+50

打印浮而不階

0

科學記數法我想浮動轉換爲14位顯著打印浮而不階

val s = "1200000000".toFloat 

輸出-1.2E9

下面我試過,但不起作用

f"$s%1.0f"但這不列入工作與所有值 我想要一個方法,它接受字符串並返回一個浮點數。 該方法可支持多達15位有效數字

+0

不,你還沒有試圖打印它的方式。你能分享你嘗試過什麼嗎? –

+0

已更新問題 – coder25

+0

'f「$ s%1.0f」'_does_適用於所有值。 – Dima

votes
answers
21 views
+50

base64圖像不在圖像中顯示

0

您好我正在使用jquery圖像上載器,其中選擇圖像後,我得到它的base64代碼。base64圖像不在圖像中顯示

function readImage(input) { 
    if (input.files && input.files[0]) { 
     var FR= new FileReader(); 
     FR.onload = function(e) { 
      $('#img').show().attr("src", e.target.result); 
      $('#base').text(e.target.result); 
     }; 
     FR.readAsDataURL(input.files[0]); 
    } 
} 
$("#upload").change(function(){ 
    readImage(this); 
}); 

我正在存儲的base64編碼到我的數據庫和檢索它的另一個頁面上我從我的表得到以下數據

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIABAMAAAAGVsnJAAAAIVBMVEUAAAB fX1 fX1 fX1 fX1 fX1 fX1 fX1 fX1 fX1 fX1I2PRsAAAACnRSTlMAF/ClME Kb9vEsIrXWQAACWpJREFUeNrs3T1rVEEUBuBzs1 JlbGImkpREW6lVrqVhBBCKhESIZWCIqTSgEZSKSrCVordVrrxY/P SouEJG7uzH7k3rBz3vf5CYe9Z87MOTNrIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiMo755fWdty931pfnjU/25EGOI73vby4akWzjPk75 IIlBtlGF4X2OUKw0kXQ/nPzrnEPUTcemWsrOYboef4RZO8wgi9uM0Gri5HsvzKXWh2MqO8yApdzjKz32txZyDGG3jNzZiEHmCPQyjGm3lNzpNHB2PqOSqKsjQns akHtjGR2 bEKib02VyoYWJ3zYF6BxPrP7T0HSYA2jRQAwDij DgAyD CLYBgPgjqOHM7ljKujizfUvYVZTgmyUr66AE/XT3BKsoxSdLVD1HKXqpLoWPUZJblqQGSpPm2cgSSnPTEnSQAYizwBWU6IMl57gGIK0F5lCqr5aaLk4g3BHU8B TeEuSvbXklJH6dJaCQ/XQN6VsI3S7VlCWqhASmMjSzhCuSE4UQVyVoPHRQBpKbCJSvy2VHRQib4looUjnOvAJVTkuqWhjRMIa6EGBrAdjs6iMu8tBVuozB9LQIYKpVAMNlGhFOZnBxdBuoVwMAWwJYEsR4V6058EmhjAlgROpQC2JLCLAkyn4zkq1bMp10IBpi3xHIoQdUnXULFfNt22UISoFOqgGMvBYB1BHE3SGkJIugMzqNw1m2abCCFpj7QRQnI0jHNgU6yBCIaz8SbCKI4E5hBCshtYxDn4adNrE0Ec6 AWwii2Qx2EMWyHMkT57481EENQCDQRQ1AI1BBDsCGeRZz7MYkLOBc/bFqtIc79wfAmYghKwV1E e8PthHl/0yoizj3V hyRLnvEGeIYNgM0Aegjjj33TH6ADQQ5X8/rACgGE0AWhjC 6AUfQCaiPJ/JqYAoJgCwBIA iSoAKAYTQDoK0EFAMVoAkB/HkAfAEMUwahkB1H Z2ToGyP0rbEtxBDMydG3x kHJBYxhPdh4RlE b81NIc49/Py9IOS9KOy9MPS9OPysVqYoRIeNijofkwwVgpSFILDxsXdD4vr4qSuzlqOIPdzoro rwcU9ISGHlEJLgMsi0BoGaBZBPSUlh5To39Or4FTqHKgntQsyIJUOTDQHWLoCgVrQaY6MHQ0znEkrsfV9by /mAh L4 0ev6 pOVgSTAlwKKrg24vyjwj70zeXUiCMJ4jU4UPAUjbifFfU4qLpiTG6i3EHHBkwvicnI/eFJRwdxcEMlJJwpaf6XPjDGTWXq6J/Owa7763QR5PNvpqq qu6umpds/4SkyRMA8gKKEiFcEtQHF/XJTX10VZ/dnecByBygT2/r4 v6/H76BF37z8pVTAwiTAeWSgFMETAPg7ghcNYlBeqJFqlBVBU4YyOeF7ZIGHFjxMJyYMJpbozdJJEwwv4AiE5jfwBEYYT9ARCd50Z4TVIJRqgaYMY2boD3JJg YhWQZj2YE5ZnyEuyh2QTjpaMgGJT4IweL8UhEs8jXoJ9JJLgRvoPY67Nr7QE2CxHDzyKTzaSCeIHC8JazOdwNRO7L3BNPmXyyRsSwYXcWP/9BmbCOsmKCKCXt/HDca0AcJJSPJeSFNZHBeMsnVENBTAoGLuJvdeF/4TPJLss7gEwTV KMLpf0srZ7LgC8Q1Ks1bKsOjVTA6f03NWgIVawvNU0DOUMZuj2v//NBSijjuRaaxvy8g6/j00DR7G3p6cC/plQjahM7bMfwMiMojpia aeFhVy4eH2YJdJ7M/V4hHsM5itvVixBXER3M/V8jMbDA2V3MJnYqPYNfA6uf6uAmGdvV8cHFkiH5Hu/nSUohRttbQ1DAugfmfT eFDI6HIwdPK7j8gXMcuN11cNR SaJhwZNX8Smyyei1F/6ePtUSWklxC1eZ6xqiwnOXrry7NaxO08vnS2LaeFYSr gb/I1aofs4L6UjtE2s7VbcwWCR1J6hlWDAHtrrUBwU0zPZMjc/AoEN8V0zdYxN78CwU05p8j6XM3kJDkR9uV0zteyDZMBOdDpy5mgtm19xUfImjMRF BpUbSNbXlr esGdyWNz7gMQv16SBZsGYsaoDrPLhyvjIXhY1kjdKGr329egvBxJGyI8rR7y t4l0oIHo kjdHWmob9eexJwRoE526N5M3RnuZ6xB fLvzi4ZUTkcRJ6qXGofe/ 7hiBqxYAie vJI6Sr2VPeAluePVMLTgYWovPoD/ AkEY/YC54rA07OR8k5V9tkTJuSG79cFSblg6Bp7ww9ywts7EmTdrrCRPWInWdE EeQmhtqZA50zof8XZ4q4bLPDnjEgCzwwAjLIPWHvVQh0u2zQz1typN2z85y9w0INemKFZRB5zYQnTojjQ4xtLITdimKfzoT/RagU8KoOcquIPL87W8ge8HQHGPYAxg4w7QGAHFC1B9pcCFbuAZQdULoHUHZA6R6A2QHmPSDqgXWf6wHPzEAna9D3d5REvMTkoRdk4Qu1syPo4Au12Q218UYRCiHTYTIQGVgqBnGSYHkibOdQgO2oAFASNCdCb9/PSZDxGo/HlWBZRYgWAnJBAC0EZIMAXAjIBQG0EJANAnghIBME8ELAagaB7SyCb5QCqxBY7XLAazdsTkwLAHkBxZ4AiCFeao7j2IGFxiCeDFpFKRSwGLo0p5VnhP7PGaI1LIYdNKfV47E2D5S2fjasiF UgBoD01EQUAcuaEFEHbioBcHssLwtBlcLZytimL64oUsOMBxmGhcD8wOzviCkEE6JYUQzIGUJ4CaBJA0AJ4F0GsBqCmXbQ6CVwGI10Mr7EuxvVADrimX6Y7hZcJYHAS3xjDWO1hbMNAiBs A0DyJnwb95ELUW/FsPohqCCS wZQDzN2wZMBUCuMXwv4IYsS22Ou0xFgitAKyDpkoIWQcxPyBoHcR8EFsHNauENrBAvtIKiJ3hGd xhWAiBQHnoxYnpWANsT9MsJXwVAvjOoKJK4g5ITenS6DTITMG2KUA8wMCnBNPc10XQBdAY4BmAYD7w8qIu1oLqB8AnQaua2OkQbaxON7TlJY9Lfj/HiFcLywTxg oYXqiViA RI3TufeKhbD/84AURVEURVEURVEURVEURVEURVEURVEURVEURVEURVEURVEURVEURfndHhyQAAAAAAj6/7ofoQIAAAAAAAAAAPwEGcG4SMHdcSkAAAAASUVORK5CYII=" 

現在它要顯示在我的圖像標籤圖像我寫下面的代碼

$('#img').show().attr("src", convert[0].profile_picture); 

我得到的代碼在轉換[0] .profile_picture變量。

但圖像沒有顯示。其中的屏幕截圖是 screenshot of image tag in html

我提到的其他問題,並使用

var data = btoa(convert[0].profile_picture); 
$('#img').show().attr("src", data); 

嘗試,但結果是相同的。在btoa中,我必須刪除數據:image/png; base64,然後嘗試轉換它?我嘗試了一些網上的base64圖像轉換像

i used this link to try and covert base64 to image

但我得到無效的MIME類型:應用程序/八位字節流錯誤。

我在做什麼錯?

更新: - 問題發生在我從數據庫獲取數據並在圖像標記的src屬性中使用它時,而不是在選擇圖像並預覽它之後。

votes
answers
29 views
+50

CakePHP的文件夾內的在線

0

我有一個文件夾內的CakePHP應用程序的在線像這樣:https://www.example.com/mainCakePHP的文件夾內的在線

然而,當我進入那裏,我想我的網址顯示是這樣的:https://www.example.com

我已經嘗試過修改核心.php

Configure::write('App.baseUrl', '/'); 

它顯示我想要的,但返回「在此服務器上找不到請求的URL/info/inicio」。

我知道解決方案只是刪除文件夾「main」並直接加載cakephp應用程序,但目前不可能。

+1

我可以訪問Apache配置一個新的領域,你可以修改' DocumentRoot'指向正確的文件夾。如果沒有,通過'.htaccess'也可以達到類似的結果。 –

votes
answers
72 views
+50

引導3.0的行具有利潤率左15px的利潤率和右15px的

1

引導3.0的行具有利潤率左15px的利潤率和右15px的

<header> 
 
    <div class="container"> 
 
    <div class="row"> 
 
     <div class="col-lg-2 logo"> 
 
     <img src="img/logo.png" alt="Logotype"> 
 
     </div> 
 
     <div class="col-lg-7 col-lg-offset-3"> 
 
     <ul class="menu"> 
 
      <li class="menu-item"><a href="#">Home</a></li> 
 
      <li class="menu-item"><a href="#">About</a></li> 
 
      <li class="menu-item"><a href="#">Expertise</a></li> 
 
      <li class="menu-item"><a href="#">Teams</a></li> 
 
      <li class="menu-item"><a href="#">Works</a></li> 
 
      <li class="menu-item"><a href="#">People say</a></li> 
 
      <li class="menu-item"><a href="#">Contact</a></li> 
 
     </ul> 
 
     </div> 
 
    </div> 
 
    </div> 
 
    <div class="row text-center content-wrapper"> 
 
    <div class="col-lg-12 content-header"> 
 
     <h1 class="title">We Are Awesome Creative Agency</h1> 
 
     <p class="description-header"> 
 
     This is Photoshop's version of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean sollicitudin, lorem<br> quis bibendum auctor, nisi elit consequat ipsum, nec sagittis sem nibh id elit. Duis sed odio sit amet nibh<br> vulputate cursus 
 
     a sit amet mauris. Morbi accumsan ipsum velit. 
 
     </p> 
 
     <div class="button"> 
 
     <a class="content-button">LEARN MORE</a> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</header>

我最近開始學習引導,並面臨着這樣一個問題,爲什麼當我創建一個他有一個保證金左/ right 15px,我的屏幕寬度爲1263px,因爲這些字段好像有水平滾動,1293px字段之後,等等每一個新行,如何解決這個問題?

Just my template

Screenshoot my console

+0

向我們展示你的'HTML'和'CSS'。 '.row'中有'.col'嗎?任何'.container'中的'.row'? –

+0

好吧,我發表了它 –

votes
answers
45 views
+50

點擊按鈕後,通過網站上的信息更新Google表格電子表格

-1

我使用Betfair進行了大量下注,並在Google表格電子表格中追蹤這些信息。點擊按鈕後,通過網站上的信息更新Google表格電子表格

手動爲每個賭注放置信息需要很長時間。

我想知道當我點擊Betfair的「Place Bets」按鈕(參見圖片)時是否有從Betfair網站收集投注信息的方式,並且編寫腳本將此信息添加到我的Google表格電子表格中,即使用硒Webdriver。

我想我問的是,是否有一種方法來調用我自己的腳本在網頁上的特定事件。

任何幫助或指針將不勝感激!

Betfair

+1

您可以爲您的瀏覽器創建擴展程序,併爲其添加功能到Place Bets按鈕。同時解析來自網站的投注信息並將其發佈到您的Google表格。 –

+0

@MarkDavydov我認爲這就是我正在尋找的,有沒有其他的指針可以給我寫一個Chrome擴展說? –

votes
answers
30 views
+50

大教堂含有或compareDocumentPosition模擬在反應

3

我有一個包含像大教堂含有或compareDocumentPosition模擬在反應

<Parent> 
    <Portal> 
     <Child>Lorem Ipsum</Child> 
    </Portal> 
</Parent> 

但在實際DOM另一portaled組件一些部件看起來就像:

<div class="parent"></div> 
<div class="child">Lorem Ipsum</div> 

我需要知道,本地節點Child組件的子項是Parent的子項。

+0

@Chris感謝您的編輯。這是我在stackoverflow上的第一個問題) –

votes
answers
48 views
+50

MongoDB - 時間序列子文檔的範圍查詢

1

我對Mongo非常陌生,剛剛開始討論核心概念......我正在實現時間序列數據模式,並計劃嘗試模式建議在這裏:MongoDB as a Time Series Database,這也出現在一些Mongo的介紹。MongoDB - 時間序列子文檔的範圍查詢

我明白這個模式,但是我很難弄清楚如何在一個日期範圍內查詢它。更具體地說,有人可以舉例說明如何在上面的鏈接中查詢架構以檢索跨越多個小時/天的1分鐘系列?理想情況下,不需要在Mongo之外進行後期處理。

Mongo文檔和聚合管道似乎主要關注處理數組而不是嵌套子文檔...... TIA。

編輯:爲了更清晰添加到我試圖解決特定的問題...

比方說,我在存儲間隔1分鐘的數據,每天一個父文檔,使用下面的架構(從上方連結後剪斷):

{ 
    timestamp_hour: ISODate("2013-10-10T23:00:00.000Z"), 
    type: 「spot_EURUSD」, 
    values: { 
    0: { 0: 1.2343, 1: 1.2343, …, 59: 1.2343}, 
    1: { 0: 1.2343, 1: 1.2343, …, 59: 1.2343}, 
    …, 
    22: { 0: 1.2343, 1: 1.2343, …, 59: 1.2343}, 
    23: { 0: 1.2343, 1: 1.2343, …, 59: 1.2343} 
    } 
} 

什麼是最有效的/高效的方式滿足形式的查詢:「給我值的時間列表,每分鐘1日起對2013- 09-25在下午1點37分,結束於2013-10-15下午2點56分「?

votes
answers
27 views
+50

Objective C: Reading text files

I've done this before, but its not working for me now. I'm doing:

NSString* path = [[NSBundle mainBundle] pathForResource:@"test" 
                                                 ofType:@"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];
NSLog(@"%@",path);

and it returns (null) every time when I NSLog path and content. Can anyone see what I'm doing wrong?

votes
answers
28 views
+50

此代碼的哪一部分提供了用於選擇項目的msg框

-1

我付了一個人來幫助我編寫一個宏來填充電子表格中的表。我覺得我通常可以理解一些編寫的代碼,但這超出了我的想法。我只是想學習如何爲自己做這件事。此代碼的哪一部分提供了用於選擇項目的msg框

Option Explicit 
Option Base 1 
Dim s_no() As String 
Sub createReport() 
start_win.Show 
End Sub 



Sub ook() 


Dim last As Integer 

ReDim s_no(1 To 1) 

If Not Sheet1.Range("A2").Value = "" Then 
    s_no(1) = Sheet1.Range("A2").Value 
Else 
    MsgBox "Empty sheet" 
End If 

last = Cells(Sheet1.Rows.Count, 1).End(xlUp).Row 
Dim i As Integer 
For i = 2 To last 
    If already_exists(Sheet1.Range("A" & CStr(i)).Value) = False Then 
     ReDim Preserve s_no(1 To UBound(s_no) + 1) 
     s_no(UBound(s_no)) = Sheet1.Range("A" & CStr(i)).Value 
    End If 
Next 

For i = 1 To UBound(s_no) 
    Debug.Print s_no(i) 
Next 
End Sub 

Function already_exists(trial) 
already_exists = False 
Dim i As Integer 
For i = 1 To UBound(s_no) 
    If s_no(i) = trial Then 
     already_exists = True 
     Exit Function 
    End If 
Next 
End Function 
+1

只有一個部分打開了一個消息框,在這裏是「MsgBox」Empty sheet「,你可以在你需要幫助的地方添加更多信息嗎? –

+0

你可能需要發佈'start_win'的代碼, – YowE3K

votes
answers
40 views
+50

How to resize a tableHeaderView of a UITableView?

I'm having trouble resizing a tableHeaderView. It simple doesn't work.

1) Create a UITableView and UIView (100 x 320 px);

2) Set the UIView as tableHeaderView of the UITableView;

3) Build and Go. Everything is ok.

Now, I want to resizing the tableHeaderView, so I add this code in viewDidLoad:

self.tableView.autoresizesSubviews = YES;

self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

CGRect newFrame = self.tableView.tableHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
self.tableView.tableHeaderView.frame = newFrame;

The height of the tableHeaderView should appear with 200, but appears with 100.

If I write:

self.tableView.autoresizesSubviews = YES;


CGRect newFrame = myHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
myHeaderView.frame = newFrame;


self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

Then it starts with 200 of height, as I want. But I want to be able to modify it in runtime.

I've also tried this, without success:

self.tableView.autoresizesSubviews = YES;

self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

CGRect newFrame = self.tableView.tableHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
self.tableView.tableHeaderView.frame = newFrame;

[self.tableView.tableHeaderView setNeedsLayout];
[self.tableView.tableHeaderView setNeedsDisplay];
[self.tableView setNeedsLayout];
[self.tableView setNeedsDisplay];

The point here is: How do we resize a tableHeaderView in runtime ???

Have anyone able to do this?

Thanks

iMe

votes
answers
23 views
+50

WPF:Glyph從右到左的文本渲染

3

我想使用Glyph來渲染從右向左的語言文本(例如阿拉伯語或混合英語和阿拉伯語)。WPF:Glyph從右到左的文本渲染

我使用這個代碼:

Typeface typeface = new Typeface(new FontFamily("Arial"), 
         FontStyles.Italic, 
         FontWeights.Normal, 
         FontStretches.Normal); 

     GlyphTypeface glyphTypeface; 
     if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) 
      throw new InvalidOperationException("No glyphtypeface found"); 

     string text = "Hello , ????"; 
     double size = 40; 

     ushort[] glyphIndexes = new ushort[text.Length]; 
     double[] advanceWidths = new double[text.Length]; 

     double totalWidth = 0; 

     for (int n = 0; n < text.Length; n++) 
     { 
      ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]]; 
      glyphIndexes[n] = glyphIndex; 

      double width = glyphTypeface.AdvanceWidths[glyphIndex] * size; 
      advanceWidths[n] = width; 

      totalWidth += width; 
     } 

     Point origin = new Point(50, 50); 

     GlyphRun glyphRun = new GlyphRun(glyphTypeface, 0, false, size, 
      glyphIndexes, origin, advanceWidths, null, null, null, null, 
      null, null); 

     dc.DrawGlyphRun(Brushes.Black, glyphRun); 

但問題是,阿拉伯字符分開表示,像這樣的:

Hello , ? ? ? ? 

請指導我

--- -------------------------------------------------- -

UPDATE:

這是模糊處理解決方案的結果是: image1

的問題是阿拉伯字母分別呈現。

但是,這是我想要的東西: image2

+0

可能不得不分成兩個因爲一個是LRT和o它是RTL – codebender

+0

爲什麼你需要首先使用字形?也許你工作的槓桿太低,而不是利用一些更高級別的工具來呈現文本? WPF控件是否首先呈現文本OK? –

+0

@George,因爲性能需要使用字形(上面的代碼是一個小示例),我發現[這個偉大的Github項目測試所有WPF文本渲染方法](https://github.com/dgrunwald/WPF-Text-Rendering-Benchmark),我意識到雕文是我需要的。 –

votes
answers
48 views
+50

神經網絡的Scilab

0

認識我試着運行這個例子,它採用神經網絡工具箱的Scilab https://burubaxair.wordpress.com/2014/03/12/artificial-neural-networks-in-scilab/神經網絡的Scilab

這是代碼:

T = [ 
1 1 1 1 1 
0 0 1 0 0 
0 0 1 0 0 
0 0 1 0 0 
0 0 1 0 0 
0 0 1 0 0 
0 0 1 0 0 
]'; 
U = [ 
1 0 0 0 1 
1 0 0 0 1 
1 0 0 0 1 
1 0 0 0 1 
1 0 0 0 1 
1 0 0 0 1 
0 1 1 1 0 
]'; 
N = [35 10 2]; 
W = ann_FF_init(N); 
x = [1, 0, 0, 0, 1; 
1, 0, 0, 0, 1; 
1, 0, 0, 0, 1; 
1, 0, 0, 0, 1; 
1, 0, 0, 0, 1; 
1, 0, 0, 0, 1; 
0, 1, 1, 1, 0]'; 
t_t = [1 0]'; 
t_u = [0 1]'; 
t = [t_t, t_u]; 
lp = [0.01, 1e-4]; 
epochs = 3000; 
W = ann_FF_Std_batch(x,t,N,W,lp,epochs); 
y = ann_FF_run(x,N,W) 
disp(y) 

但是我收到一個錯誤:

-->exec('D:УчёбаЗадачиRecognition.sce', -1) 
!--error 15 
Подматрица задана некорректно (Submatrix is incorrect). 
at line  37 of function ann_FF_grad_BP called by : 
at line  25 of function ann_FF_Std_batch called by : 
W = ann_FF_Std_batch(x,t,N,W,lp,epochs); 
at line  33 of exec file called by :  
exec('D:УчёбаЗадачиRecognition.sce', -1) 

一個錯誤可能在T和U矩陣中,但我不明白爲什麼。你能告訴我做錯了什麼嗎?謝謝!

votes
answers
40 views
+50

如何在Android Studio 3.0.1中更改新項目的默認文件結構?

2

我一直在嘗試安裝android studio。所有在線教程都遵循一個非常簡單的過程,只需按照提示安裝和製作一個新項目即可。但是,每當我創建一個新項目時,我的默認文件結構都是不同的。我目前正在使用Android Studio 3.0.1。 如何在Android Studio 3.0.1中更改新項目的默認文件結構?

這就是我想要創建的每當我做一個新的項目。 This is what I want to create whenever I make a new project.

這就是我實際得到的。

This is what I actually get.

特別是某些文件夾丟失,如manifest文件夾,res文件夾,每當我創建一個新項目。

每當我做一個新項目時,我怎樣才能達到理想的結構?

我確定它在技術上並不重要,但我希望能夠密切關注教程,使其更易於學習。我一直在這樣一個令人尷尬的大量時間,包括幾個重新安裝。這發生在我的兩臺機器上,一臺是Windows電腦和一臺Mac電腦。

我試過改變緊湊的空中間包。 這是之前, Before 和之後。 After

謝謝!

+0

您沒有爲項目選擇正確的文件夾,或者您打開了一箇舊項目,所以仍然存在編譯錯誤。 – Ibrahim

+0

這是一個新項目。新項目完成後會立即發生此問題。我的問題是由我的Android Studio中的新項目自動創建的文件夾和文件不正確。另外我不擔心編譯。 – SYSTEM

+0

從齒輪的圖標菜單發佈屏幕截圖。 – Enzokie

votes
answers
6 views
+50

我的索引表沒有排隊

-1

我想打印索引表,就像我在這裏的索引表 但它沒有正確排列。我想我錯過了一個結局; 預先感謝您。他們不會讓我發佈這個問題沒有更多的上下文,所以我打字這看看這是否可能工作。我的索引表沒有排隊

#include <iostream> 
#include <cmath> 
#include <iomanip> 
using namespace std; 

int main() 
{ 


cout << "Wind Chill Table" << endl;   //Produces the table 
cout << "Speed Temperature T " << endl; //Produces the table 
cout << "MPH";        //Produces the table 



for (int temp = 45; temp >= -10; temp -= 5) // Generate temp 45 to -10 
{ 
cout << setw(5)<< temp ; 
} 

cout << endl; 


for (int count = 0; count <= 62; count++) // generate the lines "------" 
{ 
cout << "-" ; 
} 
cout << endl; 

for(int speed = 5; speed <=50; speed+=5) // generate the speed 5 to 50 
{ 
cout << setw(5)<< speed <<"|" << endl; 
for (int temp = 45; temp >=-10; temp -= 5) 
{ 

cout << setw(5)<<windchill(speed,temp);// calling the function windchill 
} 
cout << endl; 
} 

return 0; 
} 




int windchill(int s, int t)// function to calculate the wind chill 
{ 

int windChillFactor = int(round(35.74 + 0.6215 * 
t - 35.75 * pow(s, 0.15) + 
0.4275 * t * pow(s, 0.16))); //Formula for wind chill 

return windChillFactor; 

} 
votes
answers
33 views
+50

如何通過操縱快門按鈕

-1

瞭解iPhone有自動設置定時拍照功能,自動拍攝照片。之後按下快門按鈕啓動。如何通過操縱快門按鈕

我想要做類似的事情。所以如何在相機啓動後以編程方式處理快門按鈕。

- implement: UINavigationControllerDelegate, UIImagePickerControllerDelegate 

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { 

var imagePicker: UIImagePickerController! 


} 

//-- launch the camera 

    @IBAction func takePhoto(_ sender: UIButton) { 

     imagePicker = UIImagePickerController() 
     imagePicker.delegate = self 
     imagePicker.sourceType = .camera 
     present(imagePicker, animated: true, completion: nil) 
    } 

所以,相機推出後,如何通過編程處理的快門按鈕類似點擊它來拍照?

votes
answers
40 views
+50

Python statsmodel魯棒線性迴歸(RLM)異常值選擇

0

我正在分析一組數據,我需要找到它的迴歸。數據集中的數據點數量很少(?15),因此我決定使用強大的線性迴歸作業。問題在於程序選擇了一些看起來不具有影響力的異常點。這裏是數據的散點圖,其影響用作尺寸:X vs Y. The Points B and C are selected as outliers, while point A is not.Python statsmodel魯棒線性迴歸(RLM)異常值選擇

點B和C(圖中用紅色圓圈表示)被選作異常值,而點A具有較高的影響力則不是。雖然A點並沒有改變回歸的總體趨勢,但它基本上定義了斜率與X最高的點一樣。而B點和C點隻影響斜率的顯着性。所以我的問題有兩個部分: 1)如果沒有選擇最具影響力的點,並且您是否知道其他具有我選擇的異常值選項的包,則RLM包的選擇異常值的方法是什麼? 2)你認爲A點是異常點嗎?

votes
answers
46 views
+50

根據兩個條件選擇python數據框中的行

1

基於下面的數據框(1),我希望創建一個數據框(2),其中y或z等於2.是否有方法可以方便地執行此操作?根據兩個條件選擇python數據框中的行

如果我要創建一個僅包含dataframe(1)但不包含dataframe(2)的行的數據框(3),我該如何處理它?

id x y z 
    0 324 1 2 
    1 213 1 1 
    2 529 2 1 
    3 347 3 2 
    4 109 2 2 

...

+0

如果你的問題得到回答,不要忘了[上投票,並接受一個答案(https://開頭stackoverflow.com/help/someone-answers)。謝謝。 –

votes
answers
38 views
+50

如何獲得元素的平面列表屬於使用Java流

3

我試圖讓組件列表屬於項目的特定名單列表中的元素。如何獲得元素的平面列表屬於使用Java流

由於我開始使用流,我無法弄清楚如何做到這一點。

projects.stream() 
     .map(p -> p.getComponents()) 
     .collect(Collectors.toList()); 

由於Project.getComponents()返回Collection<ProjectComponent>以前的代碼將返回List<Collection<ProjectComponent>>但我想回到一個List<ProjectComponent>我該怎麼辦呢?

親切的問候。

votes
answers
49 views
+50

如何使用v-modal從以下腳本發佈lat和lng的值?

-1

這是我的代碼,將標記放在客戶端的google地圖中。我如何能夠捕獲這些值並使用vue js發佈這些值?如何使用v-modal從以下腳本發佈lat和lng的值?

<script> 
function initMap() { 
    var uluru = { 
    lat: -25.363, 
    lng: 131.044 
    }; 
    var mapDiv = document.getElementById('map'); 
    var map = new google.maps.Map(mapDiv, { 
    zoom: 8, 
    center: uluru, 
    clickableIcons: true, 
    }); 

    google.maps.event.addListener(map, 'click', function(e) { 

    if (map.getClickableIcons()) { 
     var Latitude = e.latLng.lat(); 
     var Longitude = e.latLng.lng(); 
     // add your new marker with this info. 
     var marker = new google.maps.Marker({ 
     position: { 
      lat: Latitude, 
      lng: Longitude 
     }, 
     map: map, 
     draggable: true, 
     }); 
     map.clickableIcons = false; 
     // get latitude and longitude after dragging: 
     google.maps.event.addListener(marker, 'dragend', 
     function(marker){ 
      var latLng = marker.latLng; 
      currentLatitude = latLng.lat(); 
      currentLongitude = latLng.lng(); 

}); 


    } 
    }); 
} 
</script> 

<div id="map"></div> 
<!-- Replace the value of the key parameter with your own API key. --> 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCu8vqg35dD4fNfxlI8ICoycehbL0F6bis&callback=initMap"> 
</script> 

我VUE js代碼是

<script> 
submitBox = new Vue({ 
el: "#submitBox", 
    data: { 
    articles: [], 
    services: [], 
    lat : '', 
    lng : '', 
    username: '', 
    category: '', 
    subcategory: [], 

    }, 
methods: { 
    handelSubmit: function(e) { 
      var vm = this; 
      data = {}; 
      data['lat'] = this.lat; 
      data['lng'] = this.lng; 
      data['username'] = this.username; 
      data['category'] = this.category; 
      data['subcategory'] = this.subcategory; 
      $.ajax({ 
       url: 'http://127.0.0.1:8000/api/add/post/', 
       data: data, 
       type: "POST", 
       dataType: 'json', 
       success: function(e) { 
       if (e.status) 
       { 
       alert("Success") 

       window.location.href= "https://localhost/n2s/registersuccess.html"; 
      } 
       else { 
       vm.response = e; 

       alert(" Failed") 
       } 
      } 
      }); 
      return false; 
} 
}, 
}); 
     </script> 

我如何能捕捉緯度和經度值和崗位,重視使用Ajax請求。如果有人請幫助我實現這一目標,那將會很棒。我可以在地圖上放置標記。我需要使用vue js發佈lat和lng值?

+0

你爲什麼不換地圖到Vue的成分,使它您的主要Vue組件的子項,並通過從地圖組件發出事件來公開經緯度數據?或者只是從Vue組件內初始化映射,以便組件可以訪問它。讓Vue組件一起工作,而不是試圖將數據壓入你的Vue組件實例。 –

+0

可以請你展示如何實現相同? – coder

+0

您也可以從問題中移除您的Google地圖API密鑰。 –

votes
answers
39 views
+50

如何啓動另一個活動並在其中啓動一個方法?

-3

只要執行setOnClickListener我想開始另一個活動並將變量cn.getID()傳送給它。當在其他活動中我想immidietaly啓動方法findlocation並給它。如何啓動另一個活動並在其中啓動一個方法?

方法findLocation尚未完成。這個想法是,一旦獲得其他活動按鈕的ID,我可以使用我的數據庫中的sqllite搜索它所屬的位置,獲取經度和緯度,並告知mapcontroller關注這一點的世界地圖。

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.verladestellen); 
    final DB_Verladestellen db = new DB_Verladestellen(this); 
    List<DB_Place> placeList = db.getAllDBPlaces(); 
    final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste); 

    for (final DB_Place cn : placeList) { 

     final LinearLayout row = new LinearLayout(this); 
     row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

     Button place = new Button(this); 
     place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

     place.setText(cn.getName()); 
     place.setId(cn.getID()); 
     row.addView(place); 
     row.setId(cn.getID()); 

     LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams(); 
     params.weight = 1.0f; 
     place.setLayoutParams(params); 

     place.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       //Here I want to call the method to start the other activity 
       //and transmit cn.getID(). 
       openMap(null); 
      } 
     }); 

     layout.addView(row); 
    } 
} 

//The method to start the other activity 
public void openMap(View view) { 
    Intent intent = new Intent(this, UI_MainActivity.class); 
    startActivity(intent); 
} 

這是新的活動我想immidietaly執行裏面的方法,它已開始之後:

public void findLocation(View view){ 
    MapView map = (MapView) findViewById(R.id.map); 
    IMapController mapController = map.getController(); 
    mapController.setZoom(17); 
    GeoPoint myLocation = new GeoPoint(PLACEHOLDER X , PLACEHOLDER Y); 
    mapController.animateTo(myLocation); 
} 

編輯: @Murat K.一些修改後,這是我現在全班同學:

public class UI_Verladestellen extends AppCompatActivity { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.verladestellen); 
    final DB_Verladestellen db = new DB_Verladestellen(this); 
    List<DB_Place> placeList = db.getAllDBPlaces(); 
    final LinearLayout layout = (LinearLayout) findViewById(R.id.verladestellen_liste); 

    for (final DB_Place cn : placeList) { 

     final LinearLayout row = new LinearLayout(this); 
     row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

     Button place = new Button(this); 
     place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

     place.setText(cn.getName()); 
     place.setId(cn.getID()); 
     row.addView(place); 
     row.setId(cn.getID()); 

     LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams(); 
     params.weight = 1.0f; 
     place.setLayoutParams(params); 

     place.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       openMap(cn.getID()); 
      } 
     }); 

     layout.addView(row); 
    } 
} 

public void openMap(int view) { 
    Intent intent = new Intent(UI_Verladestellen.this, UI_MainActivity.class); 
    intent.putExtra("findLocation", 1); 
    startActivity(intent); 
} 

}

這是我的onCreate的getIntent方法在UI_MainActivity:

int i = getIntent().getIntExtra("findlocation", 999); 
    if(i == 1){ 
     findLocation(i); 
    } 

當我編輯到我以前的評論,我不能看到我的按鈕ID收到的地方。起初我以爲我會是我的ID,但那不起作用,因爲按鈕ID可以是從1到n的每個數字。

+0

在你的'openMap()'方法中,你沒有把任何東西放入Intent中。您必須完全按照原樣使用我的答案。 –

+0

@MuratK。我以爲我的確很好地回答了你的答案。也許我誤解了你。那麼你能告訴我我錯過了什麼嗎?對不起,我不是很有經驗。 – Glave

votes
answers
50 views
+50

C++進程啓動問題,路徑爲

0

我使用process::start(PATH);來打開進程。問題是,有時它會找到該文件,有時它不會。C++進程啓動問題,路徑爲

例如,這個工程:

process::start("C:	ext.exe"); 

但是,這並不工作:

process::start("C:New Folder	ext.exe"); 

任何想法有什麼區別?

+1

凡定義'process'? – 2010-08-09 01:42:21

votes
answers
27 views
+50

pyfilesystem2,FSTestCases:測試文件系統

0

我已經使用pyfilesystem2實現了一個文件系統,現在我想測試它。我有我自己的單元測試用例,但pyfilesystem2提供了自己的測試用例,我很樂意運行,但是...我不知道如何。該文檔僅說明如何創建測試人員類,但不說明如何調用測試 - see for yourself。 help()函數也沒有幫助 - 在那裏幾乎沒有文檔。pyfilesystem2,FSTestCases:測試文件系統

好的,但有一個可用的方法列表,對吧?是啊,我試圖創建一個測試對象,然後調用其test_basic()方法,但它失敗,因爲一些內部錯誤......

(env) [email protected]:~/code/filesyst$ python3 dropboxfs.py 
Traceback (most recent call last): 
    File "dropboxfs.py", line 630, in <module> 
    t.test_basic() 
    File "/mnt/d/code/filesyst/env/lib/python3.4/site-packages/fs/test.py", line 349, in test_basic 
    repr(self.fs) 
AttributeError: 'TestDropBoxFS' object has no attribute 'fs' 
(env) [email protected]:~/code/filesyst$ python3 dropboxfs.py 
Traceback (most recent call last): 
    File "dropboxfs.py", line 629, in <module> 
    t.test_basic() 
    File "/mnt/d/code/filesyst/env/lib/python3.4/site-packages/fs/test.py", line 349, in test_basic 
    repr(self.fs) 
AttributeError: 'TestDropBoxFS' object has no attribute 'fs' 

(我知道有對DropBox的一個實現,它只是一個鍛鍊; Tibial我)。

谷歌搜索並沒有幫助,因爲一切都指向回pyfilesystem2文檔,這是缺乏...

任何人可以給我一個提示做什麼?我如何運行這些測試用例?

PS。從C/C++語言到Python在文檔方面令人沮喪。可能我只是不明白範例,但它看起來缺乏很多。

votes
answers
22 views
+50

graphviz三個行列布局與子圖

1

我試圖將元素定位在自動生成的流程圖的形式。 一般而言,inputs(綠色)應該在最左邊,outputs(紅色)在最右邊,其餘的應按照佈局放置在中間。 我爲此使用rank=sourcerank=sink。 在標準圖形中,它很好地工作。graphviz三個行列布局與子圖

但是,當我開始嵌套圖形時,rank=source似乎不起作用。我期望<>(電,開關,房間溫度)的三個輸入被放置在最左邊(因爲它在子圖內發生)以及子圖+狀態(棕色圓圈)和輸入和輸出之間的藍色框。

有沒有指定「等級=中心」(或類似的東西?)

我已經通過了documentation,但沒有找到正確的屬性(並在指定他們)的方式。

MWE

digraph MyGraph { 
    node [fontsize=8 margin=".1,.01" width=.5 height=.5 shape=box] 
    edge [fontsize=8] 
    rankdir=LR; 
    ranksep = .25; 
    nodesep= .5; 

subgraph cluster_4386357488 { 
    label = " <<GrowLamp>>" 
    style=solid 
    {rank=source; 
     4386357544 [label="electricity" style=filled fillcolor="#b5fed9"] 
     4386357712 [label="room_temperature" style=filled fillcolor="#b5fed9"] 
     4386357768 [label="switch" style=filled fillcolor="#b5fed9"] 
    } 
    { 
     4386357880 [label="off" style=filled fillcolor="#e2cbc1" shape=doublecircle] 
     4386357936 [label="on" style=filled fillcolor="#e2cbc1" shape=circle] 
     4386357656 [label="on_time" style=filled fillcolor="#d2ceef"] 
    } 
    {rank=sink; 
     4386357600 [label="light" style=filled fillcolor="#fcc5b3"] 
     4386357824 [label="temperature" style=filled fillcolor="#fcc5b3"] 
    } 
    4386357880 -> 4386357936 
    4386357936 -> 4386357880 
    { 
     subgraph cluster_4386357992 { 
      label = "<<Adder>>" 
      style=dashed 
      {rank=source; 
       4386358048 [label="heat_in" style=filled fillcolor="#b5fed9"] 
       4386358104 [label="room_temp_in" style=filled fillcolor="#b5fed9"] 
      } 
      { 
       4386358216 [label="state" style=filled fillcolor="#e2cbc1" shape=doublecircle] 
      } 
      {rank=sink; 
       4386358160 [label="temperature" style=filled fillcolor="#fcc5b3"] 
      } 
      4386358216 -> 4386358160 [style="dashed"] 
     } 


     subgraph cluster_4386358328 { 
      label = "<<HeatElement>>" 
      style=solid 
      {rank=source; 
       4386358384 [label="electricity" style=filled fillcolor="#b5fed9"] 
      } 
      { 
       4386358496 [label="on" style=filled fillcolor="#e2cbc1" shape=doublecircle] 
      } 
      {rank=sink; 
       4386358440 [label="heat" style=filled fillcolor="#fcc5b3"] 
      } 
      4386358496 -> 4386358440 [style="dashed"] 
     } 


     subgraph cluster_4386358608 { 
      label = "<<LightElement>>" 
      style=solid 
      {rank=source; 
       4386358664 [label="electricity" style=filled fillcolor="#b5fed9"] 
      } 
      { 
       4386358776 [label="off" style=filled fillcolor="#e2cbc1" shape=doublecircle] 
       4386358832 [label="on" style=filled fillcolor="#e2cbc1" shape=circle] 
      } 
      {rank=sink; 
       4386358720 [label="light" style=filled fillcolor="#fcc5b3"] 
      } 
      4386358776 -> 4386358832 
      4386358832 -> 4386358776 
      4386358776 -> 4386358720 [style="dashed"] 
      4386358832 -> 4386358720 [style="dashed"] 
     } 

     4386358160 -> 4386357824 
     4386357712 -> 4386358104 
     4386358440 -> 4386358048 
     4386358720 -> 4386357600 
     4386357936 -> 4386358384 [style="dashed"] 
     4386357936 -> 4386358664 [style="dashed"] 
     4386357936 -> 4386357656 [style="dashed"] 
    } 

} 

有希望的解決方案: 這裏是我想和落得什麼。請注意,綠框在各自子圖的左側如何,紅框在右側。在這之間應該有其他的元素,由graphviz定位。

How it should look like

+0

沒有一個排名=中心,但也有其他方法來獲得節點對準你會的方式喜歡。我有一個關於如何幫助你的想法,但我對於希望的安排很不清楚。你想要左邊的所有綠色框,中間的棕色圓圈和右邊的橙色框?或者你只是以這種方式wan some他們?你可以添加一個你想要的元素排列的粗略草圖嗎? – Craig

+0

我添加了一個圖像來解釋我想要的。在每個盒子裏,綠色框(輸入)應該在左邊,紅色框(輸出)在右邊,其餘的在中心(如'dot'看起來合適)。因此,應該有一種從左到右的「流動」。 – stklik

votes
answers
50 views
+50

Drupal的8次模板:把當前頁碼

1

我試圖得到一個觀點樹枝模板文件「意見 - 視圖 - 格式化 - 分類 - page_1.html.twig」裏面的尋呼機當前頁碼Drupal的8次模板:把當前頁碼

在Drupal 7的我已經設法通過得到尋呼機的當前頁面:$視圖 - >查詢 - > pager-> CURRENT_PAGE

這是exacly什麼,我需要得到的,但我無法弄清楚如何做到這一點在Drupal 8中。我試過{{dump()}}來查看模板內可用的變量,但最終以白色屏幕結束。

任何幫助,將不勝感激。

votes
answers
36 views
+50

iOS 11.2 NFC-Tag隨機UID

-1

使用iOS 11.2我無法從標籤中讀取真正的uid。我可以從「NFCNDEFReaderSession」讀取一個ID,但是這個ID在每次掃描時都會改變。iOS 11.2 NFC-Tag隨機UID

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) { 

    var uid: String = "" 
    if(session.value(forKey: "_foundTags") != nil) { 

     let foundTags : NSArray = session.value(forKey: "_foundTags") as! NSArray 
     if(foundTags.count > 0) { 

      let tag : NSObject = foundTags.firstObject as! NSObject; 
      if(tag.value(forKey: "_UID") != nil) { 

我需要從NFC標籤的真正的UID。有人想法從一個nfc標籤獲得uid。使用iOS 11.0可以閱讀這些信息。

+1

我不相信你可以。你只能得到NDEF數據。 – Paulw11

votes
answers
36 views
+50

提取3D(time,lat,lon)數組中的每個值並創建一個列表或一維數組

0

請原諒我,如果這很簡單,但我是python的新手。我每天都有一個數據點,每個緯度(180度)和經度(360度)和時間(6624)是一個三維數組,具有numpy.shape(時間,緯度,經度)。我試圖提取每一個風速並將其放入一個新的數組或列表中,以便我可以繪製直方圖或概率密度函數。有沒有在Python中提取每個這些值的方法?提取3D(time,lat,lon)數組中的每個值並創建一個列表或一維數組

+0

你的意思是你需要每一行矩陣與拉特,長和時間來生成函數? – skrubber

+0

是的,對於每個經緯度單元,有6624天的風速數據,其中一個值是單個值,並且該點能夠查看特定單元格並提取6624個風速來創建直方圖。感謝您提供的任何見解。 – laff

+0

提供了幾行3D數組,因爲切片將根據數組的形狀而變化 – skrubber

votes
answers
31 views
+50

如何在Java中合併兩個字符串集合,但前提是它們具有相同的元素?

-1

我是新來的Java和我試圖(和 - apparently-失敗),如果他們有共同的要素兩個字符串組結合:如何在Java中合併兩個字符串集合,但前提是它們具有相同的元素?

CommonElements = Set1; 
CommonElements.retainAll(Set2); 
System.out.println("common elements of"+Set1+"and"+Set2+":"+CommonElements); 
if (CommonElements.size()!=0) { 
    Set1.addAll(Set2); 
    System.out.println("both sets"+Set1); 
} 

現在,我正在申請同樣的事情,雖然我現在有套一個ArrayList:

for (i=0; i<myList.size(); i++) { 
    for (int j = 1; j<myList.size()-i; j++) { 
     Set<String> Set1 = myList.get(i); 
     System.out.println("Set1"+Set1); 
     Set<String> Set2 = myList.get(i+j); 
     System.out.println("Set2"+Set2); 
     Set<String> commonElements = myList.get(i); 
     commonElements.retainAll(Set2); 
     System.out.println("Common elements of"+i+"and"+(i+j)+":"+Set3); 
     if (commonElements.size()!=0) { 
      Set1.addAll(Set2); 
      myList.set(i, Set1); 
      System.out.println("both sets"+Set1); 
     } 
     System.out.println(myList.get(i)); 

不過的System.out.println(myList.get(I))結果:

如果這兩組沒有什麼共同點: SET1變空, myList.get(i)返回[]。

如果兩組確實有共同之處: Set1變爲Set2,所以列表條目編號i取列表條目編號i + j的值。

+0

這是因爲'retainAll'你'myList.get調用(我)'修改的列表。除非你告訴它,否則你認識到'Object'的變量賦值不會複製? – bcsb1001

+0

@Dichard:我想要一個工會,但我首先要檢查是否有交叉點,因爲我不想要交叉點(兩個集合加在一起)或交叉點(只存在於兩個元素中) – Richard

+0

@ Richard:如果它們沒有至少一個共同的元素,則要合併這些集合。 – Wiesel

votes
answers
22 views
+50

如何通過使用django-hitcount計算的流行度來返回對象

0

我在我的應用程序中擁有itens,我想通過「流行度」返回它。這種受歡迎程度意味着該項目的觀看次數。 我使用django-hitcount來做到這一點。我看到了here我如何獲得每個對象的命中數。但是我不想將所有的Item對象加載到內存中來完成我想要的操作,因爲這是不必要的重載。 我想返回N個最受歡迎的itens傳遞給視圖和每個項目的訪問號碼。如何通過使用django-hitcount計算的流行度來返回對象

我的項目模型爲波紋管

class Item(models.Model, HitCountMixin): 
    nome = models.CharField(max_length=255, unique=True) 
    slug = models.SlugField(max_length=255, null=True) 
    imagem = models.ImageField(upload_to='itens/item/', null=True, blank=True) 
    descricao = RichTextUploadingField(null=True, blank=True) 
    categoria = models.ForeignKey(Categoria) 
    hit_count_generic = GenericRelation(
     HitCount, object_id_field='object_pk', 
     related_query_name='hit_count_generic_relation') 

    def __str__(self): 
     return '{}'.format(self.nome) 

    def get_absolute_url(self): 
     from django.urls import reverse 
     return reverse('itens:detail_item', args=[str(self.slug)]) 

起初,我認爲我是想用這個功能

def get_most_popular_itens(amount): 
    return Item.objects.order_by('-hit_count.hits')[:amount] 

得到最流行的itens但沒有奏效。我無法理解這種內容類型/通用關係是如何工作的。 因此,我看到了數據庫表是如何被管理並做功能的(見下文)。 但它有一個問題。返回的查詢集不按視圖數量排序,我無權訪問此數字。 更重要的是,在我看來,我的解決方案至少是不好的。 因此,我想知道如何改進這一點,或許從通用關係中獲得一些優勢?

def get_most_popular_itens(amount): 
    ct = ContentType.objects.get_for_model(Item) 
    hit_counts = HitCount.objects.filter(content_type_id=ct.id).order_by('-hits')[:amount] 
    items = [] 
    for hit in hit_counts: 
     items.append(hit.object_pk) 
    return Item.objects.filter(id__in=items) 
votes
answers
27 views
+50

pyfilesystem2,FSTestCases:測試文件系統

0

我已經使用pyfilesystem2實現了一個文件系統,現在我想測試它。我有我自己的單元測試用例,但pyfilesystem2提供了自己的測試用例,我很樂意運行,但是...我不知道如何。該文檔僅說明如何創建測試人員類,但不說明如何調用測試 - see for yourself。 help()函數也沒有幫助 - 在那裏幾乎沒有文檔。pyfilesystem2,FSTestCases:測試文件系統

好的,但有一個可用的方法列表,對吧?是啊,我試圖創建一個測試對象,然後調用其test_basic()方法,但它失敗,因爲一些內部錯誤......

(env) [email protected]:~/code/filesyst$ python3 dropboxfs.py 
Traceback (most recent call last): 
    File "dropboxfs.py", line 630, in <module> 
    t.test_basic() 
    File "/mnt/d/code/filesyst/env/lib/python3.4/site-packages/fs/test.py", line 349, in test_basic 
    repr(self.fs) 
AttributeError: 'TestDropBoxFS' object has no attribute 'fs' 
(env) [email protected]:~/code/filesyst$ python3 dropboxfs.py 
Traceback (most recent call last): 
    File "dropboxfs.py", line 629, in <module> 
    t.test_basic() 
    File "/mnt/d/code/filesyst/env/lib/python3.4/site-packages/fs/test.py", line 349, in test_basic 
    repr(self.fs) 
AttributeError: 'TestDropBoxFS' object has no attribute 'fs' 

(我知道有對DropBox的一個實現,它只是一個鍛鍊; Tibial我)。

谷歌搜索並沒有幫助,因爲一切都指向回pyfilesystem2文檔,這是缺乏...

任何人可以給我一個提示做什麼?我如何運行這些測試用例?

PS。從C/C++語言到Python在文檔方面令人沮喪。可能我只是不明白範例,但它看起來缺乏很多。

votes
answers
24 views
+50

Django - Modelform not rendering

0

我創建了一個表單來更新用戶的配置文件,但是當我運行它時,沒有任何錯誤,但是當我嘗試打開頁面時,表頭出現,但沒有出現UpdateBioForm。其次,我想知道如何創建一個大型文本框來存儲某人的傳記。Django - Modelform not rendering

Models.py

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    biography = models.CharField(max_length = 255, default = '') 
    city = models.CharField(max_length=100, default = '') 
    website = models.URLField(default='') 
    image = models.ImageField(upload_to='profile_image', blank=True) 

    def setdefault(self, default_path='/profile_image/Default.jpg'): 
     if self.image: 
      return self.image 
     return default_path 

    def __str__(self): 
     return self.user.username 

Forms.Py

class UpdateBioForm(forms.ModelForm): 

    class Meta: 
     model = UserProfile 
     fields = (
      'biography', 
      'city', 
      'website' 
     ) 

    def save(self, commit=True): 
     savedBio = super(UpdateBioForm, self).save(commit=False) 
     savedBio.biography = self.cleaned_data['biography'] 
     savedBio.city = self.cleaned_data['city'] 
     savedBio.website = self.cleaned_data['website'] 

     if commit: 
      savedBio.save() 

     return savedBio 

Views.py

def update_bio(request): 
    if request.method == 'POST': 
     form = UpdateBioForm(request.POST, instance=request.user) 

     if form.is_valid(): 
      form.save() 
      return redirect('/') 
    else: 
     form = UpdateBioForm(instance=request.user) 
    args = {'form':form} 
    return render(request, 'accounts/update_bio.html') 

urls.py

url(r'^profile/updatebio/$',views.update_bio, name='update_bio'), 

update_bio.html

{% extends 'base.html' %} 

{% block body %} 
<div class="container"> 
    <h1>Update Biography</h1> 
    <form method="post"> 
     {% csrf_token %} 
     {{ form.as_p }} 
     <button type="submit">Submit</button> 
    </form> 
</div> 
{% endblock %} 
+0

無關,但爲什麼要覆蓋表單的save()方法? –

votes
answers
32 views
+50

嵌套在while循環中的ArrayList中的重置值

1

我編寫了代碼來存儲用戶輸入的美元金額的值。只要程序提示用戶,「你想輸入項目 - y/n?」然後用戶可以輸入存儲在ArrayList中的值。嵌套在while循環中的ArrayList中的重置值

初始提示如下。它似乎工作,因爲我可以把值沒有明顯的錯誤。

System.out.print("Would you like to input item/s - y/n: "); 
    String response = textReader.nextLine(); 
    System.out.println(); 
    // create while loop to restrict responses to single characters 
    while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n"))) 
    { 
     System.out.print("Sorry - we need a y/n: "); 
     response = textReader.nextLine(); 
     System.out.println(); 
    } 

但是,當我去放值的第二次,我注意到程序不會從我的第一個條目清除出值。我編寫的用於提示用戶輸入另一組值的代碼與我爲初始提示編寫的代碼相同。我在由用戶選擇「y」觸發的一個while循環中嵌套第二個提示。

while ((response.equalsIgnoreCase("y"))) 
    { 
     System.out.print("Please enter an item price, or -1 to exit: $"); 
     double values = numberReader.nextDouble(); 
     while ((values > (-1))) 
     { 
      cartItems.add(values); 
      System.out.print("Please enter another item price, or -1 to exit: $"); 
      values = numberReader.nextDouble(); 
     } 
     System.out.println(); 
     System.out.println("********** Here are your items **********"); 

     // I omitted the code here to make this more concise. 

     // prompt the user to input a second round of values 
     System.out.print("Would you like to input item/s - y/n: "); 
     response = textReader.nextLine(); 
     System.out.println(); 
     // create while loop to restrict responses to single characters 
     while ((!response.equalsIgnoreCase("y")) && (!response.equalsIgnoreCase("n"))) 
     { 
      System.out.print("Sorry - we need a y/n: "); 
      response = textReader.nextLine(); 
      System.out.println(); 
     } 
    } 

我的輸出結果如下。當我再次收到提示時,我選擇'y'添加更多項目。但是,我新添加的項目$ 3.00會從第一個提示中添加到列表中。無論如何刷新或擦除ArrayList,以便每當用戶想要輸入新值時它是全新的? My output

votes
answers
25 views
+50

打字稿編譯器是否有@inline功能選項?

0
//ts code 
function div(props?: { id?: String; style?: any }) { 
     return function(...children: ReactNode[]) { 
     return createElement("div", props, ...children); 
     }; 
    } 
const d = div({ id: "hello" })("welcome to TS"); 

生成的JS代碼打字稿編譯器是否有@inline功能選項?

function div(props) { 
    return function() { 
     var children = []; 
     for (var _i = 0; _i < arguments.length; _i++) { 
      children[_i] = arguments[_i]; 
     } 
     return createElement("div",props,...); 
    }; 
} 
var d = div({ id: "hello" })("welcome to TS"); 

//努力實現

var d = createElement("div",{ id: "hello" },"welcome to TS") 

確實打字稿支持@inline的功能呢?如果不是最好的方式實現類似的..

+2

不,在打字稿內聯函數的支持,你應該相信JS運行時做了優化,或手編代碼你想要的方式。 –

+1

要添加到以前的評論,請閱讀[「JavaScript引擎中的自動內聯」](https://ariya.io/2013/04/automatic-inlining-in-javascript-engines)---如果您的代碼是如果您希望手動優化這些細節,您應該查看WASM(WebAssembly),這正是它的一個用例([Youtube:Dan Callahan:實用WebAssembly | JSConf布達佩斯2017年](https://www.youtube。 com/watch?v = bac0dGQbUto) - 跳過第15分鐘)。 –

+0

感謝您的信息:) – invariant

votes
answers
37 views
+50

如何在Laravel中禁用SMTP身份驗證

-1

如何在Laravel 5.2中發送電子郵件時禁用SMTP身份驗證?如何在Laravel中禁用SMTP身份驗證

PHPMailer

,有禁用SMTP驗證參數:

$ MAIL-> SMTPAUTH = FALSE;

我似乎無法找到在Laravel中禁用的選項。任何人有任何想法?由於我的郵件服務器不支持SMTP認證。

votes
answers
32 views
+50

Grunt watch error - Waiting…Fatal error: watch ENOSPC

Why do I get the Waiting...Fatal error: watch ENOSPC when I run the watch task ? How do I solve this issue?

votes
answers
41 views
+50

bash根據config.ini文件中默認變量的值使用源讀取變量

0

我想讀取我的配置文件並獲取默認打印機的值。所以在這個例子中,我期望返回結果Zebra_GK420Dbash根據config.ini文件中默認變量的值使用源讀取變量

我的config.ini文件,如下所示:

enable_printing=yes 
default_printer=printer1 
printer1=Zebra_GK420D 
printer2=DYMO_LabelWriter_4XL 
create_proof=yes 

我使用以下bash腳本:

1 #!/usr/bin/env bash 
    2 
    3 #Define filename 
    4 fConfig=config.ini 
    5 
    6 #If file exists, read in variables. 
    7 if test -f $fConfig ; then 
    8   source $fConfig 
    9 fi 
10 
11 echo The default_printer is: ${default_printer%?} 
12 
13 echo The name of the default_printer is: $(${default_printer%?}) 

當我運行該腳本,它返回:

The default_printer is: printer1 
./test.sh: line 13: printer1: command not found 

如何我可以修復我的bash腳本,以便它返回以下內容:

The default_printer is: printer1 
The name of the default_printer is: Zebra_GK420D 

請注意,由於config.ini文件託管在Windows驅動器上,因此每行最後會返回 ,所以我使用%?刪除每行的最後一個字符。這裏的危險在於文件中的最後一行最後沒有 。我可以使用什麼來代替%?來只刪除 而不是盲目刪除最後一個字符?

謝謝。

+1

如果你修改你的配置文件,以便它不使用DOS行尾,你可以使用間接參數擴展:'$ {!default_printer}'。 (沒有修復它,只需要兩行'tmp = $ {default_printer%?}; echo $ {!tmp}'。) – chepner

+1

您可以指定要移除的確切字符:'$ {default_printer%$' r'} '。但是,我強烈建議只修復該文件,而不要讓消費者處理回車。 – chepner

+1

你可以嘗試進程替換過濾掉源文件中的回車:'source <(tr -d' r'<$ fConfig)' –

votes
answers
25 views
+50

trying to animate a constraint in swift

I have an UITextField that I want to enlarge it's width when tapped on. I set up the constraints and made sure the constraint on the left has the lower priority then the one that I am trying to animate on the right side.

Here is the code that I am trying to use.

  // move the input box
    UIView.animateWithDuration(10.5, animations: {
        self.nameInputConstraint.constant = 8
        }, completion: {
            (value: Bool) in
            println(">>> move const")
    })

This works, but it seems to just happen instantly and there doesn't seem to be any movement. I tried to set it 10 seconds to make sure I wasn't missing anything, but I got the same results.

nameInputConstraint is the name of the constraint that I control dragged to connect into my class from IB.

Thanks for your help in advance!

votes
answers
33 views
+50

選擇/行突出緊鄰的小區後功能已經在谷歌腳本執行

1

我不是真的編碼,所以我提前道歉,如果這是帶有明顯的答案一個愚蠢的問題,經歷過......選擇/行突出緊鄰的小區後功能已經在谷歌腳本執行

我用一張谷歌表來跟蹤工作中的事情,我的員工每天多次使用它。他們會將三個短語中的一個鍵入到一行中的某個單元格中,所以我使用繪圖功能創建了按鈕,只需單擊它們即可將相應的文本插入到突出顯示的單元格中。

一旦這個文本被插入到單元格中,我想添加一些東西到自動選擇行中的下一個相鄰的單元格(在右邊),以便他們可以繼續輸入。目前,一次他們點擊按鈕將文本插入到一個單元格中(例如B23),他們必須先使用鼠標手動選擇C23,然後再鍵入該單元格。出於某種原因,您不能使用鍵盤上的右箭頭鍵或Tab鍵移動,所以我想知道是否有方法將選擇過程添加到腳本中(甚至是用於允許選項卡或右箭頭鍵的解決方法上班)。

我意識到這可能看起來像一個單調乏味的問題,人們可能會認爲我非常懶惰地要求轉移到單元格比使用鼠標更有效的方式,但我的員工使用表單數百次一天,所以我真的想盡量提高他們的效率,儘可能方便和方便。輸入數據可能非常繁瑣,所以我試圖簡化一些東西,並儘可能減少痛苦:)

非常感謝!

votes
answers
29 views
+50

How is “int main(){(([](){})());}” valid C++?

I recently came across the following esoteric piece of code.

int main(){(([](){})());}

Reformat it as follows to make it more readable:

int main(){
    (([](){})());   //  Um... what?!?!
}

But I can't get my head around how (([](){})()) is valid code.

  • It doesn't look like function pointer syntax.
  • It can't be some operator overloading trick. The code compiles as is.

Google didn't help much with this all-symbol search. But it compiles in Visual Studio 2010 and outputs nothing. There were no errors, and no warnings. So it looks like valid code.

I've never seen any valid code that is so bizarre outside of Javascript and C function pointers.

Can someone explain how this is valid C++?

votes
answers
38 views
+50

功能的雙電源沒有math.h中

0

我想知道如何使雙打對權力的功能,而不math.h中功能的雙電源沒有math.h中

例如,如果我想

4.3^2.5 
+0

定義你自己的函數來尋找雙倍的力量。找出預定義的pow()如何工作和分析。 – achal

+2

我相信有幾個算法可以做到這一點。你有什麼嘗試?你的嘗試是如何工作的?還是不行?也許你應該花一些時間[閱讀如何提出好問題](http://stackoverflow.com/help/how-to-ask),並學習如何創建[最小,完整和可驗證示例](http ://stackoverflow.com/help/mcve)?也許你需要[學習如何調試你的程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)? –

+1

[浮點實現pow()函數的最有效方式]的可能重複(https://stackoverflow.com/questions/2664445/the-most-efficient-way-of-implementing-pow-function-in-浮點數) – OznOg

votes
answers
70 views
+50

使用iOS在WKWebView中自動播放YouTube視頻11

1

我想在我的應用中使用小型YouTube播放器。我發現推薦的唯一方法是將帶有YouTube播放器的網頁嵌入到我的應用程序中。所以我用WKWebView並加載嵌入YouTube播放器頁面自動播放參數:https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1使用iOS在WKWebView中自動播放YouTube視頻11

代碼將是這樣的:在桌面Safari瀏覽器

let webConfiguration = WKWebViewConfiguration() 
let webView = WKWebView(frame: .zero, configuration: webConfiguration) 
let youtubeURL = URL(string: "https://www.youtube.com/embed/VUbsFtLkGN8?autoplay=1") 
webView.load(URLRequest(url: youtubeURL!)) 

這個嵌入播放器自動播放的網址,但在移動Safari或WKWebView不會自動播放。我可以強制WKWebView以某種方式自動播放視頻嗎?或者使用其他YouTube播放器網址?

+0

並不在視頻的蘋果阻止自動播放? –

+0

是的,在Safari中,但我認爲你應該可以在你的應用中自動播放。 – Ondra

votes
answers
28 views
+50

Insert line break in postgresql when updating text field

I am trying to update a text field in a table of my postgresql database.

UPDATE public.table SET long_text = 'First Line' + CHAR(10) + 'Second line.' WHERE id = 19;

My intended result is that the cell will look like this:

First Line
Second line

The above syntax returns an error.

votes
answers
28 views
+50

實現算法來計算R中的R

1

我試圖在R中實現Brent-Salamin algorithm的變體。它在前25次迭代中運行良好,但後來出乎意料地返回負結果。實現算法來計算R中的R

算法我想要實現的是:

initial values: 
x_0 = 1; y_0 = 1/sqrt(2); z_0 = 1/2 

x_n = (x_n-1 + y_n-1)/2 
y_n = sqrt(x_n-1 * y_n-1) 
z_n = z_n-1 - 2^n * (x_n^2-y_n^2) 

p_n = (2 * x_n^2)/z_n 

其中n是當前迭代。

一個更漂亮的格式化公式是here

我想通了的代碼是:

mypi <- function(n){ 

    x = 1 
    y = 1/sqrt(2) 
    z = 1/2 
    iteration = 0 

    while(iteration < n){ 
    iteration = iteration + 1 

    newx = (x + y)/2 
    y = sqrt(x * y) 
    x = newx 
    z = z-(2^iteration * (x^2 - y^2)) 
    p = (2 * x^2)/z 
    } 

    return(p) 
} 

輸出:

> mypi(10) 
[1] 3.141593 
> mypi(20) 
[1] 3.141593 
> mypi(50) 
[1] -33.34323 

所以,我是新來的R,有沒有在我的代碼中的錯誤或者是它的算法?

+0

哪裏'i'從何而來? – AdamO

+0

@AdamO它應該是'iteration',而不是'i' –

+1

在玩了大約20分鐘的代碼之後,我沒有確切的答案,而且我不確定是否有解釋可能是由於浮點運算的侷限性。在我開始看到負數之前,我已經完成了將近50次的迭代。我認爲經過這麼多迭代之後,'z'中的'2 ^迭代'項變得如此之大,並且'x^2 - y^2'項變得如此之小,以至於四捨五入等開始起作用。你看到的負數只是一個神器。 –

votes
answers
34 views
+50

代碼沒有檢測到來自用戶的空輸入

0

我有刪除按鈕的問題。當我在文本字段中輸入任何內容並按下刪除按鈕時,我沒有收到彈出式菜單作爲例外。代碼沒有檢測到來自用戶的空輸入

private void billdeleteActionPerformed(java.awt.event.ActionEvent evt) { 
    // TODO add your handling code here: 
    try{ 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     int id=Integer.parseInt(billidtext.getText()); 
     try (//step2 create the connection object 
      Connection con = DriverManager.getConnection("jdbc:oracle:thin:localhost:xe","hr","****")) { 
      Statement stmt=con.createStatement(); 
      stmt = con.createStatement(); 
      String sql = "DELETE FROM bill " + 
      "WHERE bid = ('"+id+"')"; 
      int w=stmt.executeUpdate(sql); 
      if(w!=0) 
      JOptionPane.showMessageDialog(null,"Deleted Successfully!"); //this is displayed successfully 
      else 
      JOptionPane.showMessageDialog(null,"value does not exists!");// this is displayed successfully 
      supplieridtext.setText(""); 

      //view trigger 
      String sql1="SELECT * FROM bill"; 

      stmt = con.createStatement(); 

      ResultSet rs = stmt.executeQuery(sql1); 
      //STEP 5: Extract data from result set 
      billtable.setModel(DbUtils.resultSetToTableModel(rs)); 
      rs.close(); 

      //step5 close the connection object 
     } 
    }catch(ClassNotFoundException | SQLException e){ 
     JOptionPane.showMessageDialog(null,"no value entered!");} //this line is not displayed when the text field is empty 
} 
+0

它看起來像你應該捕獲一個'java.lang.NumberFormatException',以防給'Integer.parseInt'提供一個它不理解的輸入。 –

+0

'billidtext.getText()。trim()。isEmpty()' – MadProgrammer

votes
answers
20 views
+50

使用遞歸和循環解析JSON

0

我有一個JSON來解析。我試圖用遞歸方法更換預定電流JSON具有類似於底部一個使用遞歸和循環解析JSON

Item 01 
SubItem 01 
    InnerSubItem 01 

Item 02 
SubItem 01 
    InnerSubItem 01 

的結構使用我創建的功能,我能夠解析只有第一套(根據01項內容) 。代碼不回來爲條件時,環路是假

代碼使用

$.getJSON('https://api.myjson.com/bins/6atbz', function(data) { 
 
    repeat(data, data.layers); 
 
}) 
 

 
function repeat(data, x) { 
 
    var layer = data.layers.reverse() 
 
    for (i = 0; i < x.length; i++) { 
 
    name = x[i].name 
 
    console.log(name) 
 
    if (x[i].layers.length > 0) { 
 
     repeat(data, x[i].layers) 
 
    } 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

JSON就像是在JavaScript原生。你可以簡單地使用JSON.parse(data)來將json數據解析爲js對象。 –

votes
answers
24 views
+50

Phonegap/vue js nothing appear on my android phone (withscreen) but it works on my browser

I'am doing a cross-platform application (android/ios), so I am using phonegap and vue js.

I run phonegap serv on my ubuntu with: sudo phonegap serv

If I go on the ip (that phonegap tell me) on my phone with the phonegap app I have nothing, just white screen, but on my browser everything works well.

I tried to use weinre to see my log (in the html I mask my ip that why I put a X but in my real file is just my ip), but in my console log I have nothing, but in inspector if I go on the div and I click on it my screen phone became blue (like when you inspect a web page) so I think the debugger work but not the console.

here my index.html:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Vue Stack 2.0</title>
    <link rel="stylesheet" type="text/css" href="css/app.css">
    <script src="http:/X:8080/target/target-script-min.js#anonymous"></script>
            <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="msapplication-tap-highlight" content="no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

</head>
<body>
    <div id="app"></div>
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script> 
<!-- 
  <script src="js/materialize.js"></script>
        <script src="js/validate.js"></script>
 -->    <script src="js/app.js"></script>
        <!-- <script src="https://unpkg.com/vue-validator@2.1.7/dist/vue-validator.min.js"></script> -->

    <script type="text/javascript">
    app.initialize();
    $(document).bind("mobileinit", function() {
        $.support.cors = true;
        $.mobile.allowCrossDomainPages = true;
    });
    </script>

</body>
</html>

my config.xml:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.Societhy" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Societhy</name>
    <description>Hello World sample application that responds to the deviceready event.</description>
    <author email="support@phonegap.com" href="http://phonegap.com">PhoneGap Team</author>
    <content src="index.html" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="14" />
    <plugin name="cordova-plugin-battery-status" source="npm" spec="~1.1.1" />
    <plugin name="cordova-plugin-camera" source="npm" spec="~2.1.1" />
    <plugin name="cordova-plugin-media-capture" source="npm" spec="~1.2.0" />
    <plugin name="cordova-plugin-console" source="npm" spec="~1.0.2" />
    <plugin name="cordova-plugin-contacts" source="npm" spec="~2.0.1" />
    <plugin name="cordova-plugin-device" source="npm" spec="~1.1.1" />
    <plugin name="cordova-plugin-device-motion" source="npm" spec="~1.2.0" />
    <plugin name="cordova-plugin-device-orientation" source="npm" spec="~1.0.2" />
    <plugin name="cordova-plugin-dialogs" source="npm" spec="~1.2.0" />
    <plugin name="cordova-plugin-file" source="npm" spec="~4.1.1" />
    <plugin name="cordova-plugin-file-transfer" source="npm" spec="~1.5.0" />
    <plugin name="cordova-plugin-geolocation" source="npm" spec="~2.1.0" />
    <plugin name="cordova-plugin-globalization" source="npm" spec="~1.0.3" />
    <plugin name="cordova-plugin-inappbrowser" source="npm" spec="~1.3.0" />
    <plugin name="cordova-plugin-media" source="npm" spec="~2.2.0" />
    <plugin name="cordova-plugin-network-information" source="npm" spec="~1.2.0" />
    <plugin name="cordova-plugin-splashscreen" source="npm" spec="~3.2.1" />
    <plugin name="cordova-plugin-vibration" source="npm" spec="~2.1.0" />
    <plugin name="cordova-plugin-whitelist" source="npm" spec="~1.2.1" />
    <icon src="icon.png" />
    <platform name="android">
        <icon density="ldpi" src="www/res/icon/android/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="www/res/icon/android/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="www/res/icon/android/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="www/res/icon/android/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="www/res/icon/android/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="www/res/icon/android/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="www/res/screen/android/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="www/res/screen/android/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="www/res/screen/android/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="www/res/screen/android/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="www/res/screen/android/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="www/res/screen/android/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="www/res/screen/android/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="www/res/screen/android/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="www/res/screen/android/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="www/res/screen/android/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="www/res/screen/android/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="www/res/screen/android/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <icon height="57" platform="ios" src="www/res/icon/ios/icon.png" width="57" />
        <icon height="114" platform="ios" src="www/res/icon/ios/icon@2x.png" width="114" />
        <icon height="40" platform="ios" src="www/res/icon/ios/icon-40.png" width="40" />
        <icon height="80" platform="ios" src="www/res/icon/ios/icon-40@2x.png" width="80" />
        <icon height="50" platform="ios" src="www/res/icon/ios/icon-50.png" width="50" />
        <icon height="100" platform="ios" src="www/res/icon/ios/icon-50@2x.png" width="100" />
        <icon height="60" platform="ios" src="www/res/icon/ios/icon-60.png" width="60" />
        <icon height="120" platform="ios" src="www/res/icon/ios/icon-60@2x.png" width="120" />
        <icon height="180" platform="ios" src="www/res/icon/ios/icon-60@3x.png" width="180" />
        <icon height="72" platform="ios" src="www/res/icon/ios/icon-72.png" width="72" />
        <icon height="144" platform="ios" src="www/res/icon/ios/icon-72@2x.png" width="144" />
        <icon height="76" platform="ios" src="www/res/icon/ios/icon-76.png" width="76" />
        <icon height="152" platform="ios" src="www/res/icon/ios/icon-76@2x.png" width="152" />
        <icon height="29" platform="ios" src="www/res/icon/ios/icon-small.png" width="29" />
        <icon height="58" platform="ios" src="www/res/icon/ios/icon-small@2x.png" width="58" />
        <icon height="87" platform="ios" src="www/res/icon/ios/icon-small@3x.png" width="87" />
        <splash height="1136" platform="ios" src="www/res/screen/ios/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" platform="ios" src="www/res/screen/ios/Default-667h.png" width="750" />
        <splash height="2208" platform="ios" src="www/res/screen/ios/Default-736h.png" width="1242" />
        <splash height="1242" platform="ios" src="www/res/screen/ios/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" platform="ios" src="www/res/screen/ios/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="768" platform="ios" src="www/res/screen/ios/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" platform="ios" src="www/res/screen/ios/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="1024" platform="ios" src="www/res/screen/ios/Default-Portrait~ipad.png" width="768" />
        <splash height="960" platform="ios" src="www/res/screen/ios/Default@2x~iphone.png" width="640" />
        <splash height="480" platform="ios" src="www/res/screen/ios/Default~iphone.png" width="320" />
    </platform>
    <platform name="wp8">
        <icon height="99" platform="wp8" src="www/res/icon/wp8/ApplicationIcon.png" width="99" />
        <icon height="159" platform="wp8" src="www/res/icon/wp8/Background.png" width="159" />
        <splash height="1280" platform="wp8" src="www/res/screen/wp8/screen-portrait.jpg" width="768" />
    </platform>
    <platform name="windows">
        <icon height="150" platform="windows" src="www/res/icon/windows/Square150x150Logo.scale-100.png" width="150" />
        <icon height="30" platform="windows" src="www/res/icon/windows/Square30x30Logo.scale-100.png" width="30" />
        <icon height="50" platform="windows" src="www/res/icon/windows/StoreLogo.scale-100.png" width="50" />
        <splash height="300" platform="windows" src="www/res/screen/windows/SplashScreen.scale-100.png" width="620" />
        <icon height="120" platform="windows" src="www/res/icon/windows/StoreLogo.scale-240.png" width="120" />
        <icon height="44" platform="windows" src="www/res/icon/windows/Square44x44Logo.scale-100.png" width="44" />
        <icon height="106" platform="windows" src="www/res/icon/windows/Square44x44Logo.scale-240.png" width="106" />
        <icon height="70" platform="windows" src="www/res/icon/windows/Square70x70Logo.scale-100.png" width="70" />
        <icon height="71" platform="windows" src="www/res/icon/windows/Square71x71Logo.scale-100.png" width="71" />
        <icon height="170" platform="windows" src="www/res/icon/windows/Square71x71Logo.scale-240.png" width="170" />
        <icon height="360" platform="windows" src="www/res/icon/windows/Square150x150Logo.scale-240.png" width="360" />
        <icon height="310" platform="windows" src="www/res/icon/windows/Square310x310Logo.scale-100.png" width="310" />
        <icon height="150" platform="windows" src="www/res/icon/windows/Wide310x150Logo.scale-100.png" width="310" />
        <icon height="360" platform="windows" src="www/res/icon/windows/Wide310x150Logo.scale-240.png" width="744" />
        <splash height="1920" platform="windows" src="www/res/screen/windows/SplashScreenPhone.scale-240.png" width="1152" />
    </platform>
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <plugin name="cordova-plugin-statusbar" spec="~2.2.3" />
    <plugin name="cordova-plugin-crosswalk-webview" spec="https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview">
        <variable name="XWALK_VERSION" value="23+" />
        <variable name="XWALK_LITEVERSION" value="xwalk_core_library_canary:17+" />
        <variable name="XWALK_COMMANDLINE" value="--disable-pull-to-refresh-effect" />
        <variable name="XWALK_MODE" value="embedded" />
        <variable name="XWALK_MULTIPLEAPK" value="true" />
    </plugin>
</widget>

my app.js:

import { Vue, router, store } from './boot/core'
import App from './components/app.vue'
import io from 'socket.io-client';
import VueSocketio from 'vue-socket.io';
import VueToastr from '@deveodk/vue-toastr'
// You need a specific loader for CSS files like https://github.com/webpack/css-loader
// If you would like custom styling of the toastr the css file can be replaced

var Vue = require('vue');
var VueCookie = require('vue-cookie');
//require('jquery-toast-plugin')

var socketio = io('http://localhost:4242/');


// Tell Vue to use the plugin
Vue.use(VueSocketio, socketio);
Vue.use(VueCookie);
Vue.use(VueToastr, {
    defaultPosition: 'toast-top-right',
    defaultType: 'info',
    defaultTimeout: 4000
});


var vm = new Vue({
    router : router,
    el: 'app',
    render: h => h(App),
    data: { store },
    sockets:{
    connect: function(){
      console.log('socket connected');
    },
    sessionId: function(val){
      console.log('sessionId');
      console.log(val);
      this.store.sessionId = val;
    },
    txResult: function(val){

      console.log(val)
      console.log("txResult");
      this.$toastr('success', 'Success', val.event);
      this.store.txResult = val.event;
    }
    },
    methods: {
        /**
        * The Application method
        *
        * @module App
        */

         /**
        * @method getJSONData
        * @param {Object} object - data
        * get the json of a data
        */
        getJSONData(json) {
            if (this.isPhoneGap()) {
                console.log("PJSON: " + json.data)
                console.log("PJSON: " + json.data.toString())
                return json.user;
            }
            else {
                console.log("BJSON: " + JSON.parse(json.data))
                console.log("BJSON: " + JSON.parse(json.data).toString())
                return JSON.parse(json.user);
            }
        },

        /**
        * @method ajaxRequest
        * Basic ajax request for the edition 
        */
        ajaxRequest(type, route, params, success, error) {
            var res = "";
            var url = 'http://localhost:4242/login';
            var xhr = $.ajax({
                url: route,
                async: false,
                dataType : "json",
                type: type,
                contentType: "application/json; charset=utf-8",
                xhrFields: { withCredentials: true },
                crossDomain: true,
                data: JSON.stringify(params),
                beforeSend: setAuthToken,
                success: success,
                error: error,
                cache: false,
            })
        },

        /**
        * Set the token of authentification
        * @method setAuthToken
        * @param {Object} json object who contains the token
        */
        setAuthToken(request) {
            if (this.store.auth_data != null) {
                request.setRequestHeader("Authentification", this.store.auth_data.token);
            }
        },
        /**
        * Check if the application turn on phonegap
        * @method isPhoneGap
        */
        isPhoneGap() {
            return (window.cordova || window.PhoneGap || window.phonegap) 
            && /^file:/{3}[^/]/i.test(window.location.href) 
            && /ios|iphone|ipod|ipad|android/i.test(navigator.userAgent);
        },

        /**
        * Set the auth data
        * @param {Object} json object with all the information about the user
        * @method setAuthData
        */
        setAuthData(_auth_data) {
            this.store.auth_data = _auth_data;
        },
    }
})

window.vue = vm;
votes
answers
22 views
+50

Javascript:我如何才能影響我試圖觸發的特定ID?

-1

例如,當我點擊一個按鈕時,它會以某種方式影響頁面上的每個按鈕。我只是想影響我點擊的那個。Javascript:我如何才能影響我試圖觸發的特定ID?

下面是腳本:

// when the user clicks on like 
    $('.icon-wrapper').on('click', function(){ 
     var postid = $(this).data('id'); 
      $post = $(this); 

     $.ajax({ 
      url: 'user_profiles.php', 
      type: 'post', 
      data: { 
       'liked': 1, 
       'postid': postid 
      }, 
      success: function(response){ 
       $post.parent().find('span.likes_count').text(response); 

       $post.addClass('hide'); 
       $post.siblings().removeClass('hide'); 
       $post.siblings().addClass('anim'); 
       $post.removeClass('anim'); 


      } 
     }); 
    }); 

HTML:

$sql = "SELECT * FROM user_images WHERE username = '$username' ORDER BY id DESC"; 
     $result = mysqli_query($db, $sql); 
      echo '<div class="hero">'; 
      echo '<div class="hero-content">'; 
      echo '<div class="row">'; 

    while ($row = mysqli_fetch_array($result)) { 
     echo '<div class="social-img hide-750">'; 
     echo '<div class="social-content">'; 
     echo '<a style="outline: none;" href="../profiles/uploads/'.$row["images"].'" data-fancybox="quote" data-caption="Uploaded by: '.$row["username"].'" >'; 
     echo  '<img src="../profiles/uploads/'.$row["images"].'">'; 
     echo  '</a>'; 
     echo  '<div class="share">'; 
     echo    '<form enctype="multipart/form-data" action="../update_note" method="post">'; 
     echo    '<i class="fa fa-comment-o" aria-hidden="true"></i>'; 
     echo    '<a href="../delete.php?id='.$row["id"].'"><i style="float:right;" class="fa fa-times" aria-hidden="true"></i></a>'; 
     echo    '<input type="hidden" name="id" value="'.$row["id"].'"/>'; 
     echo   '<input type="hidden" name="img" value="'.$row["images"].'"/>'; 
     echo    '<input type="hidden" name="submitOne" />'; 
     echo    '<div class="col-3">'; 
     echo    '<input name="note" class="effect-2" type="texxxt" placeholder="Update your note..." /> '; 
     echo    '<span class="focus-border"></span>'; 
     echo    '</div>'; 
     echo    '</form>'; 
     echo  '</div>'; 
     ?> 
     <?php 
     $ssql = "SELECT * FROM likes WHERE userid =".$_SESSION['user_id']." AND postid=".$row['id'].""; 
     $rresult = mysqli_query($db,$ssql); 
     $lrow = mysqli_fetch_array($rresult); 
     ?> 
     <?php 
     if ($lrow['userid']==$_SESSION['user_id'] && $lrow['postid']==$row['id']) { 
      // user has already liked quote 
      echo'<div data-id="'.$row['id'].'" class="icon-appear"> 
       <span class="icon"><i style="color: #FFD700;" class="fa fa-star"></i></span> 
       <div class="border"><span></span></div> 
       <div class="satellite"> 
       <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
       </div> 
       <span class="likes_count">'.$row['likes'].'</span> 
       </div>'; 
       echo'<div data-id="'.$row['id'].'" class="icon-wrapper hide"> 
       <span class="icon"><i class="fa fa-star"></i></span> 
       <div class="border"><span></span></div> 
       <div class="satellite"> 
       <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
        <span></span> 
       </div> 
       <span class="likes_count">'.$row['likes'].'</span> 
       </div>'; 

     } else {} 

動畫腳本:

var $iconWrapper = $(".icon-wrapper"); 
$iconWrapper.on('click', function() { 
    var _this = $iconWrapper; 
    if (_this.hasClass('anim')) _this.removeClass('anim'); 
    else { 
    _this.addClass('anim'); 
    _this.css('pointer-events', 'none'); 
    setTimeout(function() { 
     _this.css('pointer-events', ''); 
    }, 1200); 
    } 
}) 

注:其實我有這樣的早期類似的問題,因爲一切都被打印出來mysqli_fetch_array裏面,我通過重新排列一些lin來解決這個問題ES。

+0

我想我們會結婚,看看您呈現的HTML代碼,看看這裏發生了什麼。您是否可以使用受影響按鈕的HYML代碼進行更新? –

+0

你也應該顯示HTML – 2017-11-11 15:34:49

+0

我加了HTML –

votes
answers
40 views
+50

CGImage.cropping(to :)在OS X上翻轉

1

我發現CGImage.cropping(to:)將使用左上角的原點(增加Y向下)而不是左下角(隨着Y向上增加)處理指定的矩形, 。這是特別奇怪的,因爲CGImage默認情況下不是這樣定向的,因爲在應用掩碼時情況並非如此。請注意,這與UIImage和方向無關 - 這是OS X特定的。CGImage.cropping(to :)在OS X上翻轉

我將此作爲一個問題提交,但這更多的是一個觀察。 Core Graphics上的Stack Overflow上的iOS中有更多的信息比OS X更多,Apple的裁剪文檔沒有解釋這一點。

下面是繪製圖像右下象限的代碼,而期望它繪製右上象限。

func getImage(_ url: CFURL) -> CGImage? { 
    guard let imageSource = CGImageSourceCreateWithURL(url, nil) else { return nil } 

    guard let image = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else { 
     let imageSourceStatus = CGImageSourceGetStatus(imageSource) 
     Swift.print("image nil, Image Source Status = (imageSourceStatus)") 
     return nil 
    } 
    return image 
} 

func northeastQuadrant(fromImage: CGImage) -> CGRect { 
    let w = CGFloat(fromImage.width) 
    let h = CGFloat(fromImage.height) 
    let bottomleft = CGPoint(x: w/2.0, y: h/2.0) 
    return CGRect(x: bottomleft.x, y: bottomleft.y, width: w/2.0, height: h/2.0) 
} 

func southwestQuadrant(fromImage: CGImage) -> CGRect { 
    let w = CGFloat(fromImage.width) 
    let h = CGFloat(fromImage.height) 
    return CGRect(x: 0, y: 0, width: w/2.0, height: h/2.0) 
} 

class CGImageView: NSView { 
    func setImage() { 
     let url = CFURLCreateWithString(nil, "file:////Users/erickampman/Documents/FractIFS/Demonic%20Scarecrows.tiff" as CFString, nil) 

     let img = getImage(url!) 
     let quad = northeastQuadrant(fromImage: img!) 
//  let quad = southwestQuadrant(fromImage: img!) 
     image = img!.cropping(to: quad) 
    } 

    override func draw(_ dirtyRect: NSRect) { 
     if nil == image { 
      Swift.print("Calling setImage") 
      setImage() 
     } 

     guard let image = self.image else { 
      Swift.print("Nil image!") 
      return 
     } 
     super.draw(dirtyRect) 
     guard let cgContext = NSGraphicsContext.current?.cgContext else { return } 
     Swift.print("ctx transform: (cgContext.ctm)") 
     cgContext.saveGState(); 
     cgContext.draw(image, in: self.bounds, byTiling: false) 
     cgContext.restoreGState(); 
    } 

    var image: CGImage? 
} 
votes
answers
35 views
+50

與無線電輸入結合使用`ngModel`顯示或隱藏部

0

我建立一個用戶接口,其中用戶可以創建兩種類型的內容即LINKMESSAGE與無線電輸入結合使用`ngModel`顯示或隱藏部

我會使用內置解決方案,例如Ionic中的Segment組件,但由於設計要求,這是不可能的。

我做的是什麼,我有兩個無線電輸入

<input [(ngModel)]="notificationCreateType" type="radio" id="notification_type_link" name="notificationType" value="0" class="custom-radio" /> 

<input [(ngModel)]="notificationCreateType" checked type="radio" id="notification_type_message" name="notificationType" value="1" class="custom-radio" /> 

值0的鏈路和1是消息。

  <div *ngIf="notificationCreateType == '0'"> 
       ... stuffs here 
      </div> 


      <div *ngIf="notificationCreateType == '1'"> 
       ... stuffs here 
      </div> 

似乎選擇任意的無線選項時,工作正常,但是當已經被選中的頁面加載和無線選項最初不工作。

[(ngModel)]="notificationCreateType"絕對使用無線電輸入的值,並設置notificationCreateType它,雖然它不會做同樣的當輸入已經被設置checked屬性

什麼我會檢查喜歡做的是要麼ngModel尊重輸入的checked屬性,或者甚至更好的是我可以在組件的ts文件中設置notificationCreateType的初始值,該文件用於在模板中自動檢查無線電輸入。

這是甚至可能的,因爲我經歷了許多文檔,包括官方的Ionic和Angular文檔,仍然沒有發現關於無線電輸入的詳細信息。

votes
answers
23 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
16 views
+50

確切的詞衝突字與前圍

1

本來,我用是爲完全相符的文字只是字的邊界 - https://regex101.com/r/M97FkV/4確切的詞衝突字與前圍

更新1

1)完全相符的文字裏面的字標點符號,如20-year-old

  • 搜索year's只有year's確切匹配

- 單獨的搜索year,將不匹配year's

  • 如果我搜索20-year-old,準確20-year-old是匹配

- 搜索20yearold不會匹配20-year-old

2 )在標點符號之前或之後的精確匹配詞

  • 如果我搜索old,確切的詞或前或標點後old.oldold.-oldold-_oldold_old''old這些都會匹配。

- old將不會與標點符號中的單詞匹配20-year-old

我們最後的進展

https://regex101.com/r/M97FkV/15 - 解決(2),而不是(1)

https://regex101.com/r/M97FkV/16 - 解決(1),而不是(2)

+0

我們是否需要考慮多個前導或尾隨標點符號的可能性? '字,''? – mickmackusa

+0

我很難告訴我的手機,但我想這是一個Unicode單引號或捲曲單引號。複製該字符並粘貼到谷歌搜索中以確定。當我到達我的電腦時,我會將unicode標誌添加到我的答案中。 – mickmackusa

votes
answers
32 views
+50

PHP檢查字段是否爲空

0

我正在做一個註冊表單,並且我試圖編寫一個代碼,如果用戶沒有填寫所有字段,將顯示錯誤。它工作正常,但由於某種原因,它只適用於我輸入電子郵件。如果我將所有字段留空並單擊註冊,我不會收到任何錯誤,並且所有字段爲空,當我單擊註冊按鈕時,我的光標會轉到電子郵件字段並被激活(此字段)。 這封郵件有問題,但我找不到任何問題,所以錯在哪裏?PHP檢查字段是否爲空

PHP源代碼:

if(empty($_POST['fname']) || empty($_POST['lname']) || empty($_POST['email']) || empty($_POST['password'])) 
{ 
    $error="Fill all fields!"; 
} 

HTML:

<form action="register.php" method="POST"> 
    <input style="margin-top:10px" type="text" value="First Name" name="fname" onblur="if (this.value == '') {this.value = 'First Name';}" onfocus="if (this.value == 'First Name') {this.value = '';}" /> 

    <input type="text" value="Last Name" name="lname" onblur="if (this.value == '') {this.value = 'Last Name';}" onfocus="if (this.value == 'Last Name') {this.value = '';}" /> 

    <input type="email" value="Adres e-mail" name="email" onblur="if (this.value == '') {this.value = 'Adres e-mail';}" onfocus="if (this.value == 'Adres e-mail') {this.value = '';}" /> 

    <p><input type="password" value="Password" name="password" onblur="if (this.value == '') {this.value = 'Password';}" onfocus="if (this.value == 'Password') {this.value = '';}" /></p> 

    <button type="submit" name="submit"> Register</button> </br> 
    </br> 

</form> 
+0

這是什麼問題的現狀如何? – chris85

votes
answers
37 views
+50

將產品添加到一個新的銷售報價通過Odoo API(Java)的

0

我通過Odoo API,像這樣創造新的銷售報價編程:將產品添加到一個新的銷售報價通過Odoo API(Java)的

final Object orderLineItem = asList((Object[]) models.execute("execute_kw", asList(
    db, uid, password, 
    "sale.order.line", "search", 
    asList(asList()), 
    new HashMap() {{ 
     put("limit", 10); 
    }}) 
)).get(0); 

final Integer id = (Integer) models.execute("execute_kw", asList(
    db, uid, password, 
    "sale.order", "create", 
    asList(new HashMap() {{ 
     put("currency_id", resCurrency); 
     put("date_order", dateTime); 
     put("partner_id", resPartnerId); 
     put("picking_policy", ""); 
     put("pricelist_id", productPricelistId); 
     put("name", name); 
     put("warehouse_id", stockWarehouseId); 
     put("partner_invoice_id", resPartnerId); 
     put("partner_shipping_id", resPartnerId); 
     put("access_token", ""); 
     put("order_line", asList(
     asList(1, false, new HashMap<String, Object>() {{ 
      put("product_id", orderLineItem); 
     }}))); 
    }}) 
)); 

不過,我無法列出產品在報價單的order_line部分。 Order_line有一對多的關係,但我不確定這是否與可銷售給客戶的產品有關係,或者完全不同。

我知道sale.order.line資源包含我所有的'order_lines'或產品,但我不確定如何將這些產品添加到新的銷售報價中。

任何幫助在Java或python等效將不勝感激。

+0

什麼問題正好沒看明白的資源解決了這個:我知道了sale.order.line資源包含了所有我的「ORDER_LINES」或產品,但我不確定如何將這些產品添加到新的銷售報價 – Cherif

+0

orderLineItem的價值是什麼? – jo541

votes
answers
49 views
+50

爲什麼Google Cloud Function在部署後多次運行全局功能?

1

我設置了多個觸發器,如:爲什麼Google Cloud Function在部署後多次運行全局功能?

exports.doSomething = functions.firestore.document('col/{doc}').onCreate(event => {}) 

比我有我想要運行時刻,當我部署一個功能。這看起來是這樣的:

now() 
function now(){ 
    console.log("running function") 
} 

而且我得到這個在我的日誌:

enter image description here

它爲什麼跑這麼多次,並得到其他函數調用?

的完整代碼,只是測試它和運行函數被調用4次,相同數量的觸發我已設置:

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 
const db = admin.firestore() 
var geoip = require('geoip-lite'); 

exports.z = functions.firestore.document('converasdassdtIP/{UID}').onCreate(event => { }) 
exports.x = functions.firestore.document('sads/{UID}').onCreate(event => { }) 
exports.n = functions.firestore.document('asdasasdsa/{UID}').onCreate(event => { }) 
exports.m = functions.firestore.document('converasdasddtIP/{UID}').onCreate(event => { }) 

now() 
function now(){ 
    console.log("running function") 
} 
+0

你的代碼在哪裏調用'now()'?你可以添加你的一些'function/index.js'到這個問題嗎? – Callam

+0

@Callam看到我的編輯 –

+0

每次觸發函數時,都會調用'now()'的調用,因爲它位於'index.js'文件的根範圍內,因此每個運行的雲功能都會看到登錄。你想用這個日誌實現什麼?你想什麼時候打印? – Callam

votes
answers
33 views
+50

硒的webdriver的java:點擊複選框

1

我有一個表,它的HTML代碼如下所示。我想單擊包含「基本用戶」的行中的複選框(即在tr [5]中)。我無法點擊複選框。我使用firefox瀏覽器和硒的webdriver(JAVA)硒的webdriver的java:點擊複選框

<div class="ui-jqgrid-bdiv" style="height: 340px; width: 440px;"> 
<div style="position:relative;"> 
<div></div> 
<table id="s_4_l" class="ui-jqgrid-btable" border="0" cellspacing="0" cellpadding="0" tabindex="0" role="grid" aria-multiselectable="true" aria-labelledby="" style="width: 439px;" summary="Responsibilities" datatable="1"> 
<tbody> 
<tr class="jqgfirstrow" style="height:auto" role="row"> 
<tr id="1" class="ui-widget-content jqgrow ui-row-ltr" tabindex="-1" role="row" style="height: 32px;"> 
<tr id="2" class="ui-widget-content jqgrow ui-row-ltr" tabindex="-1" role="row" style="height: 32px;"> 
<tr id="3" class="ui-widget-content jqgrow ui-row-ltr" tabindex="-1" role="row" style="height: 32px;"> 
<tr id="4" class="ui-widget-content jqgrow ui-row-ltr" tabindex="-1" role="row" style="height: 32px;" aria-selected="false"> 
<tr id="5" class="ui-widget-content jqgrow ui-row-ltr ui-state-highlight selected-row ui-state-hover" tabindex="-1" role="row" style="height: 32px;" aria-selected="true"> 
<td aria-describedby="s_4_l_cb" style="text-align:center;display:none;" role="gridcell"> 
<input id="jqg_s_4_l_5" class="cbox" type="checkbox" role="checkbox"> 
</td> 
<td id="5_s_4_l_SSA_Primary_Field" class="edit-cell ui-state-highlight" title="Unchecked" style="text-align:center;" role="gridcell" aria-labelledby="s_4_l_SSA_Primary_Field s_4_l_altCheckBox" tabindex="0"> 
<span tabindex="-1"> 
<input id="5_SSA_Primary_Field" class="customelement siebui-ctrl-checkbox siebui-align-center siebui-input-align-center s_4_2_82_0" type="checkbox" aria-checked="false" value="N" tabindex="0" role="checkbox" name="SSA_Primary_Field" maxlength="1" aria-labelledby="5_s_4_l_Name s_4_l_SSA_Primary_Field s_4_l_altCheckBox"> 
</span> 
</td> 
<td id="5_s_4_l_Name" title="Base User" style="text-align:left;" role="gridcell" aria-labelledby="s_4_l_Name">Base User</td> 
<td id="5_s_4_l_Organization" title="Canada" style="text-align:left;" role="gridcell" aria-labelledby="s_4_l_Organization">Canada</td> 
</tr> 
<tr id="6" class="ui-widget-content jqgrow ui-row-ltr" tabindex="-1" role="row" style="height: 32px;"> 
<td aria-describedby="s_4_l_cb" style="text-align:center;display:none;" role="gridcell"> 
<td id="6_s_4_l_SSA_Primary_Field" title="Checked" style="text-align:center;" role="gridcell" aria-labelledby="s_4_l_SSA_Primary_Field s_4_l_altCheckBox"> 
<span class="siebui-icon-checkbox-checked"> 
<img hspace="0" border="0" space="0" title="Selected" alt="Selected" src="XYZ.com/images/check_d.gif"> 
</span> 
<span style="display:none;">Y</span> 
</td> 
<td id="6_s_4_l_Name" title="Product Administrator" style="text-align:left;" role="gridcell" aria-labelledby="s_4_l_Name">Product Administrator</td> 
<td id="6_s_4_l_Organization" title="Canada" style="text-align:left;" role="gridcell" aria-labelledby="s_4_l_Organization">Canada</td> 
</tr> 
<tr id="7" class="ui-widget-content jqgrow ui-row-ltr" tabindex="-1" role="row" style="height: 32px;"> 
</tbody> 
</table> 

此表包含7行,第一列各行中的複選框。在任何給定時間,只有一行有複選框CHECKED/TICKED,這裏是第6行。對於其他行,複選框不顯示。只有當您在某一行的第一個單元格區域內單擊某處時,該行的複選框纔會顯示。然後你可以勾選該複選框。因此,我點擊了第五行的第一個單元格,現在顯示了複選框(如下面的代碼所示)。

如何點擊此複選框第5行的? 我的代碼如下,第三行是一個我試圖點擊複選框,但它不會點擊。

WebElement primaryCell = driver.findElement(By.xpath("/html/body/div[9]/div[2]/div/div/div/div[3]/form/div[1]/div/div/div[3]/div[3]/div/table/tbody/tr/td[contains(text(),'Base User')]/preceding-sibling::td[@title='Unchecked']")); 
primaryCell.click(); 
primaryCell.findElement(By.xpath("//span/input")).click(); 

請幫忙,謝謝!

請注意,標記名錶,TR的@id,TD - 不是靜態的,不斷變化。 我曾嘗試使用某些現有帖子中提供的解決方案,但我無法解決我的問題。

votes
answers
20 views
+50

如何在Swift 4中引用數組內的數組的單元格?

0

我在Swift中有些不太起眼。我有一個數組的數組。我想參考字母"H",即僅使用一行代碼來參考第一個陣列的第一個單元。這是如何在Swift中完成的?即如何在一行中寫入示例代碼的最後兩行,而不使用temp如何在Swift 4中引用數組內的數組的單元格?

let textArrays = [ 
         ["H","E","L","L","O"], 
         ["W","O","R","L","D","!"] 
        ] 
    let temp = textArrays[0] 
    let HWLabel.text = HWLabel.text + temp[0].description 
+0

'textArrays [0] [0]' – Sweeper

+0

我應該猜到了。我正在嘗試'textArrays [0]。[0]'謝謝! – user594883

+0

@Sweeper是否介意將您的評論寫爲答案,以便我可以接受問題的答案? – user594883

votes
answers
29 views
+50

Is JSON Hijacking still an issue in modern browsers?

I am using Backbone.js and the Tornado web server. The standard behavior for receiving collection data in Backbone is to send as a JSON Array.

On the other hand, Tornado's standard behavior is to not allow JSON Array's due to the following vulnerability:

http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

A related one is: http://haacked.com/archive/2009/06/25/json-hijacking.aspx

It feels more natural for me to not have to wrap up my JSON in an object when it really is a list of objects.

I was unable to reproduce these attacks in modern browsers (i.e. current Chrome, Firefox, Safari, and IE9). At the same time I was unable to confirm anywhere that modern browsers had addressed these issues.

To ensure that I am mislead neither by any possible poor programming-skills nor poor googling-skills:

Are these JSON Hijacking attacks still an issue today in modern browsers?

(Note: Sorry for the possible duplicate to: Is it possible to do 'JSON hijacking' on modern browser? but since the accepted answer does not seem to answer the question - I thought it was time to ask it again and get some clearer explanations.)

votes
answers
45 views
+50

python/Pyqt5 - 如何避免使用ast和獲取ValueError時的eval:試圖提高代碼安全性時使用格式錯誤的字符串

0

我試圖防止使用eval基於示例how-to-avoid-eval-in-python-for-string-conversion使用ast。挑戰在於有十二個這樣的self.ch%s_label被創建,但它的變量根據GUI中的用戶輸入而改變。python/Pyqt5 - 如何避免使用ast和獲取ValueError時的eval:試圖提高代碼安全性時使用格式錯誤的字符串

我的代碼:

import ast ...etc. 

.... 

channel_no += 1 

ch_width = eval('self.ch%s_label.frameGeometry().width()' % (channel_no)) 

當我把它變成:

ch_width = ast.literal_eval('self.ch%s_label.frameGeometry().width()' % (channel_no)) 

我會得到錯誤:

File "c:pythonanac2libast.py", line 80, in literal_eval return _convert(node_or_string) File "c:pythonanac2libast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string

更改代碼(使用關「「)保留錯誤:

ch_width = ast.literal_eval("'self.ch%s_label.frameGeometry().width()' % (channel_no)") 

還有什麼其他選擇...有什麼建議嗎?

votes
answers
25 views
+50

當用`sess.run`請求一個變量的值時,爲什麼沒有隱式的控制依賴?

0

我想了解是否有下面的行爲可以用下面的代碼片段重現的原因。當用`sess.run`請求一個變量的值時,爲什麼沒有隱式的控制依賴?

當我請求sess.run返回Variable的值時,它返回的值不依賴於可能更新返回之前執行的變量的所有操作。

在這裏的示例中,我正在測試應用於將變量a的值複製到b之前的依賴關係,然後再爲a指定一個隨機值。

該過程有效,但第一個打印語句的結果是任意的(取決於任意處理順序),第二個打印語句的結果是正確的。

我自然希望該值張量ab返回是在所有計算的END變量的值,但事實並非如此。

不是是否有一個很好的理由,包括對作爲sess.run的一部分請求的變量的隱式控制依賴?

import tensorflow as tf 

a = tf.Variable(0.0) 
b = tf.Variable(0.0) 
r = tf.random_normal(shape=()) 

op_a2b = tf.assign(b, a) 

with tf.control_dependencies([op_a2b]): 
    op_r2a = tf.assign(a, r) 

sess = tf.InteractiveSession() 
sess.run(tf.global_variables_initializer()) 

print(sess.run([a, b, r, op_r2a, op_a2b])) 
print(sess.run([a, b])) 

下面的結果。請注意,ab的值在sess.run的調用之間有所不同,但它們不會更改。這表明張量流不能保證變量的返回值是返回前計算的最後一個值。

[0.0, 0.0, 0.79926836, 0.79926836, 0.0] 
[0.79926836, 0.0] 
votes
answers
44 views
+50

如何從其他線程訪問主UI線程中的System.Windows.Threading.Dispatcher?

1

我讀過,我們無法從其他工作線程訪問Silverlight應用程序的主UI線程中的任何內容。如何從其他線程訪問主UI線程中的System.Windows.Threading.Dispatcher?

那麼,爲什麼有可能訪問一個類System.Windows.Threading.Dispatcher的對象,該對象與其他工作線程中的主UI線程關聯時,我們想要委派一些工作在用戶界面上完成?

public partial class DispatcherExample : UserControl 
{ 
    public void AnyFunctionExecutingInSomeOtherThread() 
    { 
    this.Dispatcher.BeginInvoke(SomeDelegate); 
    } 
} 
votes
answers
26 views
+50

閱讀Haskell中的ini文件

1

我正在嘗試閱讀Haskell中的簡單.ini文件,以用作我的應用程序的配置。我不是Haskell的專家,所以我可能會錯過簡單的東西。閱讀Haskell中的ini文件

到目前爲止,我的簡化代碼如下所示

{-# LANGUAGE OverloadedStrings   #-} 

import Data.Ini 

main :: IO() 
main = do 
    config <- readIniFile "config.ini" 
    p <- lookupValue "NETWORK" "port" config 

    ... 

編譯器給了我這個錯誤

無法匹配,期望型「燕麗」與實際類型的「任意字符串燕麗」在第三個參數lookupValue即'config'。

我看着Data.Ini的docs,但我找不到如何使用Api的任何示例。

任何幫助將非常感激。

+0

聽起來配置返回一個字符串要麼燕麗,而不僅僅是一個ini。只是在配置模式匹配,'左犯錯的情況下配置 - > putStrLn錯誤;正確的c - >做lookupValue ...' – Zpalmtree

votes
answers
17 views
+50

PHP中的Flash消息清除$ _SESSION密鑰,然後應用。

0

我遇到了一個問題,我稱之爲Flash消息。
它應該在輸出後從$ _SESSION數組中清除一個鍵,但它在之前將其清除。我知道,因爲如果我評論的取消設置()它的作品(當然關鍵是不被清除,並堅持下去的刷新)總之,這將是代碼:

if (isset($_SESSION['error'])) { 
    echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>'); 
    unset($_SESSION['error']); 
} 

,因爲它是回聲語句不工作。如果註釋未設置回聲的作品,但$ _SESSION鍵沒有清除,我需要輸出後清除它。 非常奇怪,我在其他文件中編碼相同,它的工作完美無瑕。 這裏的謎語愛好者的整個代碼。

<?php 
session_start(); 
if(isset($_POST['username']) && isset($_POST['password'])){ 
    unset($_SESSION['username']); 
    if($_POST['password'] =='umsi' && $_POST['username'] == 'chuck') { 
     $_SESSION['username'] = $_POST['username']; 
     $_SESSION['success'] = 'Logged in successfuly'; 
     $_SESSION['password'] = $_POST['password']; 
     header('Location: app.php'); 
     return; 
    } 
    else { 
     $_SESSION['error'] = 'Login incorrect'; 
     header('Location: log.php'); 
    } 
} 
?> 
<!DOCTYPE html> 
<html lang="es"> 

<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="main.css"> 
    <title>Log In</title> 
</head> 

<body> 
    <div class="log"> 
     <?php 
     if (isset($_SESSION['error'])) { 
     echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>'); 
     unset($_SESSION['error']); 
     } 
     ?> 
     <h1>Log in</h1> 
     <form method="post"> 
     <label for="username">Username</label> 
     <input type="text" name="username"> 
     <label for="password">Password</label> 
     <input type="password" name="password"> 
     <button type="submit">Submit</button> 
     </form> 
    </div> 
</body> 

</html> 
+0

把'exit('Location:log.php');'並退出'exit'退出'退出。發生了什麼是解除它的代碼,因爲你沒有退出而被執行。 –

+0

OMG你的回答讓我看到了正確的地方,我錯過了回頭之後! –

+0

np,不要使用return使用exit,也總是在'header('Location:...')'後面退出,只有瀏覽器聽那個,而不是黑客。 –

votes
answers
68 views
+50

如何重命名數據存儲實體字段,但能夠通過舊的和新的屬性名稱檢索記錄?

0

我有一個實體如何重命名數據存儲實體字段,但能夠通過舊的和新的屬性名稱檢索記錄?

class Foo { 
    public String bar; 
} 

我想重命名 「酒吧」 到 「somethingElse」。並計劃使用Objectify的@AlsoLoad註解來實現這一點(我已經在使用Objectify進行持久化)。因此,像:

class Foo { 
    @AlsoLoad("bar") 
    public String somethingElse; 
} 

但形式有任何疑問:

final Query<Foo> query = OfyService.ofy().load().type(Foo.class) 
    .filter("somethingElse", "someValue"); 

只擷取自重命名已保存的實體。任何較舊的實體都被忽略。

什麼是重命名實體字段的最佳做法,以便我可以有一個將返回所有記錄的單個查詢?

votes
answers
67 views
+50

Windows服務在Windows 7上啓動,但無法在Windows Server 2008 R2上啓動

1

我創建了一個通過託管Windows服務部署的wcf服務。 onstart()所做的是創建併爲wcf serice打開一個tcp主機。Windows服務在Windows 7上啓動,但無法在Windows Server 2008 R2上啓動

在Windows 7中一切正常,但當我嘗試在Windows Server 2008 R2中安裝服務時,服務啓動,然後停止,有時服務停止,當沒有任何事情時會停止。它在網絡服務帳戶下運行。

我無法找到任何有用的Windows日誌。

我嘗試安裝dubug構建並調用debugger.launch(),但它不工作。我不能使用remode調試,因爲這個過程沒有保持足夠長的時間來打開它。 我真的不知道該怎麼辦。這是我的代碼:

protected override void OnStart(string[] args) 
    { 
     System.Diagnostics.Debugger.Launch(); 

     try 
     { 

      //if (!System.Diagnostics.EventLog.SourceExists("i2s CU Service (eng)")) 
      //{ 
      // System.Diagnostics.EventLog.CreateEventSource("i2s CU Service", "Application"); 
      //} 
      System.Diagnostics.EventLog.CreateEventSource("i2s CU Service", "Application"); 
     } 
     catch (Exception) 
     { 
      //throw; 
     } 
     eventLog1.Source = "i2s CU Service"; 
     eventLog1.Log = "Application"; 

     if (serviceHost != null) 
     { 
      serviceHost.Close(); 
     } 

     System.Configuration.AppSettingsReader reader = new System.Configuration.AppSettingsReader(); 
     Uri tcpUri = null; 
     try 
     { 
      tcpUri = new Uri((string)reader.GetValue("Uri", typeof(string))); //net.tcp://localhost:8008/i2sServer 

      serviceHost = new ServiceHost(typeof(ConcurrentUsers), tcpUri); 

      // Create a binding that uses TCP and set the security mode to none. 
      NetTcpBinding b = new NetTcpBinding(); 
      b.Security.Mode = SecurityMode.None; 

      // Add an endpoint to the service. 
      serviceHost.AddServiceEndpoint(typeof(IConcurrentUsers), b, ""); 

      // Open the ServiceHostBase to create listeners and start 
      // listening for messages. 
      serviceHost.Open(); 
     } 
     catch (Exception ex) 
     { 
      eventLog1.WriteEntry(ex.Message, EventLogEntryType.Error); 
     } 


     if (serviceHost.State == CommunicationState.Opened) 
     { 
      eventLog1.WriteEntry("Service started.", EventLogEntryType.Information); 
     } 
    } 

    protected override void OnStop() 
    { 
     if (serviceHost != null) 
     { 
      serviceHost.Close(); 
      serviceHost = null; 
     } 
     eventLog1.WriteEntry("Service stopped.", EventLogEntryType.Information); 
    } 

此代碼是在Windows 7中工作完美,但我不能讓它在win 2008 R2服務器上運行。

在此先感謝

+1

你不處理的第一個例外相同的用戶帳戶下運行控制檯的副本,這個問題可能發生在那裏。 – vulkanino 2012-03-07 16:04:18

+0

我已經嘗試刪除整個錯誤日誌的東西,仍然是相同的 – Ares 2012-03-07 16:59:48

+0

這似乎並沒有在Windows 7中的問題,並在之前所述的調試器不會啓動! – Ares 2012-03-07 17:09:00

votes
answers
11 views
+50

What is a “fat pointer” in Rust?

I've read the term "fat pointer" in several contexts already, but I'm not sure what exactly it means and when it is used in Rust. The pointer seems to be twice as large as a normal pointer, but I don't understand why. It also seems to have something to do with trait objects.

votes
answers
52 views
+50

使用Spring MVC與CockroachDB

0

我正在嘗試開發一個Spring CockcoreDB集羣數據庫使用Hibernate和PostgreSQL驅動程序的應用程序。使用Spring MVC與CockroachDB

與數據庫的連接正常,並且所有表都已創建。

但是,當我啓動服務器我得到這個錯誤

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at fr.esper.back.restfull.RestfullBackServer.main(RestfullBackServer.java:9) [classes/:na] 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144] 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144] 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144] 
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144] 
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory 
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] 
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE] 
    ... 21 common frames omitted 
Caused by: org.hibernate.exception.SQLGrammarException: Error accessing index information: testdb.car 
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.convertSQLException(InformationExtractorJdbcDatabaseMetaDataImpl.java:99) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getIndexes(InformationExtractorJdbcDatabaseMetaDataImpl.java:609) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.indexes(TableInformationImpl.java:110) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.getIndex(TableInformationImpl.java:121) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.findMatchingIndex(SchemaMigratorImpl.java:292) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyIndexes(SchemaMigratorImpl.java:277) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:184) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final] 
    ... 27 common frames omitted 
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "." 
    Détail : source SQL: 
SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, ct.relname AS TABLE_NAME, NOT i.indisunique AS NON_UNIQUE, NULL AS INDEX_QUALIFIER, ci.relname AS INDEX_NAME, CASE i.indisclustered  WHEN true THEN 1 ELSE CASE am.amname  WHEN 'hash' THEN 2  ELSE 3 END END AS TYPE, (i.keys).n AS ORDINAL_POSITION, trim(both '"' from pg_catalog.pg_get_indexdef(ci.oid, (i.keys).n, false)) AS COLUMN_NAME, CASE am.amcanorder  WHEN true THEN CASE i.indoption[(i.keys).n - 1] & 1  WHEN 1 THEN 'D'  ELSE 'A'  END  ELSE NULL END AS ASC_OR_DESC, ci.reltuples AS CARDINALITY, ci.relpages AS PAGES, pg_catalog.pg_get_expr(i.indpred, i.indrelid) AS FILTER_CONDITION FROM pg_catalog.pg_class ct JOIN pg_catalog.pg_namespace n ON (ct.relnamespace = n.oid) JOIN (SELECT i.indexrelid, i.indrelid, i.indoption,   i.indisunique, i.indisclustered, i.indpred,   i.indexprs,   information_schema._pg_expandarray(i.indkey) AS keys   FROM pg_catalog.pg_index i) i  ON (ct.oid = i.indrelid) JOIN pg_catalog.pg_class ci ON (ci.oid = i.indexrelid) JOIN pg_catalog.pg_am am ON (ci.relam = am.oid) WHERE true AND n.nspname = 'testdb' AND ct.relname = 'car' ORDER BY NON_UNIQUE, TYPE, INDEX_NAME, ORDINAL_POSITION 
                                                                              ^
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2412) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2125) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:297) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:301) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:287) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:264) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:231) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.postgresql.jdbc.PgDatabaseMetaData.getIndexInfo(PgDatabaseMetaData.java:2325) ~[postgresql-42.0.0.jar:42.0.0] 
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getIndexes(InformationExtractorJdbcDatabaseMetaDataImpl.java:567) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] 
    ... 38 common frames omitted 


Process finished with exit code 0 

的模式很簡單:用戶擁有多輛。

類用戶

Entity 
@Table(name = "ApplicationUser") 
public class User { 
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 
    @NotNull @Column(unique = true) 
    private String username; 
    @NotNull @Size(min = 5, max = 15) 
    private String password; 
    @NotNull 
    private String firstName; 
    @NotNull 
    private String lastName; 
    @NotNull @Column(unique = true) 
    private String mailAddress; 
    @NotNull @Column(unique = true) 
    private String phoneNumber; 
........... 
} 

級車

@Entity 
@Table(name = "car", 
     indexes = @Index(name = "owner_index", columnList = "owner_id")) 
public class Car { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private long id; 
    private String name; 
    @OneToOne 
    private User owner; 
...... 
} 

Application.properties

spring.datasource.url = jdbc:postgresql://~~~~~~/testdb 
spring.jpa.show-sql = true 
spring.jpa.database = postgresql 
spring.datasource.driver-class-name= org.postgresql.Driver 
spring.jpa.hibernate.ddl-auto = update 
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect 

在p因爲沒有創建外鍵索引,因此Car表中的外鍵「所有者」似乎來自索引

當我試圖表明從車指標,我得到:

~~~~~~~~~~/testdb> show indexes from car; 
+-------+---------+--------+-----+--------+-----------+---------+----------+ 
| Table | Name | Unique | Seq | Column | Direction | Storing | Implicit | 
+-------+---------+--------+-----+--------+-----------+---------+----------+ 
| car | primary | true | 1 | id  | ASC  | false | false | 
+-------+---------+--------+-----+--------+-----------+---------+----------+ 

我已經嘗試在球場上手動創建索引owner_id,但它不工作。

votes
answers
17 views
+50

蟒蛇2.7多線程技術在印刷掛

1

我的Python軟件死鎖interminttently(可能是由於一些競爭條件)蟒蛇2.7多線程技術在印刷掛

內正在運行的線程中的一個,它運行

while True: 
    msg = printQ.get() 
    print msg 
    sys.stdout.flush() 

在調試時,我看到我的一個線程掛起在 sys.stdout.flush()。如果我刪除了沖洗線,線程會在打印時掛起。 這是打印到stdout

如果停用此線程,我的軟件犯規僵局

有沒有在多線程ENV沖洗標準輸出的任何已知問題的唯一線索?

這些是在軟件死鎖時正在運行線程的跟蹤。什麼東西都跳出來給你們?對我來說,它看起來像睡了幾次,等待隊列中的物品。只是很奇怪我的事情是sys.stdout.flush()

# ThreadID: 139736001795840 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 726, in worker 
    jobref = Host.r.blpop(Dispatch.rkey_completeQ, timeout=1) 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/client.py", line 1090, in blpop 
    return self.execute_command('BLPOP', *keys) 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/client.py", line 529, in execute_command 
    return self.parse_response(connection, command_name, **options) 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/client.py", line 541, in parse_response 
    response = connection.read_response() 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/connection.py", line 545, in read_response 
    response = self._parser.read_response() 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/connection.py", line 213, in read_response 
    response = self._buffer.readline() 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/connection.py", line 151, in readline 
    self._read_from_socket() 
File: "/usr/software/rats/bedrock/lib/python2.7/site-packages/redis/connection.py", line 109, in _read_from_socket 
    data = self._sock.recv(socket_read_size) 

# ThreadID: 139736012285696 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 605, in worker 
    job = Factory.dispQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736022775552 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 605, in worker 
    job = Factory.dispQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737333483264 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 236, in worker 
    (job, msg, to_debug) = Factory.logQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736461068032 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 605, in worker 
    job = Factory.dispQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736492537600 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737322993408 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 313, in worker 
    sys.stdout.flush() 

# ThreadID: 139736909850368 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736920340224 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737354462976 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 350, in worker 
    item = Factory.streamQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736930830080 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736471557888 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736951809792 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736962299648 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737474270976 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Status_thread.py", line 131, in run 
    request = self._queue.get(timeout=1) # blocking get with a timeout of 1 second 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 177, in get 
    self.not_empty.wait(remaining) 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 359, in wait 
    _sleep(delay) 

# ThreadID: 139736450578176 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 605, in worker 
    job = Factory.dispQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737364952832 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Stack_Tracer.py", line 56, in run 
    self.stacktraces() 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Stack_Tracer.py", line 70, in stacktraces 
    fout.write(stacktraces()) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Stack_Tracer.py", line 22, in stacktraces 
    for filename, lineno, name, line in traceback.extract_stack(stack): 

# ThreadID: 139737343973120 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 416, in worker 
    time.sleep(1) 

# ThreadID: 139736440088320 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 605, in worker 
    job = Factory.dispQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139736482047744 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737312503552 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 

# ThreadID: 139737628997376 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Br.py", line 86, in <module> 
    Command.main() 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Command.py", line 149, in main 
    com.run(args) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Btool.py", line 181, in run 
    self.make_locked(args) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Btool.py", line 227, in make_locked 
    Dispatch.run_jobs() 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch.py", line 732, in run_jobs 
    # we got any hung jobs?? 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch.py", line 332, in check_for_hung_jobs 
    really_running = job.log_check() 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Job.py", line 391, in log_check 
    if Checkproc.check_remote_process(Options.options.rsh_cmd, lock.hostname, lock.pid, 20): 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Checkproc.py", line 92, in check_remote_process 
    time.sleep(1) 

# ThreadID: 139736941319936 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 783, in __bootstrap 
    self.__bootstrap_inner() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
File: "/u/eugenep/bedrock/source/br-new-release/lib/btool/Dispatch_Factory.py", line 470, in worker 
    job = Factory.rdyQ.get() 
File: "/usr/software/rats/bedrock/lib/python2.7/Queue.py", line 168, in get 
    self.not_empty.wait() 
File: "/usr/software/rats/bedrock/lib/python2.7/threading.py", line 340, in wait 
    waiter.acquire() 
votes
answers
18 views
+50

JavaScript拉斐爾動畫路徑

1

我有一個路徑,使形狀和能夠旋轉,但我無法弄清楚如何我可以得到形狀/路徑向下移動屏幕。我看過其他解決方案,但我似乎無法讓他們工作。謝謝。JavaScript拉斐爾動畫路徑

leftRec = paper.path("M400 50 L380 70 420 90 380 110 420 130 400 150 350 150 350 50z"); 
leftRec.attr("fill","#f00"); 
leftRec.animate({transform:"r-70,400,150"}, 2000, "ease-in"); 

leftRec.animate({cy: 600, cx: 200}, 2000); 
+0

所以,你會想要形狀旋轉,向下移動屏幕或向下移動就足夠了? –

votes
answers
17 views
+50

PHP中的Flash消息清除$ _SESSION密鑰,然後應用。

0

我遇到了一個問題,我稱之爲Flash消息。
它應該在輸出後從$ _SESSION數組中清除一個鍵,但它在之前將其清除。我知道,因爲如果我評論的取消設置()它的作品(當然關鍵是不被清除,並堅持下去的刷新)總之,這將是代碼:

if (isset($_SESSION['error'])) { 
    echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>'); 
    unset($_SESSION['error']); 
} 

,因爲它是回聲語句不工作。如果註釋未設置回聲的作品,但$ _SESSION鍵沒有清除,我需要輸出後清除它。 非常奇怪,我在其他文件中編碼相同,它的工作完美無瑕。 這裏的謎語愛好者的整個代碼。

<?php 
session_start(); 
if(isset($_POST['username']) && isset($_POST['password'])){ 
    unset($_SESSION['username']); 
    if($_POST['password'] =='umsi' && $_POST['username'] == 'chuck') { 
     $_SESSION['username'] = $_POST['username']; 
     $_SESSION['success'] = 'Logged in successfuly'; 
     $_SESSION['password'] = $_POST['password']; 
     header('Location: app.php'); 
     return; 
    } 
    else { 
     $_SESSION['error'] = 'Login incorrect'; 
     header('Location: log.php'); 
    } 
} 
?> 
<!DOCTYPE html> 
<html lang="es"> 

<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="main.css"> 
    <title>Log In</title> 
</head> 

<body> 
    <div class="log"> 
     <?php 
     if (isset($_SESSION['error'])) { 
     echo('<p style="color:red; margin:0">'. $_SESSION['error'] .'</p>'); 
     unset($_SESSION['error']); 
     } 
     ?> 
     <h1>Log in</h1> 
     <form method="post"> 
     <label for="username">Username</label> 
     <input type="text" name="username"> 
     <label for="password">Password</label> 
     <input type="password" name="password"> 
     <button type="submit">Submit</button> 
     </form> 
    </div> 
</body> 

</html> 
+0

把'exit('Location:log.php');'並退出'exit'退出'退出。發生了什麼是解除它的代碼,因爲你沒有退出而被執行。 –

+0

OMG你的回答讓我看到了正確的地方,我錯過了回頭之後! –

+0

np,不要使用return使用exit,也總是在'header('Location:...')'後面退出,只有瀏覽器聽那個,而不是黑客。 –

votes
answers
36 views
+50

ThreadPoolExecutor作爲隊列嗎?

-2

我使用ThreadPoolExecuter作爲我的事務處理應用程序的隊列。以下是代碼剪斷並在PROD服務器所使用的值:ThreadPoolExecutor作爲隊列嗎?

new ThreadPoolExecutor(
    corePool, maxPool,keepAlive,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>()); 
  1. 核心池和Maxpool在性能負載服務器配置爲「50」。
  2. 每筆交易的交易處理時間爲300 MS。
  3. 當我們向該服務器發送30 tps時,CPU使用率達到了100%,服務器沒有響應。

是否有任何替代解決方案來處理70到80 TPS使用該服務器?有人能指導我處理這個問題的最佳方法嗎?

+1

300毫秒(即0.3秒)是長時間。每個核心可以在一秒鐘內完成3次以上的交易。核心數量將決定你的吞吐量;例如4核心將支持12 tps; 8核心將支持24 tps。對於80 tps你需要27個內核。 INSTEAD,你可能想看看減少你的處理時間。你在做什麼,需要300ms?!? – robertf

+1

您正在使用*隊列*作爲隊列。您正在使用Executor作爲執行者。 – EJP

+0

您需要運行一個分析器來查看實際需要的時間,然後優化慢速比特。目前你正在尋找優化可能與問題無關的事情。 –

votes
answers
28 views
+50

Insert line break in postgresql when updating text field

I am trying to update a text field in a table of my postgresql database.

UPDATE public.table SET long_text = 'First Line' + CHAR(10) + 'Second line.' WHERE id = 19;

My intended result is that the cell will look like this:

First Line
Second line

The above syntax returns an error.

votes
answers
9 views
+50

Calling C# interface default method from implementing class

C# 8 supports default method implementations in interfaces. My idea was to inject a logging method into classes like this:

public interface ILoggable {
    void Log(string message) => DoSomethingWith(message);
}

public class MyClass : ILoggable {
    void MyMethod() {
        Log("Using injected logging"); // COMPILER ERROR
    }
}

I get a compiler error: "The name does not exist in the current context"

Is it impossible to use default method implementations in this way?

EDIT:

For the correct response regarding C# rules, see the accepted answer. For a more concise solution (the original idea of my question!) see my own answer below.

votes
answers
35 views
+50

How to convert UTF-8 byte[] to string?

I have a byte[] array that is loaded from a file that I happen to known contains UTF-8. In some debugging code, I need to convert it to a string. Is there a one liner that will do this?

Under the covers it should be just an allocation and a memcopy, so even if it is not implemented, it should be possible.

votes
answers
51 views
+50

建模Azure Cosmos DB

1

我正計劃爲自己的目的從CoinMarketCap API保存記錄。 我想每隔15分鐘將價格信息保存在前100個加密硬幣上,我想將它保存在Azure Cosmos數據庫中。建模Azure Cosmos DB

由於im新的文檔db的整個概念,我需要一些建模文檔的幫助。

首先我從這個模型開始。

[ 
    { 
     "id": "bitcoin", 
     "name": "Bitcoin", 
     "symbol": "BTC", 
     "rank": "1", 
     "price_usd": "573.137", 
     "price_btc": "1.0", 
     "24h_volume_usd": "72855700.0", 
     "market_cap_usd": "9080883500.0", 
     "available_supply": "15844176.0", 
     "total_supply": "15844176.0", 
     "percent_change_1h": "0.04", 
     "percent_change_24h": "-0.3", 
     "percent_change_7d": "-0.57", 
     "last_updated": "1472762067" 
    }, 
    { 
     "id": "ethereum", 
     "name": "Ethereum", 
     "symbol": "ETH", 
     "rank": "2", 
     "price_usd": "12.1844", 
     "price_btc": "0.021262", 
     "24h_volume_usd": "24085900.0", 
     "market_cap_usd": "1018098455.0", 
     "available_supply": "83557537.0", 
     "total_supply": "83557537.0", 
     "percent_change_1h": "-0.58", 
     "percent_change_24h": "6.34", 
     "percent_change_7d": "8.59", 
     "last_updated": "1472762062" 
    }, 
    ... 
] 

但是,由於每次我寫入數據庫時??id都沒有變化,記錄只是更新了,而沒有彙總。我想這是預期的。

因此,爲了確保記錄彙總,我重寫了這個模型。

[ 
    { 
     "id": <timestamp>_bitcoin 
     "identifier": "bitcoin", 
     "name": "Bitcoin", 
     "symbol": "BTC", 
     "rank": "1", 
     "price_usd": "573.137", 
     "price_btc": "1.0", 
     "24h_volume_usd": "72855700.0", 
     "market_cap_usd": "9080883500.0", 
     "available_supply": "15844176.0", 
     "total_supply": "15844176.0", 
     "percent_change_1h": "0.04", 
     "percent_change_24h": "-0.3", 
     "percent_change_7d": "-0.57", 
     "last_updated": "1472762067" 
    }, 
    { 
     "id": <timestamp>_ethereum 
     "identifier": "ethereum", 
     "name": "Ethereum", 
     "symbol": "ETH", 
     "rank": "2", 
     "price_usd": "12.1844", 
     "price_btc": "0.021262", 
     "24h_volume_usd": "24085900.0", 
     "market_cap_usd": "1018098455.0", 
     "available_supply": "83557537.0", 
     "total_supply": "83557537.0", 
     "percent_change_1h": "-0.58", 
     "percent_change_24h": "6.34", 
     "percent_change_7d": "8.59", 
     "last_updated": "1472762062" 
    }, 
    ... 
] 

在這裏,我以使其獨特添加了一個單獨的id帶有時間戳和參考舊ID。

這是行得通的,但我認爲這是一些重複的數據(如名稱和符號),我認爲這看起來不好,有雙重。但也許這就是它在文檔db世界中的方式?

我也想過這樣的模型。

[ 
    { 
     "id": <timestamp>_bitcoin 
     "identifier": "bitcoin", 
     "name": "Bitcoin", 
     "symbol": "BTC", 
     "rank": "1", 
     "price_history": [{ 
      "price_usd": "573.137", 
      "price_btc": "1.0", 
      "24h_volume_usd": "72855700.0", 
      "market_cap_usd": "9080883500.0", 
      "available_supply": "15844176.0", 
      "total_supply": "15844176.0", 
      "percent_change_1h": "0.04", 
      "percent_change_24h": "-0.3", 
      "percent_change_7d": "-0.57", 
      "last_updated": "1472762067" 
     ]} 
    }, 
    { 
     "id": <timestamp>_ethereum 
     "identifier": "ethereum", 
     "name": "Ethereum", 
     "symbol": "ETH", 
     "rank": "2", 
     "price_history": [{ 
      "price_usd": "12.1844", 
      "price_btc": "0.021262", 
      "24h_volume_usd": "24085900.0", 
      "market_cap_usd": "1018098455.0", 
      "available_supply": "83557537.0", 
      "total_supply": "83557537.0", 
      "percent_change_1h": "-0.58", 
      "percent_change_24h": "6.34", 
      "percent_change_7d": "8.59", 
      "last_updated": "1472762062" 
     ]} 
    }, 
    ... 
] 

但由於沒有選擇新的記錄添加到price_history無需重寫整個文件,這不會是一個好主意。此外,由於price_history中的記錄數量將無限制地增長,因此該文檔將變得非常龐大且難以處理。

接下來我想分解成單獨的文件,但不知道如果這是要走的路。所以我現在有點迷路了。

有什麼建議嗎?

+0

你能在你的每cryptocurrency聚集的價格信息(如果有的話)的要求詳細點嗎?或者是你只需要記錄每個時間戳最後一小時,一天和一週的百分比變化? –

+0

我想保留歷史數據以便分析它。一個例子就是及時檢查新聞對價格變化或其他類似情景的影響。還想玩Azure機器學習,並且爲了使用我需要的一些數據來分析。 – Martin

votes
answers
34 views
+50

在另一個線程創建窗口(不是主線程)

5

我有一個功能:在另一個線程創建窗口(不是主線程)

HWND createMainWindow(P2p_Socket_Machine * toSend){ 

    HWND hMainWnd = CreateWindow( 
     L"Class",/*(LPCWSTR) nameOfConference.c_str()*/L"Chat", WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU, 
    CW_USEDEFAULT, 0, 600,400, 
    (HWND)NULL, (HMENU)NULL, 
    /*(HINSTANCE)hlnstance*/NULL, NULL 
    ); 

    if (!hMainWnd) { 
     MessageBox(NULL, L"Cannot create main window", L"Error", MB_OK); 
     return 0; 
    } 

    CreateWindowA("LISTBOX",NULL, WS_CHILD|WS_VISIBLE|WS_BORDER|WS_VSCROLL|LBS_NOTIFY|LBS_MULTIPLESEL,310,30,255,275,hMainWnd,(HMENU)List_Box,NULL,NULL); 

    CreateWindowExA(NULL,"BUTTON", "Refresh", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,385,310,100,24,hMainWnd,(HMENU)Button_Refresh, NULL ,NULL); 

    CreateWindowExA(NULL,"BUTTON", "Send", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,385,334,100,24,hMainWnd,(HMENU)Button_Send, NULL ,NULL); 

    CreateWindowExA(NULL,"BUTTON", "New", WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,385,354,100,24,hMainWnd,(HMENU)Button_New, NULL ,NULL); 

    CreateWindowA("EDIT",0,WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE|WS_VSCROLL|WS_DISABLED, 
    10,30,265,275,hMainWnd,(HMENU)Text_Box_Get,NULL,NULL); 

    CreateWindowA("EDIT",0,WS_BORDER|WS_VISIBLE|WS_CHILD|ES_LEFT|ES_MULTILINE|WS_VSCROLL, 
    10,320,265,45,hMainWnd,(HMENU)Text_Box_Send,NULL,NULL); 

    SetWindowLongPtr(hMainWnd,GWLP_USERDATA,(LONG_PTR)toSend); 

    ShowWindow(hMainWnd, SW_SHOW); 
    //UpdateWindow(hMainWnd); 

    return hMainWnd; 

} 

這是我計劃的主要部分:)

int WINAPI WinMain(HINSTANCE hlnstance, HINSTANCE hPrevInstance, LPSTR IpCmdLine, int 
nCmdShow) 
{ 
WNDCLASSEX wc; 
    wc.cbSize = sizeof(wc); 
    wc.style = CS_HREDRAW | CS_VREDRAW; 
    wc.lpfnWndProc = MyFunc; 
    wc.cbClsExtra = 0; 
    wc.cbWndExtra = 0; 
    wc.hInstance = hlnstance; 
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); 
    wc.hCursor = LoadCursor(NULL, IDC_ARROW); 
    wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); 
    wc.lpszMenuName = NULL; 
    wc.lpszClassName = L"Class"; 
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); 
HWND toSend = createMainWindow(P2pSocket); 

//some code 

hThread = CreateThread(NULL, 0, ClientThread, 
      Message2, 0, &dwThreadId); 

     if (hThread == NULL) 
     { 
      cout<<"Create thread filed"; 
      exit(10); 
     } 


    while (GetMessage(&msg, NULL, 0, 0)) { 

     TranslateMessage(&msg); 
     DispatchMessage(&msg); 

    } 

    return msg.wParam; 

當我打電話功能則CreateMainWindow(在我的程序的主要部分 它的作品,因爲它應該,但是當我在我的 線程中運行它(ClientThread)這是行不通的。我讀過我應該只在主線程中創建窗口。這是真的嗎?如果這是真的,從另一個主線程調用此函數最簡單的方法是什麼?


謝謝大家。現在我知道這個問題,但我堅持解決方案。 我的客戶端線程的代碼是:直到接收消息

while(1){ 

    vector<HWND> AllHandlers; 

    pair<string,string> Answer = Pointer->receiveMsgByUdp(); 

    if(!Pointer->isMyLocalAddress(Answer.first)){ 

     int type = messageUdpContentType(Answer.second); 

     switch(type){ 

     case 0 : 

      Pointer->sendMsgToIpUdp(Answer.first,"<?xml version='1.0'?><accepted/>"); 
      AllHandlers = getAllHandlersOfElementsOnWindowsByIdentityCode(Pointer->getAllHandlers(),List_Box); 
      for(vector<HWND>::iterator j = AllHandlers.begin();j!=AllHandlers.end();j++) 
       if(SendMessageA(*j, LB_FINDSTRINGEXACT, 0, (LPARAM)Answer.first.c_str())==LB_ERR) 
        SendMessageA(*j, LB_ADDSTRING, 0, (LPARAM)Answer.first.c_str()); 

      break; 

     case 1 : 
      AllHandlers = getAllHandlersOfElementsOnWindowsByIdentityCode(Pointer->getAllHandlers(),List_Box); 
      for(vector<HWND>::iterator j = AllHandlers.begin();j!=AllHandlers.end();j++) 
       if(SendMessageA(*j, LB_FINDSTRINGEXACT, 0, (LPARAM)Answer.first.c_str())==LB_ERR) 
        SendMessageA(*j, LB_ADDSTRING, 0, (LPARAM)Answer.first.c_str()); 

      break; 

     case 2 : 
      AllHandlers = getAllHandlersOfElementsOnWindowsByIdentityCode(Pointer->getAllHandlers(),List_Box); 
      for(vector<HWND>::iterator j = AllHandlers.begin();j!=AllHandlers.end();j++) 
       if((i = SendMessageA(*j, LB_FINDSTRINGEXACT, 0, (LPARAM)Answer.first.c_str()))!=LB_ERR) 
        SendMessageA(*j,LB_DELETESTRING, 0, (LPARAM)Answer.first.c_str()); 

      break; 

     case 3 : 

      userReply = MessageBoxW(NULL, L"Принять приглашение на конференцию?", 
        L"", MB_YESNO | MB_ICONQUESTION); 
      if (userReply==IDYES){ 

       //todo: Проверка на создание встречи, в которой уже состоишь 
       string nameOfConf = fetchNameOfInviteConf(Answer.second); 
       Pointer->createConference(nameOfConf); 
       HWND toSendTo = createMainWindow(Pointer); 
       Pointer->setHandlerInfo(nameOfConf,toSendTo);    
       Pointer->addNewMemberToConference_ServerType(nameOfConf,Answer.first); 
       string toSend = string("<?xml version='1.0'?><inviteAccepted>") + nameOfConf + string("</inviteAccepted>"); 
       Pointer->sendMsgToIpUdp(Answer.first,toSend); 

      } 
      break; 

     case 4 : 

      string nameOfConf = fetchNameOfInviteAcceptConf(Answer.second); 

      toSend.clear(); 
      Participants.clear(); 
      Participants = Pointer->getCurrentParticipants(nameOfConf); 
      toSend+="<?xml version='1.0'?>"; 
      toSend+="<conference>"; 
      toSend+="<nameOfConference>"; 
      toSend+=nameOfConf; 
      toSend+="</nameOfConference>"; 
      for(vector<string>::iterator i = Participants.begin();i!=Participants.end();i++){ 
       toSend+="<participant>" + *i + "</participant>"; 
      } 
      toSend+="</conference>"; 



      Pointer->addNewMemberToConference_ClientType(nameOfConf,Answer.first); 

      Pointer->sendToIpTcp(Answer.first,toSend); 

      break; 

    } 

功能receiveMsgByUdp()停止該線程。我對缺乏知識表示歉意,但我可以使用什麼功能或其他的東西來解決這個問題。我應該重寫我的方法receiveMsgByUdp()是異步的,或者如何調用函數createMainWindow()在主線程上運行?關於最後一個變體:我怎樣才能在純winapi中做到這一點,我找不到任何簡單的例子。有人可以提供代碼片段。再次感謝)

+0

感謝每一位。我設法讓這個程序起作用。我使用了David Heffernan的方法。而這個環節上的信息http://stackoverflow.com/questions/7060686/how-do-i-sendmessage-to-a-window-created-on-another-thread – knightOfSpring 2012-03-11 15:53:36

votes
answers
49 views
+50

如何在Linux或Mac中編譯用於Windows的靜態.lib庫

1

我正在尋找在Linux或Mac中爲Windows編譯靜態庫的方式,似乎有交叉編譯器爲Windows生成.a庫,如this one,但那是不是我想要的,我想要的是針對Windows的.lib靜態庫文件,最好是Visual Studio。我知道我可以運行Windows虛擬機並使用Visual Studio,但這太重了,無法在命令行中完成。如何在Linux或Mac中編譯用於Windows的靜態.lib庫

votes
answers
34 views
+50

如何使用自定義名稱添加自定義文件夾根目錄的目錄中在CakePHP 3

0

我想DIST文件夾添加我的webroot目錄,並從視圖 訪問它裏面的如如何使用自定義名稱添加自定義文件夾根目錄的目錄中在CakePHP 3

|_webroot 
    |_js 
    |_img 
    |_dist 

和訪問它是這樣的:

echo $this->Html->dist('filename.ext', ['alt' => '']); 

請給點解決辦法。謝謝