Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
36,059,526 | convert any string like "10", "-0.129894", "12.02102" to number without adding or loosing anything | <p>As you can see from the title I have various cases for strings that can contain numbers in them. I found out that using <code>parseInt()</code> and <code>parseFloat()</code> didn't work for me as parseInt will convert number like 10.28 to just 10, but parseFloat will make number like 10 into 10.0, I want to somehow convert string into number so it stays exactly like it was in the string without anything removed or added.</p>
| <javascript> | 2016-03-17 11:40:52 | LQ_CLOSE |
36,060,460 | mysql query to fetch these results | <p>i have three tables<br>
1.<strong>project_ref_table</strong> with columns<br>
project_id(pk)<br>
project_name<br>
client_id(fk)<br>
project_description </p>
<p>and 2.<strong>client_ref_table</strong> with column<br>
client_id(pk)<br>
client_name<br>
client_email<br>
client_address </p>
<p>3.<strong>emp_ref_table</strong><br>
emp_id(pk)
emp_name<br>
emp_address<br>
project_id(fk)<br>
dept_id<br>
<strong>Suppose user who login with his emp_id is a manager and i need to fetch his client list with their project like this</strong></p>
<p><strong>client_name|client_email|client_address|project_name</strong></p>
| <php><mysql> | 2016-03-17 12:22:37 | LQ_CLOSE |
36,062,332 | Oracle virtual machine (Ubuntu) on windows 7 | <p>I have windows 7 with Oracle Virtualbox 5.0.4 and Ubuntun image 15.10. I notice when I disable VirtualBox DHCP, and make network settings as Bridge, I could ping or ssh from host to guest. But at this time, I could not download package or sudo apt-get install xxx from internet.</p>
<p>when I still disable VirtualBox, I make network as NAT, then I could download package, but could not ping from host to guest. </p>
<p>How could I do both ping from host to guest and download from internet at guest(virtual box)?</p>
<p>Why I am doing that? We have project using kafka storm, solr as backend. (log management system). Client side could be Eclipse in windows, why I could put kakfa storm solr in virtualbox or vagrant, so that saving developer setting up development environment time. </p>
| <linux><ubuntu><virtualbox> | 2016-03-17 13:42:26 | LQ_CLOSE |
36,063,480 | Substitute all words following a pattern in javascript | Given the string below
"Hello this is a :sample string :hello"
i want to substitute :sample and :hello with something else.
How can i do this in javascript? | <javascript><regex> | 2016-03-17 14:29:17 | LQ_EDIT |
36,064,114 | Remove \ From String | I can not remove \ from query string in swift Language. I am using multiple option but it didn't work so please help me.
The sting is :
> "INSERT OR REPLACE INTO List VALUES(NULL,\'RS\',\'PRODUCTI
> FO\',\'AX[Demo]\',\'abc\',\'All\',\'Sk\')" | <string><swift> | 2016-03-17 14:53:19 | LQ_EDIT |
36,064,193 | optiminzing the query and export | below code gives the result but it take 5 min's to execute, after which I need export data to text. there are 12 lakhs records and it does not get export even after 9 hours. could you please help in optimizing the query and improving the execution performance and also help in getting export faster. I can not use offset and fetch in SQL developer.
I use SQL DEVELPER.
with NAGP As
(select Company_common_id,PROFILECLASSVALUE from (select /* + PARALLEL( gp, 20)*/ co.Company_common_id, gp.PROFILECLASSVALUE,rank() over (partition by co.Company_common_id order by co.commit_date desc) RK from stg_cmat.cmat_sync_ref co, stg_cmat.cmat_enrich_ref gp where gp.transaction_id=co.transaction_id and co.event='ENRICHMENT'
and gp.profilename='EnrichmentProfile'and gp.PROFILECLASSNAME='NAGP ID')
where RK =1),cte2 as(select EC.system_serial_number,EC.cmat_customer_id EC_cmat_customer_id,EC.system_status EC_system_status,(select .PROFILECLASSVALUE from NAGP n where n.Company_common_id = EC.cmat_customer_id and rownum=1) EC_NAGP_ID,SN.cmat_customer_id SN_cmat_customer_id,SN.system_status SN_system_status,(select n.PROFILECLASSVALUE from NAGP n where n.Company_common_id = SN.cmat_customer_id and rownum=1) SN_NAGP_ID from (select a.system_serial_number, a.role_id, a.cmat_customer_id, s.system_status from EIM.eim_latest_sys_party_role a, eim.eim_system s where a.system_serial_number = s.system_serial_number (+)
and a.role_id =1) EC, (select a.system_serial_number, a.role_id, a.cmat_customer_id, s.system_status rom EIM.eim_latest_sys_party_role a, eim.eim_system s where a.system_serial_number = s.system_serial_number (+)
and a.role_id =19) SN where EC.system_serial_number=SN.system_serial_number)
select ec_system_status,count(decode ec_system_status, '0',system_serial_number,0))as ec_countofnum,sn_system_status,
count(decode(sn_system_status, '0',system_serial_number,0))as SN_countofnum from cte2 GROUP BY ec_system_status,sn_system_status
| <sql><oracle><oracle-sqldeveloper> | 2016-03-17 14:56:07 | LQ_EDIT |
36,064,779 | JAVA. I'm moving jar file to other PC then the program not showing image | JAVA. I'm finished project, done compilation. Runing the Jar file, program is working.
If I'm moving jar file to other PC then the program not showing image and not showing information from txt files.
I thinking this is from wrang path's. Can you help me?
This some code:
FileInputStream fr2 = new FileInputStream("C:\\Users\\Nickolskiy\\IdeaProjects\\DeutcheCard\\src\\com\\2.txt");
BufferedReader br2 = new BufferedReader (new InputStreamReader(fr2, "Cp1251")); | <java> | 2016-03-17 15:19:41 | LQ_EDIT |
36,065,018 | Here i have the code which works on click. I need this to work onBlur mode iin javascript. Please give your opinions... Here is my code | if(!m.isSystemButtonClicked)
{
console.debug("Inside onHide. m.isSystemButtonClicked=",m.isSystemButtonClicked);
if(m.unloadListener)
{
window.onbeforeunload = m.unloadListener;
}
} | <javascript><onclick><onblur> | 2016-03-17 15:29:20 | LQ_EDIT |
36,067,835 | addStyleClass("sapUiSizeCompact"); after clicking a button in UI5 | I want to change the compact density with a button.
onInit: function () {
this.getView().addStyleClass("sapUiSizeCompact");
},
works well. If I will change it in a button, it does not work.
onOpenDialog: function (oEvent) {
var oDialog1 = new sap.ui.commons.Dialog();
oDialog1.setTitle("App View Settings");
var oText = new sap.ui.commons.TextView({ text: "Compact Content Density:" });
oDialog1.addContent(oText);
var oToggleButton1 = new sap.ui.commons.ToggleButton({
text: "ON, press for OFF",
tooltip: "This is a test tooltip",
pressed: true,
press: function ()
{
if (oToggleButton1.getPressed()) {
oToggleButton1.setText("ON, press for OFF");
this.getView().addStyleClass("sapUiSizeCompact");
} else {
oToggleButton1.setText("OFF, press for ON");
this.getView().removeStyleClass("sapUiSizeCompact");
}
}
});
oDialog1.addContent(oToggleButton1);
oDialog1.addButton(new sap.ui.commons.Button({ text: "OK", press: function () { oDialog1.close(); } }));
oDialog1.open();
},
How can I point to the view from inside the function?
Thanks
Marcus | <javascript><sapui5> | 2016-03-17 17:35:01 | LQ_EDIT |
36,071,014 | Value to be from a selection of 3 and not null | I'm using oracle to create a table called module:
Module(ModuleId, ModuleTitle, ModuleLeader, Credits, CourseworkPercentage, ExamPercentage)
ModuleId being the PK.
A constraint/check which i have to implement is for 'Credits' to be not null and it must be equal to one of the following three values: 10, 20 or 40.
What I have so far is:
CREATE TABLE "MODULE_CC"
("MODULEID" NUMBER,
"MODULETITLE" VARCHAR2(30) NOT NULL ENABLE,
"MODULELEADER" VARCHAR2(30) NOT NULL ENABLE,
"CREDITS" NUMBER NOT NULL ENABLE,
"COURSEWORKPERCENTAGE" NUMBER,
"EXAMPERCENTAGE" NUMBER,
PRIMARY KEY ("MODULEID") ENABLE,
CHECK (CourseworkPercentage + ExamPercentage = 100) ENABLE
);
What would be the check/constrains to make sure that credits will be equal to one of three values(10,20 or 40)? | <sql><oracle> | 2016-03-17 20:25:42 | LQ_EDIT |
36,072,904 | C program with a function which checks if integer A contains integer B ( let's say, A=2345, B=4, in which case it int A does contain int B ) | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int funkcija(int num, int num2)
{
int doesContain;
if (doesContain == 1)
return 1;
else
return 0;
}
int main(void)
{
int num, num2;
scanf("%d", num);
scanf("%d", num2);
printf("%d", funkcija(num, num2));
return 0;
}
So basically, I need to make a function which takes number 1 and number 2, checks if number2 is in number1, then returns 0 or 1.
So for example, if number 1 is let's say '2452325678', and number 2 is '7', number 1 DOES contain number 2 and the statement is true. But if num1 is '2134' and num2 is '5', the statement is false.
It needs to be done PRIMITIVELY, without arrays and whatnot. The professor is basically testing your ability to make an algorithm, and considering I wasn't @ the last lecture due to illness, and I have practice work tomorrow which I need to pass, you can see why I'm in a pickle here.
I need any help I can get with the algorithm, I myself am completely lost on how to do it, thanks! | <c> | 2016-03-17 22:34:11 | LQ_EDIT |
36,076,208 | i need to change my url seo friendly with url routing | i need to know how i change my site url my i try url routing what is not work
my site product url is => [http://www.shahilibas.in/product.php?p_id=5] and i want seo friendly url like [http://www.shahilibas.in/product.php/5]
i try this code for url routing
function getCurrentUri()
{
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
$uri = '/' . trim($uri, '/');
return $uri;
echo $uri;
}
| <javascript><php><jquery> | 2016-03-18 04:34:14 | LQ_EDIT |
36,078,816 | Run some code php from other file | I have two files
In a.php
<?php echo "one"; include 'b.php'; echo "three"; ?>
In b.php
<?php echo"one"; echo"two"; echo"three"; echo"four"; echo"five"; ?>
My question is how get only (echo"two";) from b.php and what i must write in a.php
I hope anyone understand | <php> | 2016-03-18 07:46:12 | LQ_EDIT |
36,079,327 | copy date from one excel workbook to another excel workbook with pushing macro button | >hi all
>I want to copy date from one excel workbook to another excel workbook(master work book) with pushing macro button.
>pls assist. | <excel><vba> | 2016-03-18 08:17:02 | LQ_EDIT |
36,081,945 | i need a PHP code to find longest contiguous sequence of characters in the string. | i need a PHP code to find longest contiguous sequence of characters in the string. So if 'b' is coming together for maximum number of times your program should echo 'b' and count
Example
String: "aaabababbbbbaaaaabbbbbbbbaa"
Output must be: 'b' 8 | <php><algorithm> | 2016-03-18 10:26:55 | LQ_EDIT |
36,083,477 | Do missing foreign keys in the database have an effect on sql generated by EF? | <p>I'm working on a database-first ASP.NET MVC application. Looking at the database the foreign keys are very inconsistent, basically they are only there if it was specified in the SQL scripts that created the tables. In most cases they are not there.</p>
<p>However, looking in the edmx model, I can see that it is aware of the foreign keys i.e. it has correctly identified the navigation properties.</p>
<p>My question is, does the missing foreign keys in the actual database have an effect on the sql genereted by Entity Framework? By effect I mean negative impact on performance.</p>
<p>I can't really figure out if it matters or not.</p>
<p>Just to clarify, in the database I'm expanding tables and looking for the red key which indicates a foreign key. I'm also looking in the subfolder: "Keys".</p>
| <sql-server><database><entity-framework><foreign-keys> | 2016-03-18 11:43:31 | HQ |
36,083,909 | Find a linear run-time strategy to place all records for females before any records for males? | <ol start="3">
<li>Some problems related to sorting can be solved in less than the Θ(n log n) lower bound of sorting. Consider the following scenario. A set of N records containing personnel records has a field indicating gender, male or female. Find a linear run-time strategy to place all records for females before any records for males. That is, females will be at the front of the list and males at the end. </li>
</ol>
| <algorithm><sorting> | 2016-03-18 12:04:50 | LQ_CLOSE |
36,084,515 | How does shallow compare work in react | <p>In <a href="https://facebook.github.io/react/docs/shallow-compare.html" rel="noreferrer">this documentation</a> of React, it is said that </p>
<blockquote>
<p>shallowCompare performs a shallow equality check on the current props and nextProps objects as well as the current state and nextState objects.</p>
</blockquote>
<p>The thing which I am unable to understand is If It shallowly compares the objects then shouldComponentUpdate method will always return true, as</p>
<blockquote>
<p>We should not mutate the states.</p>
</blockquote>
<p>and if we are not mutating the states then the comparison will always return false and so the shouldComponent update will always return true. I am confused about how it is working and how will we override this to boost the performance.</p>
| <javascript><reactjs> | 2016-03-18 12:33:12 | HQ |
36,084,523 | display data from sql database to html table in apache2 server | <p>I'm beginner in php and html so I need your help.
I am trying to display data from my sql database created using phpmyadmin , to a php page.</p>
<p>I've searched the internet and found similar topics , but still have problems</p>
<p>DB: wban ...</p>
<p>Table name: Jack ...</p>
<p>columns to be displayed: Temprature ,pulse , Motion ...</p>
<p>Here is my code , a blank page appear when request "localhost/Jack.php" </p>
<pre><code><?php
$conn=mysql_connect('localhost', 'root', 'MYPASSWORD');
mysql_select_db('wban');
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$query = "SELECT * FROM Jack";
$result = mysql_query($query);
?>
<html>
<head> <title> Jack Status </title> </head>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr> <!-- header row -->
<th>Data</th>
<th>Latest Readings</th>
<th>Average</th>
<th>Standard Deviation</th>
<th>Condition</th>
</tr>
<?php
while($row = mysql_fetch_assoc($result)){ //Create a loop to loop through results
echo "<tr>"
echo "<td>.$row['Temprature'].</td>"
echo "<td>.$row['Pulse'].</td>"
echo "<td>.$row['Motion'].</td>"
echo "</tr>"
}//end while
mysql_close(); //close out the database connection
?>
</table>
</body>
</html>
</code></pre>
| <php><html><mysql><apache> | 2016-03-18 12:33:36 | LQ_CLOSE |
36,084,547 | What does "this" word do in jQuery? | <p>So, here is the question</p>
<p>I can not undestand when i should use "this" instead class or id</p>
<p>If u can show example - it will be fantastic </p>
<p>Thanks</p>
| <javascript><jquery> | 2016-03-18 12:34:38 | LQ_CLOSE |
36,084,681 | Chrome Custom Tabs redirect to Android app will close the app | <p>I am trying to implement an OAuth2 flow with an Android Chrome Custom Tab but my app is always closed (no crash) when the Chrome Custom Tab is receiving the 302 with the location/scheme of my app.</p>
<p>If I create a HTML page with ahref link and touch manually on it the Chrome Custom Tab is correctly switching to my app.</p>
<p>Seems like when handling the server 302 redirect in the Chrome Custom Tab it will not correctly handle my custom app scheme... but why? </p>
<p>If I try the same redirect URL in a stock browser or with a WebView everything is working too.</p>
<p>Here is my current setup:</p>
<p>MainActiviy.java</p>
<pre><code> Button btnChromeCustomTab = (Button) findViewById(R.id.btnChromeCustomTab);
btnChromeCustomTab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
String packageName = CustomTabsHelper.getPackageNameToUse(MainActivity.this);
customTabsIntent.intent.setPackage(packageName);
Uri theLocationUri = Uri.parse(URL);
customTabsIntent.launchUrl(MainActivity.this, theLocationUri);
}
});
</code></pre>
<p>AndroidManifest.xml</p>
<pre><code> <activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter android:label="@string/filter_title">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myappscheme" android:host="oauth" />
</intent-filter>
</activity>
</code></pre>
<p>This is the redirect URL that the app received with HTTP 302 code: </p>
<p>myappscheme://oauth?code=1234567&state=tokenCheck123</p>
<p>build.gradle</p>
<pre><code>android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "de.myapptest.webviewtest"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:customtabs:23.0.0+'
}
</code></pre>
<p>Thanks for any help...</p>
| <android><google-chrome><oauth><chrome-custom-tabs> | 2016-03-18 12:41:40 | HQ |
36,084,711 | Parse error: syntax error, unexpected '$result' (T_VARIABLE), expecting function (T_FUNCTION) | <p>we are trying to rewrite core shipping model in magento.we are trying following code : but we are getting error as follows : </p>
<p>we removed the line that we are getting error</p>
<p>but still the problem didt resolved.</p>
<pre><code> we are getting this error : Parse error: syntax error,
unexpected '$result' (T_VARIABLE), expecting function (T_FUNCTION) in
/app/code/local/Webkul/Mpperproductshipping/Model/Shipping.php on line 56
</code></pre>
<p>we are using following code, you can see error at the end of the line.</p>
<pre><code><?php
class Webkul_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
/* Use group alias */
protected $_code = 'mpperproductshipping';
// Prateek code start
public function collectRates(Mage_Shipping_Model_Rate_Request $request) {
$storeId = $request->getStoreId();
if (!$request->getOrig()) {
$request
->setCountryId(Mage::getStoreConfig(self::XML_PATH_STORE_COUNTRY_ID, $request->getStore()))
->setRegionId(Mage::getStoreConfig(self::XML_PATH_STORE_REGION_ID, $request->getStore()))
->setCity(Mage::getStoreConfig(self::XML_PATH_STORE_CITY, $request->getStore()))
->setPostcode(Mage::getStoreConfig(self::XML_PATH_STORE_ZIP, $request->getStore()));
}
$postCode = $request->getDestPostcode();
$restrictedCodes = array(
110001,
110002
);
//restricted values. they can come from anywhere
if (!in_array($postCode, $restrictedCodes)) {
return $this;
}
$limitCarrier = $request->getLimitCarrier();
if (!$limitCarrier) {
$carriers = Mage::getStoreConfig('carriers', $storeId);
foreach ($carriers as $carrierCode => $carrierConfig) {
$this->collectCarrierRates($carrierCode, $request);
}
} else {
if (!is_array($limitCarrier)) {
$limitCarrier = array($limitCarrier);
}
foreach ($limitCarrier as $carrierCode) {
$carrierConfig = Mage::getStoreConfig('carriers/' . $carrierCode, $storeId);
if (!$carrierConfig) {
continue;
}
$this->collectCarrierRates($carrierCode, $request);
}
}
return $this;
}
// Prateek code end
// $result = Mage::getModel('shipping/rate_result');
/* Edited by vikas_mageworx */
$postcode=$request->getDestPostcode();
$countrycode=$request->getDestCountry();
$items=$request->getAllItems();
/* End Editing by vikas_mageworx */
$postcode=str_replace('-', '', $postcode);
$shippingdetail=array();
/* one start */
$shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
/* one end */
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if($mpassignproductId) {
$mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
$partner = $mpassignModel->getSellerId();
} else {
$collection=Mage::getModel('marketplace/product')
->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
foreach($collection as $temp) {
$partner=$temp->getUserid();
}
}
$product=Mage::getModel('catalog/product')->load($proid)->getWeight();
$weight=$product*$item->getQty();
if(count($shippingdetail)==0){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}else{
$shipinfoflag=true;
$index=0;
foreach($shippingdetail as $itemship){
if($itemship['seller_id']==$partner){
$itemship['items_weight']=$itemship['items_weight']+$weight;
$itemship['product_name']=$itemship['product_name'].",".$item->getName();
$itemship['item_id']=$itemship['item_id'].",".$item->getId();
$itemship['qty']=$itemship['qty']+$item->getQty();
$shippingdetail[$index]=$itemship;
$shipinfoflag=false;
}
$index++;
}
if($shipinfoflag==true){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}
}
}
$shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);
if($shippingpricedetail['errormsg']!==""){
Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
return $result;
}
/*store shipping in session*/
$shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
$shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
/* Use method name */
$method->setMethod($this->_code);
$method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
$method->setCost($shippingpricedetail['handlingfee']);
$method->setPrice($shippingpricedetail['handlingfee']);
$result->append($method);
return $result;
}
public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
$shippinginfo=array();
$handling=0;
$session = Mage::getSingleton('checkout/session');
$customerAddress = $session->getQuote()->getShippingAddress();
/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
/* End Editing by vikas_boy */
/* one */
foreach($shippingdetail as $shipdetail) {
$seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
$sellerAddress = $seller->getPrimaryShippingAddress();
$distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
// echo "distance ".$distance;die;
$price = 0;
$itemsarray=explode(',',$shipdetail['item_id']);
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if (Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($proid))
{
continue;
}
$mpshippingcharge = 0;
$localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
$regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
$stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
if(in_array($item->getId(),$itemsarray)) {
if($mpassignproductId) {
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
}
} else {
// echo "imte ".$item->getProductId();
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
// echo "imte ".$item->getProductId();
// echo "ship ".$mpshippingcharge;
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
}
}
/* tt */
// echo "test ".$mpshippingcharge;die;
if(!is_numeric($mpshippingcharge)){
$price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
}else{
$price=$price+($mpshippingcharge * floatval($item->getQty()));
}
}
}
$handling = $handling+$price;
$submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
}
$msg="";
return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
}
/* one end */
/* tt start */
private function getDistanse($origin,$destination) {
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_all = json_decode($response);
$distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
if($distance==0){
$zips = array(
$origin,$destination
// ... etc ...
);
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = json_decode(curl_exec($curl));
$info = curl_getinfo($curl);
if ($info['http_code'] != 200) {
// Request failed
} else if ($data->status !== 'OK') {
// Something happened, or there are no results
} else {
$geocoded[$zip] =$data->results[0]->geometry->location;
}
}
$distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);
}
return $distance;
}
public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)
{
$measure_unit = 'kilometers';
$measure_state = false;
$measure = 0;
$error = '';
$delta_lat = $lat_b - $lat_a ;
$delta_lon = $lon_b - $lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$measure = $distance;
return $measure;
}
}
/* tt end */
</code></pre>
| <php><magento> | 2016-03-18 12:42:56 | LQ_CLOSE |
36,084,759 | How can I time something in PHP? | <p>I want to do on a script I`m working on that every month a part of the site resets. </p>
<p>Or a better example, Something like a Subscription, when you want to buy something and you need to renew it every month. How can I know its been a month?</p>
| <php><date><time> | 2016-03-18 12:45:13 | LQ_CLOSE |
36,084,902 | Error with SELECT statement in a FOR loop. SQLDEVELOPER | When I try to execute the code below I receive this error here:
Error(9,4): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( ) - + case mod new not null <an identifier> <a double-quoted delimited-identifier> <a bind variable> table continue avg count current exists max min prior sql stddev sum variance execute multiset the both leading trailing forall merge year month day hour minute second timezone_hour timezone_minute timezone_region timezone_abbr time timestamp interval date <a string literal with character set specifica
CREATE OR REPLACE PROCEDURE PROC_LIST_SIMILAR_TVSERIES
(seriesName IN SERIES.NAME%TYPE)
AS CURSOR series IS (SELECT IDS FROM SERIES WHERE NAME = seriesName);
allSeries SERIES%ROWTYPE;
BEGIN
FOR series IN allSeries
(SELECT 2*
(SELECT COUNT(*) FROM DICT d WHERE d.idt IN (
SELECT DISTINCT IDT FROM POSTING WHERE IDS = series
INTERSECT
SELECT DISTINCT IDT FROM POSTING WHERE IDS = allSeries.IDS))
/ ((SELECT DISTINCT COUNT(IDT) FROM POSTING WHERE IDS = series) +
(SELECT DISTINCT COUNT(IDT) FROM POSTING WHERE IDS = allSeries.IDS) ) INTO similarity
FROM SERIES s1, SERIES s2
WHERE s1.IDS = series
AND s2.IDS != series);
IF similarity > 0.7 THEN
DBMS_OUTPUT.PUT_LINE('ok');
END LOOP;
END;
/
What the code does is take in a name, find it's ID, and compare it to other id's. I'm trying to print out "ok" whenever the similarity calculation is over 0.7 . No idea why this doesn't work. | <sql><oracle><plsql> | 2016-03-18 12:52:20 | LQ_EDIT |
36,085,131 | Laravel: connect to databases dynamically | <p>I'm creating an application in Laravel 5(.1) where it is needed to connect to different databases. The only problem is that it's not known which databases it has to connect to, so making use of the database.php in config is not possible. A controller is in charge of making a connection with dynamically given connection details.</p>
<p>How can I make a new connection to a database, including making use of the DB class? (Or is this possible)</p>
<p>Thanks in advance!</p>
| <php><mysql><laravel><laravel-5.1> | 2016-03-18 13:03:11 | HQ |
36,085,665 | != operator condition usage in c# | <p>I know that in C++ you can do this kind of declarations:</p>
<pre><code>size = 8 * (x % 8 != 0);
</code></pre>
<p>What would be the equivalent in C#? Do I have to use an "if"? Thanks for the help!</p>
| <c#><c++><operators><conditional-statements> | 2016-03-18 13:28:05 | LQ_CLOSE |
36,085,828 | PHP Wamp server | <p>Hey I have a database that contains information about different countries. I also have a html page where you can submit information about countries. Can someone help me to write a code that says that the information has been stored in the database instead of it just redirecting to a blank page?</p>
<p>Here is my html page where you submit information:</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Sett inn land</title>
</head>
<body>
<form action="geoinn.php" method="get">
Land: <input type="text" name="navn"> <br>
Hovedstad: <input type="text" name="hovedstad"> <br>
Areal: <input type="text" name="areal"> <br>
Folketall: <input type="text" name="folketall"> <br>
<input type="submit" value="Legg inn informasjon">
</form>
</body>
</html>
</code></pre>
<p>And here is the page that you are redirected to when you click submit on the other page. This is the page where I want to have a code saying either that "The information has been stored in our database" or that it has not:</p>
<pre><code> <?php
$tjener = "localhost";
$brukernavn = "root";
$passord ="";
$database ="Geografi";
$kobling = mysqli_connect($tjener,$brukernavn,$passord,$database);
$kobling->set_charset("utf8");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Geografi</title>
</head>
<body>
<?php
$land = $_GET["navn"];
$hovedstad = $_GET["hovedstad"];
$areal = $_GET["areal"];
$folketall = $_GET["folketall"];
$sql ="INSERT INTO land (navn,hovedstad, areal, folketall) VALUES('$land','$hovedstad','$areal', '$folketall')";
mysqli_query($kobling, $sql);
mysqli_close($kobling);
?>
</body>
</html>
</code></pre>
| <php><wamp> | 2016-03-18 13:35:20 | LQ_CLOSE |
36,085,910 | Extract name of a file without its extension using php | <p>I upload a file say 'example.csv'...How do I store 'example' inside a variable using php so as to create a table in the database having the table name as 'example'?</p>
| <php><mysql> | 2016-03-18 13:38:56 | LQ_CLOSE |
36,086,110 | Deploy a specific directory to npm with Travis-CI | <p>I want to deploy the <code>dist</code> folder after success. But instead, it keeps deploying the whole repository.</p>
<p>What I want to achieve is the same effect with:</p>
<pre><code>npm publish dist
</code></pre>
<p>Here is the related part from my <code>.travis.yml</code>:</p>
<pre><code>deploy:
provider: npm
email: sa.alemdar@hotmail.com
api_key:
secure: MyApiKey
skip_cleanup: true
file_glob: true
file: "dist/**/*"
on:
tags: true
repo: salemdar/angular2-cookie
</code></pre>
| <npm><travis-ci> | 2016-03-18 13:48:01 | HQ |
36,086,529 | Understanding num_classes for xgboost in R | <p>I'm having a lot of trouble figuring out how to correctly set the num_classes for xgboost. </p>
<p>I've got an example using the Iris data</p>
<pre><code>df <- iris
y <- df$Species
num.class = length(levels(y))
levels(y) = 1:num.class
head(y)
df <- df[,1:4]
y <- as.matrix(y)
df <- as.matrix(df)
param <- list("objective" = "multi:softprob",
"num_class" = 3,
"eval_metric" = "mlogloss",
"nthread" = 8,
"max_depth" = 16,
"eta" = 0.3,
"gamma" = 0,
"subsample" = 1,
"colsample_bytree" = 1,
"min_child_weight" = 12)
model <- xgboost(param=param, data=df, label=y, nrounds=20)
</code></pre>
<p>This returns an error</p>
<pre><code>Error in xgb.iter.update(bst$handle, dtrain, i - 1, obj) :
SoftmaxMultiClassObj: label must be in [0, num_class), num_class=3 but found 3 in label
</code></pre>
<p>If I change the num_class to 2 I get the same error. If I increase the num_class to 4 then the model runs, but I get 600 predicted probabilities back, which makes sense for 4 classes. </p>
<p>I'm not sure if I'm making an error or whether I'm failing to understand how xgboost works. Any help would be appreciated. </p>
| <r><xgboost> | 2016-03-18 14:07:44 | HQ |
36,086,913 | compare one value with four tables | <p>I am trying to compare ssn with four tables to find any unmatched ssn. i need assistance with sql query. thanks in advance</p>
| <sql> | 2016-03-18 14:26:47 | LQ_CLOSE |
36,087,071 | How can I copy 1 specific commit to another branch ? | <p>I have 2 branches : </p>
<ul>
<li>branchA</li>
<li>branchB</li>
</ul>
<p>I checkout <code>branchB</code>, and fix a small thing while I am on that branch.</p>
<pre><code>commit f2c88cad3d7648cad9c12e724d09db0952abec63
Author: Name <email>
Date: Fri Mar 18 09:10:22 2016 -0400
Fix small bug on dashboard
</code></pre>
<p>Then, I do <code>git push origin branchB</code>
Which I should have did </p>
<p><code>git push origin branchA branchB</code> </p>
<p>Now, in branchB I have </p>
<pre><code>commit f2c88cad3d7648cad9c12e724d09db0952abec63
</code></pre>
<p>but I don't have it on branchA</p>
<p>How do I copy that <strong>1</strong> commit <code>f2c88ca</code> into my branchA as well ? </p>
<p>Any hints on this will be much appreciated ! </p>
| <git> | 2016-03-18 14:34:30 | HQ |
36,087,121 | How to ordering the the JSON data in a given format using Angular.js/Javascript | I need one help.I need to format some array of data using Angular.js/Javascript.I am explaining the code below.
var response=[{
day_id:1,
day_name:"Monday",
subcat_id:"2",
cat_id:"1",
comment:"hii"
}, {
day_id:1,
day_name:"Monday",
subcat_id:"1",
cat_id:"2",
comment:"hello"
}
{
day_id:2,
day_name:"Tuesday",
subcat_id:"3",
cat_id:"2",
comment:"hii"
}
]
I have the above given array.I need to convert it as per following format
var responseNew = {
data: [{
day_name: "Monday",
day_id:1
answers:[{
cat_id:1,
subcat_id:1,
comment:'hii'
},{
cat_id:1,
subcat_id:2,
comment:'hello'
}]
}, {
day_name: "Tuesday",
day_id:2
answers:[{
cat_id:3,
subcat_id:2,
comment:'hello'
}]
}, {
day_name: "Wednesday"
day_id:3
}, {
day_name: "Thursday"
day_id:4
}, {
day_name: "Friday"
day_id:5
}, {
day_name: "Saturday",
day_id:6
}, {
day_name: "Sunday"
day_id:7
}]
};
Here i want to convert my first array into the second format.Here one condition is if other day_id is not present its simple set the day name and day id in static as given above.Please help me.
| <javascript> | 2016-03-18 14:36:37 | LQ_EDIT |
36,087,173 | Containers are not linked with docker-compose version 2 | <p>I have a docker-compose file that I upgraded from version 1 to version 2.</p>
<p>It set ups a simple Selenium hub with a firefox node.</p>
<p>When I set it up as version 1 it launches fine. When I set it up with version 2 the ff container returns <code>"Not linked with a running Hub container"</code> and exits.</p>
<p>As I researched it and understood it , is that the linkage between the containers somehow suffers.</p>
<p>Is there a solution ?? Am I missing something ??</p>
<pre><code>version: '2'
services:
hub:
container_name: hub
image: selenium/hub
ports:
- "8080:4444" # HOST:CONTAINER
expose:
- "4444"
ff:
container_name: ff
image: selenium/node-firefox
links:
- hub
expose:
- "5555"
</code></pre>
| <docker><docker-compose> | 2016-03-18 14:38:49 | HQ |
36,087,262 | ggplot2 legend items in a single horizontal row | <p>This may seem like a stupid question, but I am a little confused.</p>
<p>It seems that the code I wrote and tested last week has now suddenly decided to change the output even though nothing in the code or the version of R or Rstudio has changed.</p>
<p>Previously when I drew a plot with ggplot2 and asked for the legend to appear at the bottom of the plot, it automatically oriented the items into a single horizontal row. Now when I run the same code it places the item in a number of 2-row columns.</p>
<p>Here's an example...</p>
<pre><code>mtcars$cyl <- (1:32)
subcars <- subset(mtcars, cyl<10)
subcars$cyl <- as.factor(subcars$cyl)
ggplot(subcars, aes(carb, mpg, group=cyl, colour=cyl)) +
geom_line() +
theme_classic() +
theme(plot.title = element_text(size = rel(2), face="bold", vjust=-4)) +
theme(legend.position = "bottom") +
theme(legend.direction = "horizontal") +
labs(title="Title")
</code></pre>
<p>As you can see, I have already tried adding in the line <code>theme(legend.direction = "horizontal")</code> but I still get a legend which displays the items in 5 2-row columns (yes, its not even just in two rows).</p>
<p>Now I can only assume that there has been some update that I was not aware of or something, so I'm willing to accept that I need to come up with a new strategy for dealing with this problem (which just wasn't a problem last week). Although I am a little bit confused about why my code has suddenly decided to stop working (any input on this welcome), I'm more interested in finding a fix for the immediate problem of my legend items being displayed in a strange configuration.</p>
| <r><ggplot2><legend> | 2016-03-18 14:42:36 | HQ |
36,087,839 | what is best way to save variable in compiler | i want save variable in bison and don't know what is best way to save variable.
value is string or int.
parser :
....
assignment : '$' identifier '=' exp {updateSymbolVal($2,$4); }
...
function :
void updateSymbolVal(char symbol,int val)
{
int bucket = computeSymbolIndex(symbol);
symbols[bucket] = val;
////printf("\n is: %s",symbols[bucket]);
}
how fix them to can give big string ?
please help me
tank you. | <c++><parsing><compiler-construction><bison><lexer> | 2016-03-18 15:07:51 | LQ_EDIT |
36,088,409 | Error 111 connecting to localhost:6379. Connection refused. Django Heroku | <p>I am able to run redis locally and everything works. </p>
<p>However when I deploy to heroku I get this error: </p>
<pre><code>Error 111 connecting to localhost:6379. Connection refused.
</code></pre>
<p>I have set up a Procfile with...</p>
<pre><code>web: gunicorn odb.wsgi --log-file -
worker: python worker.py
</code></pre>
<p>I have a worker.py file...</p>
<pre><code>import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL')
if not redis_url:
raise RuntimeError('Set up Redis To Go first.')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
if __name__ == '__main__':
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
</code></pre>
<p>A REDISTOGO_URL variable appears in the heroku config.</p>
<p>Redis to go is an installed add-on for my app. </p>
<p>Does REDISTOGO_URL have to be defined in settings.py? Why is heroku trying to connect to the local host when it is not even defined in worker.py? </p>
| <python><django><heroku> | 2016-03-18 15:33:59 | HQ |
36,088,972 | ASP.NET 4.5 in IIS | <p>How I can check which ASP.NET 4.5 install on IIS in C#. How to detect IIS version</p>
<p>tanks</p>
| <c#><asp.net><winforms><iis> | 2016-03-18 15:59:57 | LQ_CLOSE |
36,089,307 | How to get the first key (not value) of immutable.js map? | <p>How to get the first key (not value) of immutable.js map?</p>
<p>basically <code>myMap.first()</code> will return the value, but I am interested in the key...</p>
<p>I can do a forEach and store first, but must be a better way!</p>
<p>didn't see it in the docs, prob missing it... :/</p>
<p>tx</p>
<p>Sean</p>
| <immutable.js> | 2016-03-18 16:17:11 | HQ |
36,089,439 | Angular 2 Http testing multiple connections | <p>Can anyone help me with testing Http requests in Angular 2. I have a service that gets a stream from two http requests. How do I mock this behaviour in my test?</p>
<pre><code>loadData() {
return Observable.forkJoin(
this.http.get('file1.json').map((res:Response) => res.json()),
this.http.get('file2.json').map((res:Response) => res.json())
).map(data => {
return {
x: data[0],
y: data[1]
}
});
}
</code></pre>
<p>Here is my test code, I have tried to use an array of connections but I get an error message saying "Failed: Connection has already been resolved". I have left the body of the connections blank to avoid exposing sensitive data. </p>
<pre><code>describe('Test Load Init Data', () => {
it('should load Menu Zones and Menu Sections',
inject([XHRBackend, AppInitService], (mockBackend, appInitService) => {
console.log('Lets do some testing');
//first we register a mock response
mockBackend.connections.subscribe(
(connection:MockConnection) => {
return [
connection.mockRespond(new Response(
new ResponseOptions({
body: []
})
)),
connection.mockRespond(new Response(
new ResponseOptions({
body: []
})
))
];
});
appInitService.loadData().subscribe(data => {
expect(data.x.length).toBeGreaterThan(0);
expect(data.y.length).toBeGreaterThan(0);
});
}));
});
</code></pre>
| <angularjs><angular><angular2-testing> | 2016-03-18 16:24:04 | HQ |
36,090,136 | Differences in C++ in different platforms | I was unsure of how should I name this question. It's probably a noob question but anyway...<br>I don't really now why assigning values in `struct` in C++ does work in Linux(Ubuntu) but doesn't in Windows(I get an error compiling same program in windows)<br>It depends on compiler, yes? Or there is something else I should know?
[![It's just a simple example program.][1]][1]
[1]: http://i.stack.imgur.com/lAhrn.png | <c++><linux><windows><compiler-errors> | 2016-03-18 16:57:50 | LQ_EDIT |
36,090,215 | How to gracefully handle exceptions in Spring Security not handled by ControllerAdvice? | <p>I have recently implemented Spring Security in my Spring 4 / Hibernate Web application to handle logging in/out and different user roles. </p>
<p>After a lot of reading it appears to work pretty fine now, but I noticed that exceptions thrown due to a wrong Spring Security configuration were not handled gracefully using my custom handler but shown as an ugly Tomcat error page (showing HTTP Status 500 - UserDetailsService is required followed by a stacktrace). </p>
<p>Solving the particular error was not difficult (adding userDetailsService(userDetailsService) in the RememberMe configuration) but the fact remains that some exceptions thrown are not handled by the
ControllerAdvice shown below handling MaxUploadSizeExceededException and all other runtime exceptions:</p>
<pre><code>@ControllerAdvice
public class ExceptionHandlingControllerAdvice {
public static final String DEFAULT_ERROR_VIEW = "genericerror";
@ExceptionHandler(value = MaxUploadSizeExceededException.class)
public View maxUploadSizeExceededExceptionHandler(
HttpServletRequest req) throws IOException {
String redirectUrl = req.getRequestURL().toString();
RedirectView rv = new RedirectView(redirectUrl);
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(req);
if (outputFlashMap != null) {
outputFlashMap.put(KeyConstants.FLASH_ERROR_KEY, "Bestand is te groot");
}
return rv;
}
@ExceptionHandler(value = RuntimeException.class)
public View defaultErrorHandler(HttpServletRequest req, Exception e) {
RedirectView rv = new RedirectView("/error", true); //context relative
StackTraceElement[] steArray = e.getStackTrace();
StringBuilder stackTrace = new StringBuilder();
for (StackTraceElement element: steArray) {
stackTrace.append(element.toString() + "\n");
}
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(req);
if (outputFlashMap != null) {
outputFlashMap.put("url", req.getRequestURL());
outputFlashMap.put("excClassName", e.getClass().getName());
outputFlashMap.put("excMessage", e.getMessage());
outputFlashMap.put("excStacktrace", stackTrace.toString());
}
e.printStackTrace();
return rv;
}
}
</code></pre>
<p>But the exception thrown by the incomplete configured Security is probably not caught by this mechanism because the login POST request is intercepted by Spring Security before any controller method is called. I would like to show ALL exceptions in graceful way on a custom error page, also the ones thrown before a Controller comes into place.</p>
<p>I cannot find much information about that, all error handling techniques described in the Spring manual (<a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers" rel="noreferrer">http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-exceptionhandlers</a>) seems to use a Controller advice. </p>
<p>Is there a convenient way to handle ALL exceptions in a generic way? And makes that my Controller advice class to handle exceptions superfluous?</p>
| <spring-mvc><spring-security><error-handling> | 2016-03-18 17:01:48 | HQ |
36,091,659 | Using semi-colons to close functions in JavaScript. Necessary? | <p>When executing a function in JavaScript, I've always ended my code block with a semi-colon by default, because that's what I've been taught to do. Coming from Java it felt a bit unorthodox at first, but syntax is syntax.</p>
<pre><code>function semiColon(args) {
// code block here
};
</code></pre>
<p>or</p>
<pre><code>function sloppyFunction(args) {
// code block here
}
</code></pre>
<p>Lately I've been seeing more and more code where the developer left the semi-colon out after functions, but the intended code still executed normally. So are they actually required? If not, why is it common practice to include them? Do they serve another purpose?</p>
| <javascript><function> | 2016-03-18 18:21:29 | LQ_CLOSE |
36,091,667 | What is the difference between Seq and IndexedSeq/LinearSeq in Scala? | <p>In <a href="http://www.scala-lang.org/docu/files/collections-api/collections_5.html" rel="noreferrer">Scala Collection documentation</a>, there is some clue to this question:</p>
<blockquote>
<p>Trait Seq has two subtraits LinearSeq, and IndexedSeq. These do not add any new operations, but each offers different performance characteristics: A linear sequence has efficient head and tail operations, whereas an indexed sequence has efficient apply, length, and (if mutable) update operations. </p>
</blockquote>
<p>But this does not address me when to use <code>IndexedSeq</code> instead of <code>Seq</code>?
I need some real example of <code>IndexedSeq</code> or <code>LinearSeq</code> where these collections do better than <code>Seq</code>.</p>
| <scala><scala-collections><seq> | 2016-03-18 18:22:10 | HQ |
36,091,741 | Spotlight reveal animation from centre of page with CSS/jQuery? | <p>Does anyone know how I might make a circular 'reveal' effect, so that my DOM elements are revealed from the page centre with a circle getting bigger and bigger.</p>
| <javascript><jquery><css> | 2016-03-18 18:26:37 | LQ_CLOSE |
36,091,973 | Is there a way to disallow runtime errors to crash app on background thread? | <p>I'm running a method in this way</p>
<pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
...
})
</code></pre>
<p>I want this logic to avoid crashing app if something goes wrong inside. Is there any way to do so?</p>
<p>Please don't answer fix the bug if any, I'm talking about any potencial bug I haven't found. This runs on a timer to process data from server, if crashes, it will make app unusable since it will crash at start up. </p>
<p>App can live without this data processing in worst case, but crashing app on start up is much more worse since app can't be used at all.</p>
<p>I know Swift doesn't have a catch for unexpected exceptions but maybe there is a way to avoid background threads to crash app if things goes wrong</p>
| <ios><swift> | 2016-03-18 18:38:52 | LQ_CLOSE |
36,092,172 | How to implement the Python program in java language | <p>Python has the in operator which makes it simple. but how do i implement the below python concept in java since java doesnt have the in operator.
This is a Python program</p>
<pre><code>secret_word = "python"
correct_letters = "oy"
count = 0
while count < len(secret_word):
print(secret_word[count] if secret_word[count] in correct_letters else '_', end=" ")
count += 1
</code></pre>
| <java> | 2016-03-18 18:48:41 | LQ_CLOSE |
36,092,200 | get a php variable in java script function | <p>i have this dropdown list and i need to save it's value by javascript but i can't get the name of the php variable (select name ) into the function</p>
<p>drop down list :</p>
<pre><code> $i=0;
while($i<$counter)
{
$vname=$row['student_id'].'_'.$i;
echo"
<td>
<select name=".$vname.">
<option value="."0".">Choose one</option>
<option value="."1".">Add</option>
<option value="."2".">R</option>
<option value="."3".">TBR</option>
<option value="."4".">P</option>
</select>
</td>";
$i++;
}
</code></pre>
<p>java script function :</p>
<pre><code> <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
var item = window.localStorage.getItem('".$vname."');
$('select[name=".$vname."]').val(item);
$('select[name=".$vname."]').change(function() {
window.localStorage.setItem('".$vname."', $(this).val());
});
});
</script>
</code></pre>
| <javascript><php><jquery> | 2016-03-18 18:50:02 | LQ_CLOSE |
36,093,117 | A system to convert html page to a prettier one as a web service | <p>As the title is too vague to understand, let me explain.</p>
<p>This is a webpage of petal laws in Japan.<br>
<a href="http://law.e-gov.go.jp/htmldata/M40/M40HO045.html" rel="nofollow">http://law.e-gov.go.jp/htmldata/M40/M40HO045.html</a></p>
<p>This look gray, drab and not interesting, right? So I'd like to set up a web service to do a little job to convert this to "better" looking one. More colors, more indentations and even a feature that a user hovers the cursor over a word and sees a pop up saying the definition of the word. But the issue is, I don't know much about technology to achieve this goal.</p>
<ol>
<li>Is there a technology to achieve this.</li>
<li>If any, what is it called?</li>
</ol>
<p>Any help would be appreciated. Thanks.</p>
| <html><web-services><web> | 2016-03-18 19:52:15 | LQ_CLOSE |
36,093,376 | Combining audio and video tracks into new MediaStream | <p>I need to get create a MediaStream using audio and video from different MediaStreams. In Firefox, I can instantiate a new MediaStream from an Array of tracks:</p>
<pre><code> var outputTracks = [];
outputTracks = outputTracks.concat(outputAudioStream.getTracks());
outputTracks = outputTracks.concat(outputVideoStream.getTracks());
outputMediaStream = new MediaStream(outputTracks);
</code></pre>
<p>Unfortunately, this doesn't work in Chrome:</p>
<blockquote>
<p>ReferenceError: MediaStream is not defined</p>
</blockquote>
<p>Is there an alternative method in Chrome for combining tracks from separate streams?</p>
| <javascript><google-chrome><webrtc><chromium><web-audio-api> | 2016-03-18 20:09:37 | HQ |
36,093,638 | Unexpected block statement surrounding arrow body | <p>I'm using <code>"eslint-config-airbnb": "^6.1.0",</code> to keep my JavaScript clean. </p>
<p>My linter is unhappy with what seems to be legitimate code:</p>
<p><a href="https://i.stack.imgur.com/4cTob.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4cTob.png" alt="enter image description here"></a></p>
<p>It seems like this might be an <a href="https://github.com/eslint/eslint/issues/4353" rel="noreferrer">ongoing issue</a>. Does anyone have any suggestions for an OCD developer on how to address this in the meantime? Perhaps disabling this rule or otherwise?</p>
| <reactjs><ecmascript-6><eslint> | 2016-03-18 20:25:49 | HQ |
36,093,838 | how can I asynchronously map/filter an asynchronous iterable? | <p>Let's say I have an asynchronous iterable that I can pass over using <code>async for</code>, how then can I then map and filter it to a new asynchronous iterator? The following code which is an adaptation of how I'd do the same thing with a synchronous iterable doesn't work, since <code>yield</code> isn't allowed inside <code>async def</code>s.</p>
<pre><code>async def mapfilter(aiterable, p, func):
async for payload in aiterable:
if p(payload):
# This part isn't allowed, but hopefully it should be clear
# what I'm trying to accomplish.
yield func(payload)
</code></pre>
| <python><async-await><python-asyncio> | 2016-03-18 20:40:08 | HQ |
36,093,880 | if I have a collection of hashes with the same key and values, how do I add another value together | Say I've assigned the rows below to hashes. How do I add together the :amount values for a specific id number? (so for id: 1, I need the total= 9290+2262)
other_id: 1,amount: 9290,id: 1
other_id: 2,amount: 2262,id: 1
other_id: 3,amount: 9588,id: 2
other_id: 4,amount: 1634,id: 2
or even better, if I had a large collection of these. how would I write code so that it would find the id number with the maximum value of total (if total is the sum of all amount instances for a specific id number) | <ruby><enumerable> | 2016-03-18 20:43:07 | LQ_EDIT |
36,095,076 | Custom Authentication in ASP.Net-Core | <p>I am working on a web app that needs to integrate with an existing user database. I would still like to use the <code>[Authorize]</code> attributes, but I don't want to use the Identity framework. If I did want to use the Identity framework I would add something like this in the startup.cs file:</p>
<pre><code>services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireNonLetterOrDigit = false;
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
</code></pre>
<p>I'm assuming I have to add something else there, and then create some kind of class that implements a specific interface? Can somebody point me in the right direction? I'm using RC1 of of asp.net 5 right now.</p>
| <c#><asp.net><authentication><asp.net-core><asp.net-core-mvc> | 2016-03-18 22:11:45 | HQ |
36,095,594 | Displaying text when hovering over first list item in a un ordered list | <p>If I have a li inside a ul and some hidden text on a page, how can I show that text when the user hovers over the first li in the ul?</p>
<p>I don't care if this is in CSS or JS, the text just has to appear only when hovering on the first itel in the list and no others. So when I hover over coffee, "hidden text" is visible</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<label style="display: none">hidden text</label></code></pre>
</div>
</div>
</p>
| <javascript><jquery><html><css> | 2016-03-18 22:56:11 | LQ_CLOSE |
36,097,085 | How to display a calendarView in ios? | <p>I am new to iOS.I want to let the users to pick a date from a calendar view. What is the easiest approach to do that?</p>
| <ios><swift> | 2016-03-19 02:18:22 | LQ_CLOSE |
36,097,397 | a warning about func unc createDirectoryAtURL(value of the type '()' ) | <p>I am learner on iOS Development,today i try to code something<a href="http://i.stack.imgur.com/Xf52o.png" rel="nofollow">enter image description here</a> about FileManger,but this method return a type '()',how can i to resolve it?</p>
<p>the warning code as follow:</p>
| <ios><swift><nsfilemanager> | 2016-03-19 03:14:11 | LQ_CLOSE |
36,097,527 | How to retrieve Medium stories for a user from the API? | <p>I'm trying to integrate Medium blogging into an app by showing some cards with posts images and links to the original Medium publication.</p>
<p>From Medium API docs I can see how to retrieve publications and create posts, but it doesn't mention retrieving posts. Is retrieving posts/stories for a user currently possible using the Medium's API?</p>
| <medium.com> | 2016-03-19 03:38:24 | HQ |
36,097,827 | Set date() to midnight in users timezone with moment.js | <p>I use moment.js to display a UTC date in the users local timezone:</p>
<pre><code>var date = new Date(Date.UTC(2016,03,30,0,0,0));
var now = new Date();
var diff = (date.getTime()/1000) - (now.getTime()/1000);
var textnode = document.createTextNode(moment(date).format('dddd, DD.MM.YYYY') + ' a las ' + moment(date).format('HH:mm A'));
document.getElementsByClassName("date")[0].appendChild(textnode.cloneNode(true));
</code></pre>
<p>I later use the <code>diff</code> variable to show a countdown timer.</p>
<p>I would like to show a different countdown timer to everyone in their local time zone. (Using the difference till its midnight in their time zone, not in UTC)</p>
<p>But I am struggeling to get it work. Instead of using <code>var date = new Date(Date.UTC(2016,03,30,0,0,0));</code> I probably need to use some function of moment.js that gives me till midnight in the users time zone.</p>
<p>The best example would be new years eve. If I use UTC everyone would have the same counter (9 hours left) but in different parts of the world this wouldn't make sense. For someone in australia it should be 2 hours left, and for someone in the US 14 hours.</p>
| <javascript><date><datetime><momentjs> | 2016-03-19 04:28:54 | HQ |
36,098,226 | Explanation for issues of type "ResourceCycle": when generate signed Apk | <p>I am getting error after update to appcompat-v7:24.0.0-alpha1 on generating the signed apk.</p>
<pre><code>Error:Error: Style Resource definition cycle: TextAppearance.AppCompat.Light.SearchResult.Title => TextAppearance.AppCompat.SearchResult.Title => TextAppearance.AppCompat.SearchResult.Title [ResourceCycle]
</code></pre>
| <android> | 2016-03-19 05:28:09 | HQ |
36,098,947 | How does Tensorflow support Cuda streams? | <p>Does Tensorflow utilize Cuda streams automatically for concurrent execution of the computation graph on a single GPU or should streams be assigned manually to ops/tensors ?</p>
| <tensorflow> | 2016-03-19 07:11:38 | HQ |
36,099,244 | How to add an HTTP header to all Django responses | <p>I'd like to add a few headers to all responses that my Django website returns. Is there a way to do this (besides adding a wrapper to the <code>render</code> function)?</p>
| <django><http><http-headers> | 2016-03-19 07:45:32 | HQ |
36,099,385 | Fisher exact test taks so long in R :( | My table has 770,000 rows and
what I did is
> mydata <- dbGetQuery(mydb, "select * from table")
> mydata$pvalue <- apply(as.matrix(mydata[, c(3,5,4,6)]), 1, function(x) fisher.test(matrix(x, nrow=2))$p.value)
to get pvalues.
But it takes so long. (it has been over 24hours and it is still running)
Should I use other method? | <r><performance><statistics><chi-squared> | 2016-03-19 08:04:19 | LQ_EDIT |
36,099,671 | Django Convert ID to slug | <p>Im new to django and wanted to <strong>convert id/pk to slug</strong>, I wanted to make <strong>url to be friendly or easy to understand</strong></p>
<p>Wanted to make url <code>http://127.0.0.1:8000/1/</code> to <code>http://127.0.0.1:8000/hello/</code></p>
<p>Model.py</p>
<pre><code>class Post(models.Model):
title=models.CharField(max_length=200)
description=models.TextField(max_length=10000)
pub_date=models.DateTimeField(auto_now_add=True)
comments=models.CharField(max_length=200, blank=True)
slug = models.SlugField(max_length=40, unique=True)
def __unicode__(self):
return self.title
def description_as_list(self):
return self.description.split('\n')
</code></pre>
<p>admin.py</p>
<pre><code>class PostAdmin(admin.ModelAdmin):
list_display=['title','description']
prepopulated_fields = {'slug': ('title',)}
class Meta:
model = Post
admin.site.register(Post,PostAdmin)
</code></pre>
<p>urls.py</p>
<pre><code>urlpatterns = [
url(r'^$', views.PostListView.as_view(),name='home'),
url(r'^(?P<slug>[\w-]+)/$', views.detail, name='detail'),
]
</code></pre>
<p>views.py</p>
<pre><code>class PostListView(ListView):
model = Post
template_name = 'blog_post.html'
queryset = Post.objects.order_by('-pub_date')
paginate_by = 2
def detail(request, id):
posts = Post.objects.get(id=id)
return render(request, "blog_detail.html", {'posts': posts,})
</code></pre>
<p>Templates</p>
<pre><code>{% for threads in object_list %}
<p class="blog-post-title"><a href="{% url 'detail' slug=threads.id %}">{{ threads.title }}</a></p>
<hr />
{% endfor %}
</code></pre>
<p>Following <strong>error</strong> is obtained by doing so...What more changes to be
<a href="https://i.stack.imgur.com/1Dh8g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1Dh8g.png" alt="enter image description here"></a></p>
<p>Any help is appreciated to make url readable. Thanks in davance</p>
| <python><django> | 2016-03-19 08:42:17 | LQ_CLOSE |
36,100,143 | How Create array with uniq key using php | <p>How Create Array like this.</p>
<pre><code>array(34) {
[0]=> object(stdClass)#11 (2)
{ ["id"]=> string(2) "11" ["name"]=> string(4) "AAAAA" }
[1]=> object(stdClass)#12 (2)
{ ["id"]=> string(2) "12" ["name"]=> string(14) "BBBBB" }
}
</code></pre>
<p>the array I get from database and i use for select option, but i wont create manualy in code how make the array like that.</p>
<p>this my code.</p>
<pre><code>$OPT_name = array('id'=>'0','name'=>'-Pilih-','id'=>'AAAAA','name'=>'BBBBB')";
var_dump($OPT_name);
exit;
</code></pre>
<p>but can't like example in a above.</p>
| <php><arrays> | 2016-03-19 09:41:32 | LQ_CLOSE |
36,100,254 | How can I make a div take parent div's end as its zero position for start? | I created a profile dialog body like this:
`
<div style="background-color: white;color: black;border-radius: 2px; position: absolute; top: 52px; right: 10px; padding: 2px">
<div style="width: 0;
height: 0;
border-style: solid;
border-width: 0 10px 15px 10px;
border-color: transparent transparent #ffffff transparent;
position: relative;
top: -10px;
right: -165px">
</div>`
I want to place child little triangle div always 10-20px far away from right end of parent div. How I can make second little triangle div take its start position on right from the end of parent div? | <html><css> | 2016-03-19 09:55:40 | LQ_EDIT |
36,101,403 | How do I extract and view cookies from Android Chrome? | <p>Is there any way for me to get and read cookies from my Android Chrome browser? </p>
<p>Thank you.</p>
| <android><google-chrome> | 2016-03-19 11:56:53 | HQ |
36,102,924 | Why does this doesn't work? (os.makedirs) | Please do help me in solving out the below code and say why is the os.makedirs doesnot work???
import os,pprint,sys
**while True:
print()
oq=input('Press the first directory: ')
print()
print()
ow=input('Press the next directory/name: ')
print()
p2=input('Continue with next directory? yes or no: ').lower()
if p2=='no':
break
print()
oe=input('Press the next directory/name: ')
print()
p3=input('Continue with next directory? yes or no: ').lower()
if p3=='no':
break
print()
oee=input('Press the next directory/name: ')
print()
p4=input('Continue with next directory? yes or no: ').lower()
if p4=='no':
break
print()
ot=input('Press the next directory/name: ')
print()
p5=input('Continue with next directory? yes or no: ').lower()
if p5=='no':
break
print()
oy=input('Press the next directory/name: ')
print()
p6=input('Continue with next directory? yes or no: ').lower()
if p6=='no':
break
print()
ou=input('Press the next directory/name: ')
print()
p7=input('Continue with next directory? yes or no: ').lower()
if p7=='no':
break
print()
if p2=='no':
os.makedirs(oq+'\\'+ow)
if p3=='no':
os.makedirs(oq+'\\'+ow+'\\'+oe)
if p4=='no':
os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee))
if p5=='no':
os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee+'\\'+ot)
if p6=='no':
os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee+'\\'+ot+'\\'+oy)
if p7=='no':
os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee+'\\'+ot+'\\'+oy+'\\'+ou)
ppp=input('Wannna continue???')
if ppp=='no':
sys.exit()** | <python> | 2016-03-19 14:25:41 | LQ_EDIT |
36,103,299 | In an Android Gradle build, how to exclude dependencies from an included jar file? | <p>In my Android project, I use a library that comes as a jar.
I include it in the dependencies section like so:</p>
<pre><code>dependencies {
...
compile files('libs/thethirdpartylibrary.jar')
...
}
</code></pre>
<p>I also want to use the okhttp library, which I include like this:</p>
<pre><code>compile ('com.squareup.okhttp:okhttp:2.7.5')
</code></pre>
<p>(This particular version of okhttp depends on okio 1.6.0.)</p>
<p>The problem is that the thirdparty jar library depends on okio v0.9.0 and what's worse, bundles it.</p>
<p>As a result, I get a dex conflict error at build time.</p>
<p>I was able to resolve this by manually removing okio from the jar file and this seems to work. But I'm wondering if there's a way to do this in gradle.</p>
<p>My question: Can I remove bundled, transitive ( <- I hope I'm using this word the right way) dependencies from an included jar during build-time with gradle?</p>
| <android><gradle><jar><android-gradle-plugin> | 2016-03-19 15:02:40 | HQ |
36,103,845 | Run a compiled C program on a computer where the headers don't exist | <p>I have written a code which includes the Windows.h header, and compiled it using Visual Studio.</p>
<p>I have then tried to run the EXE file alone on my other computer, which appears to lack the specified header.</p>
<p>How can I run it on the other computer without having to install VS?</p>
| <c++><c><compilation><execute> | 2016-03-19 15:56:39 | LQ_CLOSE |
36,103,904 | history.pushState in Chrome make favicon request | <p><strong>code :</strong></p>
<pre><code>var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname +"?"+ queryStr;
window.history.pushState({path:newurl},'',newurl)
</code></pre>
<p><strong>current scenario :</strong></p>
<p>everytime when <strong><code>window.history.pushState()</code></strong> is invoked favicon requests occur rapidly.It makes network request for favicon on every call of this function.</p>
<p><strong>expected scenario :</strong></p>
<p>favicon should be loaded only once on page load, I would not expect the favicon load on every request of <strong><code>window.history.pushState()</code></strong>.</p>
<p><strong>favicon paths are link like this in HTML page :</strong></p>
<pre><code><!-- Favicon -->
<link rel="icon" type="image/png" href="../img/icon/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="../img/icon/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="../img/icon/favicon-96x96.png" sizes="96x96">
</code></pre>
<p>Any immediate help will be highly appreciable. Thanks</p>
| <javascript><html><favicon><pushstate> | 2016-03-19 16:03:14 | HQ |
36,103,988 | Why do always must to read the last element we write with C unions? | I'm reading some slides on `enum`s and `unions`, and one slide says:
> You must always read the last element you write.
and then there's the following code:
union Value {
int int_value;
float float_value;
char *str_value;
};
int main(int argc, char *argv[]) {
union Value v;
v.str_value = "ciao";
v.int_value = 100;
printf("v = %s\n", v.str_value); /* undefined behavior! */
}
What does it mean that we have always to read the last element we write? Why accessing the field `str_value` of the union `v` is undefined behaviour? | <c><undefined-behavior> | 2016-03-19 16:10:32 | LQ_EDIT |
36,104,053 | How to get second saturday of a month using shell/perl script? | <p>Please provide me the scripting code to find out the second saturday in a month</p>
| <perl><shell> | 2016-03-19 16:15:22 | LQ_CLOSE |
36,104,136 | jslint --edition=latest Unexpected ES6 feature. const | <p>I'm trying to use node-jslint <a href="https://github.com/reid/node-jslint" rel="noreferrer">https://github.com/reid/node-jslint</a> in order to keep my code clean </p>
<p>I've got a const in my nodejs script, but jslint says it isn't valid ES6 code</p>
<pre><code> Unexpected ES6 feature.
const pdPersonsFilterId = process.argv[2]; // Line 10, Pos 0
</code></pre>
<p>Here is the command I use in the console</p>
<pre><code>jslint --edition=latest index.js
</code></pre>
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const</a> it possible to use global constants.</p>
<p>Why does jslint does not consider this code to be valid?</p>
| <javascript><node.js><constants><ecmascript-6><jslint> | 2016-03-19 16:23:39 | HQ |
36,104,243 | Different behavior between String.value0f and Character.toString in Java | <p>In the following example, this program snippet does not compile, but if we replace the method <code>Character.toString(char)</code> by <code>String.valueOf(char)</code>, everything is fine. What is the issue why Character.toString here ? In the documentation, these methods seem to have the same behavior. Thanks for explanation.</p>
<pre><code> public static void main (String args[]) {
String source = "19/03/2016 16:34";
String result = Character.toString(source.substring(1,3));
System.out.print(result);
}
</code></pre>
| <java><string><type-conversion> | 2016-03-19 16:33:31 | LQ_CLOSE |
36,104,633 | I am working with an app which,I have another team member | <p>I am developing an ios, app,it is in swift language.I have another team member.The app has many pages which we decided to program seprately.How can I integrate both of our pages in our app?Kindly help.</p>
| <ios><swift> | 2016-03-19 17:08:18 | LQ_CLOSE |
36,105,117 | string in a sequence in python | <p>I am solving a problem in codechef which is </p>
<blockquote>
<p>Chef has a sequence of N numbers. He like a sequence better if the sequence contains his favorite sequence as a substring.
Given the sequence and his favorite sequence(F) check whether the favorite sequence is contained in the sequence</p>
<p>Input</p>
<p>The first line will contain the number of test cases and are followed
by the cases. Each test case consists of four lines: The length of
the sequence, the sequence N,the length of F and the sequence F </p>
<p>Output</p>
<p>Print "Yes" if the sequence contains the favourite sequence int it
otherwise print "No" Constraints</p>
</blockquote>
<pre><code>1<=T<=10
1 1
Input:
2
6
1 2 3 4 5 6
3
2 3 4
6
22 5 6 33 1 4
2
4 15
Output:
Yes
No
</code></pre>
<p>to this I wrote
`</p>
<pre><code>for _ in xrange(int(raw_input())):
raw_input()
s = raw_input()
raw_input()
f = raw_input()
print "Yes" if f in s else "No"`
</code></pre>
<p>it returns correct result (as far as I have checked ) bu the grader returns wrong. why is this wrong ?</p>
| <python><python-2.7> | 2016-03-19 17:51:49 | LQ_CLOSE |
36,105,425 | Show hidden images on website | <p>How to see hidden images on this javascript game. This is timing memory game, and uses javascript to hide images after 2 clicks. Is there any extension or any way in console to edit the script to not hide images.
<a href="https://apps.pixel.mk/kviz-bimilk/memorija.php" rel="nofollow">https://apps.pixel.mk/kviz-bimilk/memorija.php</a> </p>
| <javascript><php> | 2016-03-19 18:20:41 | LQ_CLOSE |
36,105,850 | rand() and RAND_MAX giving different values depending upon the datatype | <p>Here when I print the value of x its giving zero as output.Whereas when I print y, I am getting correct value(a random number between 0 and 1),the typecasting is the problem it seems.Why do i need to typecast it? </p>
<pre><code>double x,y;
x=rand()/RAND_MAX;
printf("X=%f\n",x);
y=(double)rand()/RAND_MAX;
printf("Y=%f",y);
</code></pre>
<p>Output</p>
<pre><code>X=0.000000
Y=0.546745
</code></pre>
| <c><random> | 2016-03-19 18:59:38 | LQ_CLOSE |
36,105,854 | Xcode Can't Recognize my ViewController | <p><code>SignUpViewController2</code> - I have already identified this in Xcode. Xcode says "use of undeclared type <code>SignUpViewController2</code>". I don't know why Xcode doesn't know what SignUpViewController2 is.</p>
<p><a href="https://i.stack.imgur.com/5RiG2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5RiG2.png" alt="https://i.gyazo.com/b9bd7091467e71bb8ad5a73e840a1f9b.png"></a>
<a href="https://i.stack.imgur.com/h163a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h163a.png" alt="enter image description here"></a></p>
| <ios><xcode><swift> | 2016-03-19 19:00:24 | LQ_CLOSE |
36,106,066 | Changing to uppercase letters using ASCII | <p>I have to create a function that changes lower case letters to upper case letters using only the ord and chr functions. </p>
<p>This is what I have so far, but the problem is it is not returning all the letters, only the first letter.</p>
<pre><code>def changeToUpperCase(text):
for i in text:
i = ord(i) - 32
text = chr(i)
return text
def main():
text = input("Please type a random sentence.")
text = changeToUpperCase(text)
print("Step 2 -> ", text)
</code></pre>
| <python><ascii><chr><ord> | 2016-03-19 19:19:44 | LQ_CLOSE |
36,106,098 | Android espresso test NavigationView | <p>I am writing some espressotests for an appplication I recently made.
I'm using a NavigationView inside a DrawerLayout as sliding menu.</p>
<p>I managed to open the drawer this way:</p>
<pre><code> onView(withId(R.id.drawer_layout)).perform(open());
</code></pre>
<p>This works so now I am trying to perform a click on a menuitem in the NavigationView. </p>
<pre><code>onView(withId(R.id.nav_register))..
</code></pre>
<p>can not find the view. I tried several things but I can't find a way to retrieve the menuitem view. This is the way the items are assigned in the code:</p>
<pre><code> <android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</code></pre>
<p>and activity_main_drawer.xml</p>
<pre><code><group android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_menu_home"
android:title="Home" />
<item
android:id="@+id/nav_register"
android:icon="@drawable/ic_menu_register"
android:title="Registreer" />
<item
android:id="@+id/nav_login"
android:icon="@drawable/ic_menu_login"
android:title="Log in" />
<item
android:id="@+id/nav_play"
android:icon="@drawable/ic_menu_play"
android:title="Speel sessie" />
<item
android:id="@+id/nav_logout"
android:icon="@drawable/ic_menu_logout"
android:title="Log uit" />
</group>
</code></pre>
<p>I read something about NavigationViewMenuItem is a private member and not accessible. Can someone help me out?</p>
<p>Greets!
Shenno </p>
| <android><android-navigationview><android-espresso> | 2016-03-19 19:22:11 | HQ |
36,106,343 | super slow node npm commands | <p>I have node v.4.4 with npm v.2.14.20 (default bundled with windows installer). My OS: Windows 7 64bit. Hardware: Dell laptop, 16GB RAM, SSD, core i7.</p>
<p>I'm facing a problem with extremely slow npm. For example when I want to check version of node with</p>
<pre><code>node --version
v4.4.0
</code></pre>
<p>I receive output <code>4.4.0</code> within miliseconds.
But when I type</p>
<pre><code>npm --version
</code></pre>
<p>I need to wait ridiculous <strong>8-15 seconds</strong> to receive an output! And it's the same with every single npm command. </p>
<p>What i tried: update npm (to most recent 3.x version), update node to 5.9.0, i also tried my luck with x86 versions - same thing.</p>
<ol>
<li>Any clues what can cause such "sleep" (it's only with <code>npm</code>, every other cmd command works fine, system works fine)?</li>
<li>I will appreciate any tips how I can debug this thing to see what's going on under the hood</li>
</ol>
| <node.js><windows><cmd><npm> | 2016-03-19 19:45:52 | HQ |
36,106,349 | convert Java to Json Array please assist | I have to convert an Arraylist of users to from java to Json
I figured out how to get the
user to convert I don't know how to use the syntax for the array
This is in the driver:
// Convert a User to JSON
String testStr = JsonUserConverter.convertUserToJson(bob);
System.out.println(testStr);
// Convert JSON string to a User
User testUser = JsonUserConverter.convertJsonToUser(jsonUserString);
System.out.println(testUser);
// Convert an ArrayList of Users to JSON
and I have to populate this
public static String convertUsersArrayToJson(ArrayList<User>users){}
with my User data from my User class. I only just learned about ObjectMapper. I assume there's something in my library to convert but I don't know. Help. | <java><arrays><json> | 2016-03-19 19:46:23 | LQ_EDIT |
36,106,532 | Laravel difference between Events, Listeners, Jobs, Queues | <p>It sounds extremely confusing to me, what are the differences? Can someone please do an ELI5?</p>
| <php><laravel> | 2016-03-19 20:04:42 | HQ |
36,106,588 | Reading from txt file to ArrayList | Why it does not like parseInt? How to fix it? Can someone pls help me out
import java.lang.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.List;
import java.lang.*;
public class Table {
static class Data
{
private String name = "";
private int num = 0;
public Data(String name, int num)
{
this.name = name;
this.num = num;
}
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
public String toString()
{
return name + " " + num;
}
}
public static void main(String[] args) throws IOException
{
List<Data> table = new ArrayList<Data>();
try
{
String filename= ""C:\\input.txt";
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
while(line != null)
{
String[] tokens = line.split("[ ]+");
String tempname = tokens[0];
int tempnum = Integer.parseInt(tokens[1]);
Data temp = new Data(tempname,tempnum);
table.add(temp);
line = reader.readLine();
}
reader.close();
}
catch(FileNotFoundException n)
{
System.out.println("file not found");
}
catch(IOException a)
{
a.printStackTrace();
}
for(Data n:table)
{
System.out.println(n);
}
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method parseInt(String) is undefined for the type Integer
at Table.main(Table.java:58)
| <java><compiler-errors><undefined><parseint> | 2016-03-19 20:09:15 | LQ_EDIT |
36,106,716 | Make condition in one line? | <p>Usually I made the <code>if/else</code> condition like this:</p>
<pre><code>if(empty($data['key']))
{
$err = "empty . $key ";
}
</code></pre>
<p>but I saw that there is the <a href="https://davidwalsh.name/php-shorthand-if-else-ternary-operators" rel="nofollow">ternary operator.</a></p>
<p>I really don't understand how this works.. Someone could show me an example? How can I convert this condition in the ternary logic?</p>
| <php> | 2016-03-19 20:23:02 | LQ_CLOSE |
36,106,730 | Why function is not returning negative value in C? | <p>I am writing this code to return a value which I will pass through the parameter of the function and print that value.
here is my code: </p>
<pre><code>#include<stdio.h>
int abs(int x)
{
if(x<0)
return x;
}
int main()
{
int x = -6;
printf("Value of abs is %d\n",abs(x));
return 0;
}
</code></pre>
<p>This code giving me the output:</p>
<blockquote>
<p>Value of abs is 6</p>
</blockquote>
<p><em>Why this code is not returning -6 ?</em> </p>
<p>how to solve this ? </p>
<p>thanks in advance :)</p>
| <c> | 2016-03-19 20:24:35 | LQ_CLOSE |
36,107,400 | Composer update memory limit | <p>I need to run composer update at my hosting so I log in with ssh and try to run comand:</p>
<pre><code>composer update
</code></pre>
<p>inside /www folder where I have laravel and composer instalation</p>
<p>but I get error:
<a href="https://i.stack.imgur.com/FGC01.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FGC01.png" alt="enter image description here"></a></p>
<p>in contact with my hosting provider they tell me to run command:</p>
<pre><code>php -d memory_limit=512M composer update
</code></pre>
<p>I run this command but I get: "Could not open file: composer" </p>
<p>What to do? What is the soluton here?</p>
| <php><laravel><ssh><composer-php> | 2016-03-19 21:28:52 | HQ |
36,108,110 | TypeScript for ... of with index / key? | <p>As described <a href="https://basarat.gitbooks.io/typescript/content/docs/for...of.html">here</a> TypeScript introduces a foreach loop:</p>
<pre><code>var someArray = [9, 2, 5];
for (var item of someArray) {
console.log(item); // 9,2,5
}
</code></pre>
<p>But isn't there any index/key? I would expect something like:</p>
<pre><code>for (var item, key of someArray) { ... }
</code></pre>
| <for-loop><foreach><typescript> | 2016-03-19 22:43:40 | HQ |
36,108,377 | How to use the split function on every row in a dataframe in Python? | <p>I want to count the number of times a word is being repeated in the review string</p>
<p>I am reading the csv file and storing it in a python dataframe using the below line</p>
<pre><code>reviews = pd.read_csv("amazon_baby.csv")
</code></pre>
<p>The code in the below lines work when I apply it to a single review. </p>
<pre><code>print reviews["review"][1]
a = reviews["review"][1].split("disappointed")
print a
b = len(a)
print b
</code></pre>
<p>The output for the above lines were </p>
<pre><code>it came early and was not disappointed. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.
['it came early and was not ', '. i love planet wise bags and now my wipe holder. it keps my osocozy wipes moist and does not leak. highly recommend it.']
2
</code></pre>
<p>When I apply the same logic to the entire dataframe using the below line. I receive an error message</p>
<pre><code>reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
</code></pre>
<p>Error message: </p>
<pre><code>Traceback (most recent call last):
File "C:/Users/gouta/PycharmProjects/MLCourse1/Classifier.py", line 12, in <module>
reviews['disappointed'] = len(reviews["review"].split("disappointed"))-1
File "C:\Users\gouta\Anaconda2\lib\site-packages\pandas\core\generic.py", line 2360, in __getattr__
(type(self).__name__, name))
AttributeError: 'Series' object has no attribute 'split'
</code></pre>
| <python><string><dataframe> | 2016-03-19 23:13:31 | HQ |
36,108,390 | What is wrong with my java code, it won't compile? | <p>Okay so I typed a java code to do a simple function. Every time I enter it won't let me compile. Where is my error in this code?</p>
<pre><code>public int add(int a, int b) {
int sum;
sum = a + b;
}
public static void main(String[] args){
int x = 5;
double y = 7;
int total = add(x,y);
System.out.println(total);
}
</code></pre>
| <java><class><public> | 2016-03-19 23:15:39 | LQ_CLOSE |
36,108,391 | Rails - Add Column Name That Is An Array Of Date Ranges | <p>For my final project in my Intro To Ruby on Rails class, I have to make an e-commerce website. However, I decided to go more advanced than the scope of the class, so instead of the quantity of a service, I want that service to have an array of Date appointments.</p>
<p>For example, if this is a massage service, I need each massage service to have "appointment" attributes so the user can know the following:</p>
<p>"This massage service has the several open appointment ranges:</p>
<p>03/21/2016 from 3:00pm to 5:00pm</p>
<p>03/22/2016 from 2:00pm to 4:00pm</p>
<p>03/23/2016 from 12:00pm to 2:00pm"</p>
<p>How would I get this done?</p>
| <ruby-on-rails><ruby> | 2016-03-19 23:15:40 | LQ_CLOSE |
36,108,478 | How to trigger a Google Apps Script once an email get in the inbox? | <p>I have created a Google Apps Script that checks if an email has an attachment then send it to another email address.</p>
<p>It's working fine, but I would like to create a trigger that would launch the script as soon as a new email arrives in the inbox.</p>
<p>I have been able to create a trigger that launch the script every hour, but it's not what I want</p>
| <google-apps-script><gmail> | 2016-03-19 23:23:55 | HQ |
36,108,621 | Get all HTML tags with Beautiful Soup | <p>I am trying to get a list of all html tags from beautiful soup.</p>
<p>I see find all but I have to know the name of the tag before I search.</p>
<p>If there is text like </p>
<pre><code>html = """<div>something</div>
<div>something else</div>
<div class='magical'>hi there</div>
<p>ok</p>"""
</code></pre>
<p>How would I get a list like </p>
<pre><code>list_of_tags = ["<div>", "<div>", "<div class='magical'>", "<p>"]
</code></pre>
<p>I know how to do this with regex, but am trying to learn BS4</p>
| <python><html><beautifulsoup> | 2016-03-19 23:43:29 | HQ |
36,108,640 | Webpack Karma Istanbul Remapping for TypeScript | <p>I'm developing a client-side app and I'm having trouble with creating the right Karma configs. Right now, I have my setup as follows:</p>
<p>Webpack: Using ts-loader, compiles TypeScript, assets etc.</p>
<p>Karma: Using the webpack plugin, loads the Webpack config (which uses ts-loader), then runs all unit tests with Jasmine + PhantomJS</p>
<p>The unit tests all run fine, but I haven't figured out a way to handle the webpack istanbul remapping. Karma-webpacks seems to not be generating source maps to allow the remapping to happen. Any pointers would be appreciated!</p>
<p>Karma Config:</p>
<pre><code>var webpackConfig = require("./webpack.config.js");
delete webpackConfig.entry;
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// Non-automatically bundled libraries
'app/client/js/lib/easeljs.min.js',
'app/client/js/lib/tweenjs.min.js',
// Entry File
'app/client/js/index.ts',
'app/client/html/**/*.html',
// Test files and dependencies
'node_modules/angular-mocks/angular-mocks.js',
'test/client/**/*.spec.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'**/*.html': ['ng-html2js'],
'app/client/js/index.ts': ['webpack', 'sourcemap', 'coverage']
},
ngHtml2JsPreprocessor: {
cacheIdFromPath: function (filepath) {
// Remaps the path for Karma webpack
return '/_karma_webpack_//' + filepath.replace(/^.*[\\\/]/, '');
},
moduleName: 'templates'
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter: {
dir: 'build/client/test/coverage/',
reporters: [
{
type: 'json',
subdir: '.'
}
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Concurrency level
// how many browser should be started simultaneously
concurrency: Infinity
})
};
</code></pre>
| <typescript><code-coverage><webpack><istanbul> | 2016-03-19 23:45:36 | HQ |
36,109,146 | UNIX: Too many spaces | I have code with two variables in echo. I don't know why it prints before $AEXT spaces even though I have just one space in code.
echo " Average file size .$ext: $AEXT"
Files .tar: 1 | <bash><unix><posix><dash-shell> | 2016-03-20 01:04:51 | LQ_EDIT |
36,109,671 | C# class error...please help? thanks | "Member names cant be in the same as their enclosing type". How would i re-arrange this code to make it run?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace works
{
class Enemy : Character
{
Character Hero = new Character();
Character Enemy = new Character();
public override void Die()
{
Console.WriteLine("[0] has killed the enemy!", mST_Name);
}
public override void TakeDamage()
{
Enemy.mIN_HitPoints -= Hero.mIN_Strength;
Console.WriteLine("Your enemy has been hit and has {0} HP left!", mIN_HitPoints);
if (mIN_HitPoints == 0)
{
Die();
}
}
}
}
The point of this code is to simulate a RPG style game. Thanks for the help :) | <c#> | 2016-03-20 02:39:38 | LQ_EDIT |
36,109,888 | taking information from a structure and using in another function | <p>I need to know if I can call the information that is in tire_pressure in the structure and use it in another function? Basically I am not sure how to call it from one to the other. Do I have to declare the function in tireTest? Which is the function I am trying to access the tire_pressure information at. Thanks for the help</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[0];
int pressure_change[0];
}typedef tires;
// Prototypes
void getTireInformation(tires*, int);
void tirePressure(tires*, int);
void tireTest(tires*, int);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
srand(time(NULL));
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
tireTest(ptire, 4);
return 0;
}// end main
//============================
void getTireInformation(tires* ptire, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("please enter Make for the tire: \n");
scanf("%s", &(ptire + i) ->Manufacturer);
}
printf("all tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n",(ptire +i) ->Manufacturer);
}//end getTireInformation
//=======================================================================
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 35;
for (i = 0; i < size; i++)
{
(ptire + i) ->tire_pressure[0] = rand() % (max - min + 1) + min;
printf("The Tire pressure is: ");
printf("%d\n",(ptire + i) -> tire_pressure[0]);
}// end for
}// end tirePressure
//==============================================================
void tireTest(tires* ptire, int size)
{
int i = 0;
int min = 2;
int max = 5;
int change[0] = {0};
i++;
for (i = 0; i < size; i++)
{
change[0] = rand() % (max - min + 1) + min;
//(ptire + i) -> pressure_change[0] = rand() % (max - min + 1) + min;
printf("Pressure change from test %d: %d\n",i + 1, change[0]);
//(ptire + i) -> pressure_change[0] = change[0] + tirePressure;
//printf("%d\n", (ptire +i) -> pressure_change);
}// end for
}
</code></pre>
| <c><function><structure> | 2016-03-20 03:23:00 | LQ_CLOSE |
36,109,941 | A vector container declared in a different source file used in an "if" statement is out of scope? | I've created a source file that contains a number of data structures (maps, vector, array). Its header file is `#included` in the main-file.
The main file looks like this:
#include "src1.h" //Where monkey() and vector<int> bar are declared
main()
{
monkey(bar); // Calling monkey(bar) here is OK! Bar is visible
...
ifstream fp("foo.txt");
if(fp.is_open())
{
std::string line;
while( getline(fp,line) )
{
monkey(bar); //'bar' is an undefined reference!
}
}
}
And **src1.h**
#ifndef SRC1_H
#define SRC1_H
extern std::vector<int> bar;
void monkey(std::vector<int> feces);
#endif
And **src1.cpp**
std::vector<int> bar;
void monkey(std::vector<int> thrown_obj)
{
... //Iteration and dereferencing of "thrown_obj"
}
I've accessed data structures that are declared in `src1.cpp` in a for-loop in the scope of main and *that* was fine. Something wonky is happening in this if-statement though.
Compiler Error:
lab1.o: In function `main':
/home/ubuntu/workspace/ECE597/Lab1/lab1.cc:105: undefined reference to `int_req'
collect2: error: ld returned 1 exit status | <c++> | 2016-03-20 03:31:43 | LQ_EDIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.