qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
53,559,587
I have a short bit of code that needs to run for a long long time. I am wondering if the length of the variable's names that I use can alter the speed at which the program executes. Here is a very simple example written in Python. Program A ``` x = 1 while not x == 0: print('message') ``` Program B ``` xyz = 1 while not xyz == 0: print('message') ``` Will Program A print 'message' more times than Program B if I run program A and program B for 30 years on two identical machines.
2018/11/30
[ "https://Stackoverflow.com/questions/53559587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8896653/" ]
The results that @chepner mentioned are correct, Python can take longer to run the code in the console, but once the code is compiled the results are the same. To make sure that this is correct, I created the following code also inspired by the answer from @knifer: ``` from time import time from numpy import average,std x = 1 xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk = 1 short_runs = 0 long_runs = 0 for _ in range(int(2e7)): t0 = time() if x: pass short_runs += time() - t0 t0 = time() if xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk: pass long_runs += time() - t0 print('Runtime results:') print(f"Small variable runs : (sum = {short_runs:.3f})") print(f"Long variable runs : (sum = {long_runs :.3f})") ``` The code I propose is somewhat different, in the sense that the trial runs for the long and the short variable names are intertwined, such that any differences caused by underlying OS processes are minimized. The results of the code vary depending on whether you `copy-paste` the code into a Python console, or you call the code as a program (`python trial_runs.py`). Runs using `copy-paste` tend to be slower using long variables names, whereas calling the code as a program yields identical running times. PS. The actual running times change all the time for me (in one direction or the other), so it's hard to report exact values. Even the long variable names can sometimes run faster, although this is very rare on the Python console. The biggest conclusion is that any differences are really small either way :)
The difference is very small and we cant conclude that is because of name of variable. ``` import timeit x=1 xyz=1 start_time = timeit.default_timer() for i in range(1,1000000): if x==1: print("message") elapsed = timeit.default_timer() - start_time start_time2 = timeit.default_timer() for i in range(1,1000000): if xyz==1: print("message") elapsed2 = timeit.default_timer() - start_time2 print("small variable printing = ",str(elapsed),"big variable printing = "+str(elapsed2)) ``` And the Result was : ``` small variable printing = 3.6490847053481588 big variable printing = 3.7199463989460435 ```
3,407,525
Suppose I have D, an X-by-Y-by-Z data matrix. I also have M, an X-by-Y "masking" matrix. My goal is to set the elements (Xi,Yi,:) in D to NaN when (Xi,Yi) in M is false. Is there any way to avoid doing this in a loop? I tried using `ind2sub`, but that fails: ``` M = logical(round(rand(3,3))); % mask D = randn(3,3,2); % data % try getting x,y pairs of elements to be masked [x,y] = ind2sub(size(M),find(M == 0)); D_masked = D; D_masked(x,y,:) = NaN; % does not work! % do it the old-fashioned way D_masked = D; for iX = 1:size(M,1) for iY = 1:size(M,2) if ~M(iX,iY), D_masked(iX,iY,:) = NaN; end end end ``` I suspect I'm missing something obvious here. (:
2010/08/04
[ "https://Stackoverflow.com/questions/3407525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408268/" ]
You can do this by replicating your logical mask `M` across the third dimension using [REPMAT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html) so that it is the same size as `D`. Then, index away: ``` D_masked = D; D_masked(repmat(~M,[1 1 size(D,3)])) = NaN; ``` If replicating the mask matrix is undesirable, there is another alternative. You can first find a set of linear indices for where `M` equals 0, then replicate that set `size(D,3)` times, then shift each set of indices by a multiple of `numel(M)` so it indexes a different part of `D` in the third dimension. I'll illustrate this here using [BSXFUN](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/bsxfun.html): ``` D_masked = D; index = bsxfun(@plus,find(~M),(0:(size(D,3)-1)).*numel(M)); D_masked(index) = NaN; ```
My Matlab is a bit rusty but I think logical indexing should work: ``` D_masked = D; D_masked[ M ] = NaN; ``` (which probably can be combined into one statement with a conditional expression on the rhs...)
3,407,525
Suppose I have D, an X-by-Y-by-Z data matrix. I also have M, an X-by-Y "masking" matrix. My goal is to set the elements (Xi,Yi,:) in D to NaN when (Xi,Yi) in M is false. Is there any way to avoid doing this in a loop? I tried using `ind2sub`, but that fails: ``` M = logical(round(rand(3,3))); % mask D = randn(3,3,2); % data % try getting x,y pairs of elements to be masked [x,y] = ind2sub(size(M),find(M == 0)); D_masked = D; D_masked(x,y,:) = NaN; % does not work! % do it the old-fashioned way D_masked = D; for iX = 1:size(M,1) for iY = 1:size(M,2) if ~M(iX,iY), D_masked(iX,iY,:) = NaN; end end end ``` I suspect I'm missing something obvious here. (:
2010/08/04
[ "https://Stackoverflow.com/questions/3407525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408268/" ]
Reshape is [basically for free](https://stackoverflow.com/q/36062574/2732801), you can use it here for an efficient solution. reducing the whole to a 2d problem. ``` sz=size(D); D=reshape(D,[],sz(3)); %reshape to 2d D(isnan(M(:)),:)=nan; %perform the operation on the 2d matrix D=reshape(D,sz); %reshape back to 3d ```
My Matlab is a bit rusty but I think logical indexing should work: ``` D_masked = D; D_masked[ M ] = NaN; ``` (which probably can be combined into one statement with a conditional expression on the rhs...)
3,407,525
Suppose I have D, an X-by-Y-by-Z data matrix. I also have M, an X-by-Y "masking" matrix. My goal is to set the elements (Xi,Yi,:) in D to NaN when (Xi,Yi) in M is false. Is there any way to avoid doing this in a loop? I tried using `ind2sub`, but that fails: ``` M = logical(round(rand(3,3))); % mask D = randn(3,3,2); % data % try getting x,y pairs of elements to be masked [x,y] = ind2sub(size(M),find(M == 0)); D_masked = D; D_masked(x,y,:) = NaN; % does not work! % do it the old-fashioned way D_masked = D; for iX = 1:size(M,1) for iY = 1:size(M,2) if ~M(iX,iY), D_masked(iX,iY,:) = NaN; end end end ``` I suspect I'm missing something obvious here. (:
2010/08/04
[ "https://Stackoverflow.com/questions/3407525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408268/" ]
You can do this by replicating your logical mask `M` across the third dimension using [REPMAT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/repmat.html) so that it is the same size as `D`. Then, index away: ``` D_masked = D; D_masked(repmat(~M,[1 1 size(D,3)])) = NaN; ``` If replicating the mask matrix is undesirable, there is another alternative. You can first find a set of linear indices for where `M` equals 0, then replicate that set `size(D,3)` times, then shift each set of indices by a multiple of `numel(M)` so it indexes a different part of `D` in the third dimension. I'll illustrate this here using [BSXFUN](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/bsxfun.html): ``` D_masked = D; index = bsxfun(@plus,find(~M),(0:(size(D,3)-1)).*numel(M)); D_masked(index) = NaN; ```
Reshape is [basically for free](https://stackoverflow.com/q/36062574/2732801), you can use it here for an efficient solution. reducing the whole to a 2d problem. ``` sz=size(D); D=reshape(D,[],sz(3)); %reshape to 2d D(isnan(M(:)),:)=nan; %perform the operation on the 2d matrix D=reshape(D,sz); %reshape back to 3d ```
142,564
I have a use case in a modal where the user can select forms and define criteria based off of what they have selected. All of the criteria dependencies based off what form the user has selected remain the same in 90% of the use cases, but I have identified a new edge case where the dependencies may change. Do you think that it's okay to change the form fields depending on what the user has selected, or would using progressive disclosure be a better idea if the criteria fields are going to change? [![enter image description here](https://i.stack.imgur.com/zmsUd.png)](https://i.stack.imgur.com/zmsUd.png)
2022/02/18
[ "https://ux.stackexchange.com/questions/142564", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/141746/" ]
Progressive disclosure is meant to divide the UI into manageable chunks so as not to overwhelm the user with too many options and choices all at once. It's not meant to isolate each decision into a step of its own (that would be a wizard, and quite a tedious one). There's nothing wrong with dynamically changing the UI within the same screen based on the user's decisions, and it even has the upside of better reflecting to the user the meaning of the different choices they make. This enhances the feeling of control and helps them learn the system. A good example would this dialog from MS Outlook, where changing the recurrence from Weekly to Monthly immediately changes the fields affected by that change: [![enter image description here](https://i.stack.imgur.com/jMKAN.png)](https://i.stack.imgur.com/jMKAN.png) [![enter image description here](https://i.stack.imgur.com/vffgm.png)](https://i.stack.imgur.com/vffgm.png) Under the "extreme progressive disclosure" approach, this would entail navigating to a different screen and then back again in case you wanted to change your decision. I think it's easy to see that this is the friendlier option.
If Normal Form fits 90% of cases, it should be the default. But, if the user realizes after filling out the fields that Form With Tags would have been the better selection, they might be frustrated with going back and filling in different options - wasted effort. I would recommend changing the Select Form Type dropdown to radio buttons so the user can see all of their options before proceeding to fill in more information.
19,209,113
Here is my code : ``` Public Class Form1 Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If ComboBox1.SelectedItem = "1.6.4 Vanilla Server" Then Version = "164" End If If ComboBox1.SelectedItem = "1.6.2 Vanilla Server" Then Version = "162" End If End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim Version As Int16 End Sub End Class ``` Then I get a blue line under Version saying : Version is a type and cannot be used as an expression Thanks for any help :/
2013/10/06
[ "https://Stackoverflow.com/questions/19209113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2792832/" ]
Use the following way to show the select2 for your Gridview column, hope it helps. ``` array( 'name'=>'category_id', 'type'=>'html', 'value'=>'select2::activeDropDown($model,"my_select",CHtml::listData($dataToShowFromModel,"field_name_for_value","field_name_for_text"),array("empty"=>"","placeholder"=>"Please Select",select2Options=>array("allowClear"=>true)))' ) ```
See examples of this [Yii Gridview](http://yii.codexamples.com/v1.1/CGridView/) **In view e.g: admin.php** ``` $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'title', // display the 'title' attribute 'content:html', // display the 'content' attribute as purified HTML array( // display 'create_time' using an expression 'name'=>'category_id', 'type'=>'html', 'value'=>'Post::model()->getSelectTwo()', ), array( // display 'author.username' using an expression 'name'=>'authorName', 'value'=>'$data->author->username', ), array( // display a column with "view", "update" and "delete" buttons 'class'=>'CButtonColumn', ), ), )); ``` **In Post.php model** ``` public function getSelectTwo(){ $categories = Category::model()->findAll(); $data = array(); foreach($categories as $category){ $data[$category->id] = $category->title; } $this->widget('ext.select2.ESelect2',array( 'name'=>'category_id', 'data'=>$data, 'htmlOptions'=>array( ), )); } ``` See more Yii tutorials at <http://www.codexamples.com/>
19,209,113
Here is my code : ``` Public Class Form1 Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If ComboBox1.SelectedItem = "1.6.4 Vanilla Server" Then Version = "164" End If If ComboBox1.SelectedItem = "1.6.2 Vanilla Server" Then Version = "162" End If End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim Version As Int16 End Sub End Class ``` Then I get a blue line under Version saying : Version is a type and cannot be used as an expression Thanks for any help :/
2013/10/06
[ "https://Stackoverflow.com/questions/19209113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2792832/" ]
I have created a class extending the CDataColumn to add a filter to the column: ``` Yii::import('zii.widgets.grid.CDataColumn'); class TbTableDeviceType extends CDataColumn { public $model; public $fieldName; public function init() { $ajaxUpdate = $this->grid->afterAjaxUpdate; $this->grid->afterAjaxUpdate = "function(id,data){'.$ajaxUpdate.' $('#" . get_class($this->model) . "_" . $this->fieldName . "').select2({placeholder:' ', allowClear: true}); }"; } /** * Renders the filter cell. */ public function renderFilterCell() { echo '<td><div class="filter-container">'; $deviceTypes = Helper::getDeviceTypesArray(); $deviceTypes[''] = ''; // Add empty value to select all asort($deviceTypes); $this->filter = $deviceTypes; $model = $this->model; $field = $this->fieldName; if (empty($model->$field)) echo CHtml::dropDownList(get_class($this->model) . '[' . $this- >fieldName . ']', $this->fieldName, $deviceTypes); else echo CHtml::dropDownList(get_class($this->model) . '[' . $this->fieldName . ']', $this->fieldName, $deviceTypes, array( 'options' => array( $model->$field => array( 'selected' => true ) ) )); Yii::app()->controller->widget('ext.ESelect2.ESelect2', array( 'selector' => '#' . get_class($this->model) . '_' . $this- >fieldName, 'data' => $deviceTypes, 'options' => array( 'placeholder' => ' ', 'allowClear' => true ), 'htmlOptions' => array( 'minimumInputLength' => 2, 'style' => 'width:100%' ) )); echo '</div></td>'; } } ``` And then you add this column to your cgridview: ``` array( 'class' => 'ext.widgets.TbTableDeviceType', 'model' => $model, 'fieldName' => 'deviceType_id', 'name' => 'deviceType_id', ), ```
See examples of this [Yii Gridview](http://yii.codexamples.com/v1.1/CGridView/) **In view e.g: admin.php** ``` $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'title', // display the 'title' attribute 'content:html', // display the 'content' attribute as purified HTML array( // display 'create_time' using an expression 'name'=>'category_id', 'type'=>'html', 'value'=>'Post::model()->getSelectTwo()', ), array( // display 'author.username' using an expression 'name'=>'authorName', 'value'=>'$data->author->username', ), array( // display a column with "view", "update" and "delete" buttons 'class'=>'CButtonColumn', ), ), )); ``` **In Post.php model** ``` public function getSelectTwo(){ $categories = Category::model()->findAll(); $data = array(); foreach($categories as $category){ $data[$category->id] = $category->title; } $this->widget('ext.select2.ESelect2',array( 'name'=>'category_id', 'data'=>$data, 'htmlOptions'=>array( ), )); } ``` See more Yii tutorials at <http://www.codexamples.com/>
70,595,234
``` propSet = childRes.getValueMap().keySet(); ``` **Above code written in java can anyone help me to write mock in mockito in junit**
2022/01/05
[ "https://Stackoverflow.com/questions/70595234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15764925/" ]
It seems there is some conflict between Windows 10 Pro and Office 2019 Professional and using port 25 for smtp.office365.com. As mentioned I have several PC's with combinations of Windows 10 Pro/Home and Office 2019 and Office 365 and all of these worked. However, the specific combination of Office 2019 Professional and Windows 10 Pro causes an issue. This is even if the CDO is used outside of Excel VBA (using a python script). Troubleshooting: 1. Reinstall Windows 10 Pro 21H2 on a new partition and installing Office 2019 - fail 2. Reinstall Windows 10 Pro 2004 (to test earlier version of Windows) on a new partition and not installing Office - pass 3. Reinstall Windows 10 Pro 2004 on a new partition and installing Office 2019 Pro - fail 4. Reinstall Windows 10 Pro 2004 on a new partition and installing Office 365 - pass Next step is to see if going to 21H2 and Office 365 still works. Strangely enough, no ports are shown as blocked on the specific machine, no ports are blocked by the ISP, so Office 2019 must be doing something either to CDO or to ports - I wouldn't know how to identify what though
Try to add the configuration field bellow to the ones you are setting: ``` .Item("http://schemas.microsoft.com/cdo/configuration/sendtls") = True ``` Also, try to change the port from 25 to 465 or 587.
841,479
Assuming a single page application accessed initially via HTTP that uses AJAX for all server interaction, is it possible to use HTTP for regular data transfers and then switch to AJAXian HTTPS requests for secure data transfers? If so, how would the browser handle the certificate and locking notification when a HTTPS AJAX request was made? If this is not possible, then are there any workarounds to mixing AJAX HTTP and AJAX HTTPS within the same page such as loading an iFrame for HTTPS? Thanks!
2009/05/08
[ "https://Stackoverflow.com/questions/841479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103750/" ]
Attempting to switch protocols will violate the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy). I am not sure how a workaround using iFrames would behave, but I think the browser may block access to the frame that was loaded as HTTPS, again due to the same origin policy.
I know this is old post but since i arrived here by search engine it would be a worth to spill what I've learn. It is possible to use something called [CORS](http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing) but as usual old MSIE has problem [implementing it](http://caniuse.com/#search=cors). It should be simple as sending additional HTTP headers: ``` Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com ```
14,136,241
4 and JSF 2.1 , Tomcat6 for a sample application. I was trying to show a dailog box when clicked on a image inside a ui:composition. But it is not getting displayed. And if i run that without using the ui:composition> it is working fine. This is my code ``` <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/javascript" src="scripts/jquery-1.7.1.min.js"></script> </h:head> <h:body> <p:dialog id="dialog" header="Login" widgetVar="dlg"> <h:form> <h:outputText value="hi"></h:outputText> <!-- <h:panelGrid columns="2" cellspacing="5" > <h:outputLabel value="OsName" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.osName}"></h:inputText> <h:outputLabel value="OsFamily" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.osFamily}"></h:inputText> <h:outputLabel value="OsDescription" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.osDescription}"></h:inputText> <h:outputLabel value="OsGuid" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.osGuid}"></h:inputText> <h:outputLabel value="MajorVersion" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.majorVersion}"></h:inputText> <h:outputLabel value="minorVersion" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.minorVersion}"></h:inputText> <h:outputLabel value="BuildVersion" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.buildVersion}"></h:inputText> <h:outputLabel value="OsServicepack" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.osServicepack}"></h:inputText> <h:outputLabel value="OsRevision" style="color:black"></h:outputLabel> <h:inputText value="#{productBean.osRevision}"></h:inputText> <h:commandButton value="Back" action="#{productBean.product}" styleClass="button1" ></h:commandButton> <h:commandButton value="Next" action="#{productBean.productcustomer}" styleClass="button1" ></h:commandButton> </h:panelGrid> --> </h:form> </p:dialog> <ui:composition template="/pages/templates/layout.xhtml"> <ui:define name="body" > <h:form prependId="false"> <div class="widget"> <p:dataTable var="car" paginator="true" rows="10" > <f:facet name="header"> List of Cars </f:facet> <p:columnGroup type="header"> <p:row styleClass="edit"> <p:column rowspan="3" headerText="Model" sortBy="Model" filterBy="Model" width="" /> <p:column rowspan="3" headerText="Year" sortBy="Year" filterBy="Year"/> <p:column rowspan="3" headerText="Company" sortBy="Company" filterBy="Company"/> <p:column rowspan="3" headerText="Color" sortBy="Color" filterBy="Color"/> <p:column colspan="3" headerText="Actions" /> </p:row> <p:row styleClass="edit"> <p:column><f:facet name="header"><h:outputLink onclick="showStatus()" title="Edit"> <p:graphicImage value="/images/b_edit.png" /></h:outputLink> </f:facet></p:column> <p:column><f:facet name="header"><h:outputLink onclick="showStatus()" title="Delete"> <p:graphicImage value="/images/b_drop.png" /></h:outputLink> </f:facet></p:column> <p:column><f:facet name="header"><h:outputLink onclick="dlg.show()" title="View"> <p:graphicImage value="/images/search-icon.png" /></h:outputLink> </f:facet></p:column> </p:row> </p:columnGroup> </p:dataTable> </div> </h:form> </ui:define> </ui:composition> </h:body> </html> ```
2013/01/03
[ "https://Stackoverflow.com/questions/14136241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944615/" ]
Facelets skips everything outside the `<ui:composition>` tag, so the dialog will simply not be present in the view in this case. You need to put it also in the `<ui:composition>` tag
hello try the rendered Property by binding it with a boolean variable. Thanks
43,007,176
I am trying to make my selector so when it gets the class of transform with the tagname with p, it will do some event in my case it is mouse hovering but i am having trouble with it. I know there are jquery solutions but i am doing it with pure javascript. here is the code below currently ``` var hoverEvent = document.getElementsByTagName("p").getElementsByClassName("transform"); for (let i = 0; i < hoverEvent .length; i++) { hoverEvent [i].onmouseover=function() { this.style.color = "yellow"; // changes paragraph with class of transform to yellow during hover } } // end for for (let i = 0; i < hoverEvent .length; i++) { hoverEvent [i].onmouseout=function() { this.style.color = "black"; // changes it back to black } } ```
2017/03/24
[ "https://Stackoverflow.com/questions/43007176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6031896/" ]
You can use a CSS selector in `querySelectorAll` to find all paragraphs with that classname: ``` var hoverEvent = document.querySelectorAll("p.transform"); ```
``` var transformPs = document.querySelectorAll("p.transform"); for (let i = 0; i < transformPs .length; i++) { // on mouse over transformPs[i].onmouseover = function () { this.style.color = "yellow"; // changes paragraph with class of transform to yellow during hover }; // on mouse out transformPs[i].onmouseout = function () { this.style.color = "black"; // changes it back to black }; } ```
43,007,176
I am trying to make my selector so when it gets the class of transform with the tagname with p, it will do some event in my case it is mouse hovering but i am having trouble with it. I know there are jquery solutions but i am doing it with pure javascript. here is the code below currently ``` var hoverEvent = document.getElementsByTagName("p").getElementsByClassName("transform"); for (let i = 0; i < hoverEvent .length; i++) { hoverEvent [i].onmouseover=function() { this.style.color = "yellow"; // changes paragraph with class of transform to yellow during hover } } // end for for (let i = 0; i < hoverEvent .length; i++) { hoverEvent [i].onmouseout=function() { this.style.color = "black"; // changes it back to black } } ```
2017/03/24
[ "https://Stackoverflow.com/questions/43007176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6031896/" ]
You can use a CSS selector in `querySelectorAll` to find all paragraphs with that classname: ``` var hoverEvent = document.querySelectorAll("p.transform"); ```
The vanilla JavaScript equivalent would be using [`document.querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll): ```js function turnYellow (e) { e.target.style.color = 'yellow' } function turnBlack (e) { e.target.style.color = '' } document.querySelectorAll('p.transform').forEach(function (p) { p.addEventListener('mouseover', turnYellow) p.addEventListener('mouseout', turnBlack) }) ``` ```css body { background: #ccc; } ``` ```html <p class="transform">Example Paragraph</p> ``` However, I think the best approach would be to forego the JavaScript altogether and instead rely on the CSS pseudo-selector [`:hover`](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover): ```css body { background: #ccc; } p.transform:hover { color: yellow; } ``` ```html <p class="transform">Example Paragraph</p> ```
43,007,176
I am trying to make my selector so when it gets the class of transform with the tagname with p, it will do some event in my case it is mouse hovering but i am having trouble with it. I know there are jquery solutions but i am doing it with pure javascript. here is the code below currently ``` var hoverEvent = document.getElementsByTagName("p").getElementsByClassName("transform"); for (let i = 0; i < hoverEvent .length; i++) { hoverEvent [i].onmouseover=function() { this.style.color = "yellow"; // changes paragraph with class of transform to yellow during hover } } // end for for (let i = 0; i < hoverEvent .length; i++) { hoverEvent [i].onmouseout=function() { this.style.color = "black"; // changes it back to black } } ```
2017/03/24
[ "https://Stackoverflow.com/questions/43007176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6031896/" ]
You can use a CSS selector in `querySelectorAll` to find all paragraphs with that classname: ``` var hoverEvent = document.querySelectorAll("p.transform"); ```
you can use **classList** to check class of element ``` var p = document.getElementsByTagName("p"); if (p.classList.contains('transform')){ // do whatever you want to do } ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
It's: "if (action.length >= 2 && query.length >= 2 && **query.length** <=24) {" Not: "if (action.length >= 2 && query.length >= 2 && **query.lenght** <=24) {"
Replace all whitespace (including tabs, spaces, ...): ``` query.replace(/\s/g, '_'); ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Try this: ``` var str = 'a b c'; var replaced = str.split(' ').join('-'); ```
`String.prototype.replace` only replaces the first when its first argument is a string. To replace all occurrences you need to pass in a global regular expression as the first argument. > > [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2Freplace) > ========================================================================================================================================================================================================= > > > ... > > > To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter. > > > Others have shown a number of regular expressions that work for varying definitions of "space."
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Try this: ``` var str = 'a b c'; var replaced = str.split(' ').join('-'); ```
Try this ``` query.replace(/ +(?= )/g,'-'); ``` This still works, in case your query is `undefinied` or `NaN`
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
It's: "if (action.length >= 2 && query.length >= 2 && **query.length** <=24) {" Not: "if (action.length >= 2 && query.length >= 2 && **query.lenght** <=24) {"
You can try with custom function ``` String.prototype.replaceAll = function (searchText, replacementText) { return this.split(searchText).join(replacementText); }; var text = "This is Sample Text"; text.replaceAll(" ", "-"); //final output(This-is-Sample-Text) ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
You can try with custom function ``` String.prototype.replaceAll = function (searchText, replacementText) { return this.split(searchText).join(replacementText); }; var text = "This is Sample Text"; text.replaceAll(" ", "-"); //final output(This-is-Sample-Text) ```
Try this ``` query.replace(/ +(?= )/g,'-'); ``` This still works, in case your query is `undefinied` or `NaN`
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Try with this: ``` .replace(/\s/g,"-"); ``` Demo: [JSFiddle](http://jsfiddle.net/vYnxm/3/) ----------------------------------------------
Try this: ``` var str = 'a b c'; var replaced = str.split(' ').join('-'); ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Try this: ``` var str = 'a b c'; var replaced = str.split(' ').join('-'); ```
Replace all whitespace (including tabs, spaces, ...): ``` query.replace(/\s/g, '_'); ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Try this: ``` var str = 'a b c'; var replaced = str.split(' ').join('-'); ```
You can try with custom function ``` String.prototype.replaceAll = function (searchText, replacementText) { return this.split(searchText).join(replacementText); }; var text = "This is Sample Text"; text.replaceAll(" ", "-"); //final output(This-is-Sample-Text) ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Try with this: ``` .replace(/\s/g,"-"); ``` Demo: [JSFiddle](http://jsfiddle.net/vYnxm/3/) ----------------------------------------------
You can try with custom function ``` String.prototype.replaceAll = function (searchText, replacementText) { return this.split(searchText).join(replacementText); }; var text = "This is Sample Text"; text.replaceAll(" ", "-"); //final output(This-is-Sample-Text) ```
14,120,999
Why is my jquery not replacing all spaces with a `'-'`. It only replaces the first space with a `'-'` ``` $('.modhForm').submit(function(event) { var $this = $(this), action = $this.attr('action'), query = $this.find('.topsearchbar').val(); // Use val() instead of attr('value'). if (action.length >= 2 && query.length >= 2 && query.lenght <=24) { // Use URI encoding var newAction = (action + '/' + query.replace(' ','-')); console.log('OK', newAction); // DEBUG // Change action attribute $this.attr('action', newAction); } else { console.log('To small to be any good'); // DEBUG // Do not submit the form event.preventDefault(); } }); ```
2013/01/02
[ "https://Stackoverflow.com/questions/14120999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407503/" ]
Use a [regular expression](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) to replace all occurences : ``` query.replace(/\ /g, '-') ```
`String.prototype.replace` only replaces the first when its first argument is a string. To replace all occurrences you need to pass in a global regular expression as the first argument. > > [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString%2Freplace) > ========================================================================================================================================================================================================= > > > ... > > > To perform a global search and replace, either include the g switch in the regular expression or if the first parameter is a string, include g in the flags parameter. > > > Others have shown a number of regular expressions that work for varying definitions of "space."
26,025
Will generally accepted papers appear in conferences proceeding without presentation? In particular my paper is accepted for [**this**](http://www.greenorbs.org/TrustCom2014) conference. In the conference web site they pointed out: "Accepted and presented papers will be included in the IEEE CPS Proceedings." In its registration page they have told: > > Please register your papers before 20 July 2014. It is strictly > enforced. If we do not receive your registration by that date, your > papers will be moved from the proceedings. Thank you very much. > > > Does this mean the registered papers definitively will be appeared in the proceeding? Unfortunately there is no contact info on the web site and they do not response emails. I could not attend the conference and I wonder should I pay regitration fee or not?
2014/07/17
[ "https://academia.stackexchange.com/questions/26025", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/1070/" ]
The [IEEE policy on non-presented papers](http://www.ieee.org/conferences_events/conferences/organizers/handling_nonpresented_papers.html) is as follows: > > Authors are expected to attend the conference in person to present their papers and share their ideas. > > > To encourage attendance, IEEE recommends that conferences exclude or limit the distribution of any paper that was not presented at the conference. This policy is not mandatory and only applies to conference proceedings where IEEE is the copyright holder. > > > If authors are unable to attend the conference and present their papers, they should contact the program chair as soon as possible so that substitute arrangements can be made. > > > That is, it is at the conference organizer's discretion. Some IEEE conferences *do* pull a paper from the published proceedings if it isn't presented at the conference: for example, the [IEEE Signal Processing Society has the policy](http://www.signalprocessingsociety.org/about-sps/governance/policy-procedure/part-2/) that papers not presented will not be distributed on IEEEXplore. The only way to be sure your paper will appear in the conference proceedings is to confirm with the conference organizer.
In general, at least for the better conferences in the computing and information science research area that I find myself working in, if your paper is **accepted** and at least one author has **registered** for the conference, then your paper will be included in the conference proceedings and available in the usual archives (ACMDL/IEEEXplore/DBLP etc.) I have done this multiple times when I lived in different countries and could not afford to travel to a conference in a far flung location. Sometime ago, I wrote [another (very related) answer](https://academia.stackexchange.com/questions/11428/the-fate-of-an-accepted-paper-not-being-presented) which might be of further help to you. However, this may vary for the particular conference that you have a paper in. **Added:** (to incorporate Jeff's comment) In some conferences, an author may not even register. A colleague or otherwise could present your paper for you. Of course, this needs the permission of the organizers.
4,848,266
I have 4 Paragraph tags inside a div with id=address I want to append a character to this paragraph from a string array. I want that each character should be added after a finite delay. here is the code snippet: ``` $("#address p").each(function(index) { var t_delay = 0; for (var i=0; i<arr[index].length; i++){ t_delay += 1000; $(this).delay(t_delay).append(arr[index][i]); } }); ``` I am not getting the delay, and the whole paragraph displays all together. pls help me
2011/01/31
[ "https://Stackoverflow.com/questions/4848266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/596446/" ]
No jQuery is required. ``` var reps = { UN: "Ali", LC: "Turkey", AG: "29", ... }; return str.replace(/\[(\w+)\]/g, function(s, key) { return reps[key] || s; }); ``` * The regex `/\[(\w+)\]/g` finds all substrings of the form `[XYZ]`. * Whenever such a pattern is found, the function in the 2nd parameter of `.replace` will be called to get the replacement. * It will search the associative array and try to return that replacement if the key exists (`reps[key]`). * Otherwise, the original substring (`s`) will be returned, i.e. nothing is replaced. (See [In Javascript, what does it mean when there is a logical operator in a variable declaration?](https://stackoverflow.com/questions/3088098/in-javascript-what-does-it-mean-when-there-is-a-logical-operator-in-a-variable-d) for how `||` makes this work.)
You can do: ``` var array = {"UN":"ALI", "LC":"Turkey", "AG":"29"}; for (var val in array) { str = str.split(val).join(array[val]); } ```
2,703,993
Is there easy way how to round floating numbers in a file to equal length? The file contains other text not only numbers. ``` before: bla bla bla 3.4689 bla bla bla 4.39223 bla. after: bla bla bla 3.47 bla bla bla 4.39 bla. ``` Thanks
2010/04/24
[ "https://Stackoverflow.com/questions/2703993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282849/" ]
Bash ``` #!/bin/bash shopt -s extglob while read -r line do set -- $line for((i=1;i<=${#};i++)) do s=$(eval echo \${${i}}) case "$s" in +([0-9]).+([0-9]) ) s=$(printf "%.2f " $s);; esac printf "%s " $s done echo done <"file" ``` output ``` $ cat file bla1 bla 2 bla 3.4689 bla bla bla 4.39223 bla. words ..... 2.14 blah blah 4.5667 blah $ ./shell.sh bla1 bla 2 bla 3.47 bla bla bla 4.39 bla. words ..... 2.14 blah blah 4.57 blah ```
`awk BEGIN{RS="[[:space:]]"} /[0-9].[0-9]/{printf("%.2f%s",$1,RT)} !/[0-9].[0-9]/{printf("%s%s",$1,RT)} f.txt` You might want to change RS to something that can handle a more robust set of word boundaries. This solution has the advantage of preserving the boundary rather than just reprinting the output separated by spaces.
68,462,288
Simply put, I am in a entry level computer science class, with the assignment based on fixing the html and javascript files below to create four separate working calculators. As far as I understand, however, I cannot find any formatting issues that prevent the two files from influencing each other, at least in terms of simple formatting. ```css function ab() { // var a; var b; var r; a = parsefloat(document.getElementById("txt1").value); b = parsefloat(document.getElementById("txt2").value); r = a + b; document.getElementById("p1").innerHTML= "The sum of the numbers is " + r; } function cd() { // var c; var d; var r2; c = parsefloat(document.getElementById("txt3").value); d = parsefloat(document.getElementById("txt4").value); r2 = c - d; document.getElementById("p2").innerHTML= "The sum of the numbers is" + r2; } function ef() { // var e; var f; var r3; c = parsefloat(document.getElementById("txt5").value); d = parsefloat(document.getElementById("txt6").value); r3 = e / f; document.getElementById("p3").innerHTML= "The sum of the numbers is" + r3; } function gh() { // var g; var h; var r4; c = parsefloat(document.getElementById("txt7").value); d = parsefloat(document.getElementById("txt8").value); r4 = g * f; document.getElementById("p4").innerHTML= "The sum of the numbers is" + r4; } ``` ```html <html> <head> <script src="convert.js"></script> </head> <body> <form> <h1> Simple Addition</h1> Please type in two numbers to add them together: <input type="text" id="txt1" value="10"/> <input type="text" id="txt2" value="10"/> <br/> <input type="button" id ="btn1" value="Add" onclick = "ab()" /> <p id="p1"></p> </form> <h1> Simple Subtraction</h1> Please type in two numbers to subtract them <input type="text" id="txt3" value="10"/> <input type="text" id="txt4" value="10"/> <br/> <input type="button" id ="btn2" value="Subtract" onclick = "cd()" /> <p id="p2"></p> <h1> Simple Division</h1> Please type in two numbers to divide them <input type="text" id="txt5" value="10"/> <input type="text" id="txt6" value="11"/> <br/> <input type="button" id ="btn3" value="Divide" onclick = "ef()" /> <p id="p3"></p> <h1> Simple Multiplication</h1> Please type in two numbers to multiply them <input type="text" id="txt7" value="10"/> <input type="text" id="txt8" value="10"/> <br/> <input type="button" id ="btn4" value="Multiply" onclick = "gh()" /> <p id="p4"></p> </form> </body> </html> ```
2021/07/20
[ "https://Stackoverflow.com/questions/68462288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16491313/" ]
No(t really). You have two fundamental issues here. Primitives don't play the dynamic typing game. ---------------------------------------------- If you have e.g. a `StringCharacteristic` (note that in java we `WriteTypesLikeThis`, not `likeThis`) and a `LocalDateCharacteristic` it's all object refs and we can generalize over that, make a supertype `ObjectCharacteristic<T>`. But, generics can't be primitive, and there is no way to generalize over primitives. Right now, that is. Project Valhalla is seeing a ton of active development (I'm pretty sure it sees, by a large margin, the most effort amongst all the various language-related projects in active development at OpenJDK right now), so keep a weather eye on your JDK update's feature lists. You can work around it by using the wrapper type (`java.lang.Integer`), but this is a very poor substitution: They can be `null` which is annoying (`int` cannot be), and they are an order of magnitude less efficient both CPU and memory wise. They also aren't necessarily compatible - autounboxing only goes so far. You'd shove these methods in a superclass (make it package private if you don't want to make that aspect of it a part of your public API), using generics: `class Characteristic<T>`, using `T` instead of `int`/`String` everywhere in that superclass, and then that superclass can just be the thing. If you really insist on having an explicitly named type, you can just write `public class IntCharacteristic extends Characteristic<Integer> {}`, maybe add a constructor, and call it a day, the rest is taken care of (even the field, which you'd declare in the superclass as `private T value`. But, that gives you a characteristic class that uses `Integer`, and not `int`. There's no way to have it use int. Not until valhalla. If you aren't willing to accept that inefficiency, you're going to have to manually write out the `int`-related bits. The problem of the self type ---------------------------- This secondary issue does not show up if you both accept the negative aspects of using `Integer` instead of `int`, *and* you're okay with just having a single `public class Characteristic<T>`, with no custom subclasses. The problem with a type hierarchy and 'fluent API' (API methods that return their own type) is that they **do not work here**. Interlude - let's write it. --------------------------- Because the name bits are the exact same, except for the return type of the setName method, we can do this: ``` private abstract class Characteristic { private String name; public Characteristic setName(String name) { this.name = name; return this; } public String getName() { return name; } } ``` And then you can write subtypes of this, and you can just skip all the code for the name stuff, as your superclass takes care of that: ``` public class IntCharacteristic extends Characteristic { private int value; public IntCharacteristic setValue(int value) { ... } } ``` But, problem! ------------- The one issue here is that the setName method has the wrong return type. Yes, it returns `this`, and `this` would, in the case of a new `IntCharacteristic` instance, be `instanceof IntCharacteristic`, but your `setName` method's return type doesn't declare it, and thus javac won't treat it as such. Thus, this will **FAIL**: ``` new IntCharacteristic().setName("Hello").setValue(5); ``` You can make it succeed, using a self-generics hack. **This is a bad idea, and you need to read on for a much better solution**. I include it here because whilst in this case there is a better solution available, sometimes there is not, and this hack IS the best solution: ``` public class Characteristic<S extends Characteristic<S>> { private String name; @SuppressWarnings("unchecked") protected S self() { return (S) this; } public S setName(String name) { this.name = name; return self(); } } public class IntCharacteristic extends Characteristic<IntCharacteristic> { } ``` This code ensures that the return type of `setName` **is** `IntCharacteristic` which is what you want. It is **impossible** to make this work without a cast that causes the compiler to emit a warning that the operation doesn't actually do any checking at all, but we know it's going to be 'true', because that weird signature (`S extends Self<S>`) effectively means that anything that extends it can only put itself in the `<>`. Much better solutions --------------------- Mostly, that whole 'return self' thing is overblown. It's not particularly java-esque, and this shows how it causes issues. More generally, if you insist on making 'modern' API, then it's like you've built a kitchen with a medieval oven and a brand new microwave next to each other. The modern take involves immutability. Why do you even allow name to change here? Shouldn't it be set in stone upon creation? Then you avoid this entire mess! ``` public class Characteristic { private final String name; public Characteristic(String name) { this.name = name; } public String getName() { return name; } } public class IntCharacteristic extends Characteristic { private final int value; public IntCharacteristic(String name, int value) { super(name); this.value = value; } public int getValue() { return value; } } ``` Problem solved. Stop returning self, by the way ------------------------------- Fundamentally, `return this;` is not a good idea except possibly in `final` classes. The problem is that *clearly* your intent is merely to make it easy to 'chain' method calls to this thing, but fundamentally **this cannot work** if hierarchies are involved, unless you use the above hack which cannot be 'hidden' (that generics param is part of your public API now). You're also not really using it to return the result of a calculation, which is what return values are intended to do. In other words, you're hacking the language when you do this. There are reasons to do so, but it's best to do so with open eyes: Whenever you hack around the language you're going to have to deal with the fact that eventually it'll bite you in the arse. The *REAL* solution is either for java-the-language to grow the concept of 'self type', or better yet, for java-the-language to grow the concept of 'allow chaining'. The MUCH better solution to this problem is one of these 2 true solutions: Language proposal A ------------------- ``` chainable public void setName(String name) { this.name = name; } ``` Where the `chainable` keyword both requires (compiler error if not) that the return type is `void`, AND it lets callers write `new Foo().setName("stuff").chainMoreMethodsHere();`. It's purely `javac` syntax sugar, none of this survives in the class file other than as a marker so `javac` knows what to do. THe method's signature in the class file keeps its VOID return type, and language tools know that e.g. ignoring the return type is completely fine here. Language proposal B ------------------- Leave it in the hands of the callers instead of in the API writer: just have a void method: `public void setName() { ... }`, but the caller can choose to chain: ``` Foo x = new Foo()..setName()..setSomethingElse(); ``` here the double dot means: Invoke the method, toss away whatever is returned, and resolve the expression to be identical to the receiver. (`x.foo()` means: call `foo`, toss return type, expression resolves to `x`). Currently there is no traffic in OpenJDK lists about any of this. But maybe today is different. If ever this is added, your API is now broken and probably will feel outdated forever more. I'm not saying fluent APIs are utterly idiotic. But close to it. You're hacking the language and usually, either because of the self type thing or future language improvements, that means you'll regret it someday.
Exactly how useful this is depends on what the client wants to do with instances of `Characteristic`, that is when it can't tell what concrete class they are. If there are cases where (for instance) you want to show the names of a set of `Characteristic`s, and perhaps a `toString` of their values, then this will be useful. You can do this: ``` interface Characteristic<T> { public T getValue(); public String getName(); Characteristic<T> setValue(T value); Characteristic<T> setName(String name); } class StringCharacteristic implements Characteristic<String>{ String name = ""; String value = ""; public String getValue() { return value; } public StringCharacteristic setValue(String value) { this.value = value; return this; } public String getName() { return name; } public StringCharacteristic setName(String name) { this.name = name; return this; } } class IntCharacteristic implements Characteristic<Integer> { String name = ""; int value = 0; public Integer getValue() { return value; } public IntCharacteristic setValue(Integer value) { this.value = value; return this; } public String getName() { return name; } public IntCharacteristic setName(String name) { this.name = name; return this; } } ``` (Please use correct Java naming conventions by the way) You can use an abstract class to factor out the common implementation: ``` abstract class AbstractCharacteristic<T> implements Characteristic<T> { String name = ""; T value; public AbstractCharacteristic(T value) { this.value = value; } public T getValue() { return value; } public Characteristic<T> setValue(T value) { this.value = value; return this; } public String getName() { return name; } public Characteristic<T> setName(String name) { this.name = name; return this; } } class StringCharacteristic extends AbstractCharacteristic<String>{ public StringCharacteristic() { super(""); } } class IntCharacteristic extends AbstractCharacteristic<Integer> { public IntCharacteristic() { super(0); } } ``` (We need the constructor parameter because a String field would normally be initialised to `null` by default, rather than `""`)
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
``` var $this = $(this); $('p a').each(function(){ $this.append('<option value="">' + $(this).text() + '</option>'); }); ``` <http://jsfiddle.net/QgCqE/1/>
No need for a function unless you are planning to use it for sever drop downs. ``` var ddl = $("#select"); $("p a").each(function () { var link = $(this); ddl.append($("<option></option>").val(link.text()).html(link.text())); }); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
A **Cleaner and more jQuery-oriented solution** of *James Montagne*'s answer: ``` $this.append( $('<option/>').val('').text($(this).text()) ); ``` or the alternative with properties mapping: ``` $this.append($("<option/>", { value: '', text: $(this).text() })); ```
To make the loop in your elements use [$.each](http://api.jquery.com/each/) --- You dont need extend jQuery unless you want to make it reusable. `[**LIVE DEMO**](http://jsfiddle.net/pT6rs/)` ``` $.fn.populate = function(el) { var options = ''; $(el).each(function(i, e) { options += '<option>' + $(this).text() + '</option>'; }); this.append(options); return this; } $('#select').populate('p > a'); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
<http://jsfiddle.net/kasperfish/RY3U9/4/> ``` var selectbox=$("#select");//cache our slectbox, so jquery doesn't have to look for it in every loop. $('p > a').each(function(){//select all a tags in p (loop through them) var text=$(this).text();//cache the link text in a variable because we need it twice. selectbox.append($('<option>').text(text).val(text));//add new option with value en text to selectbox }) ```
No need for a function unless you are planning to use it for sever drop downs. ``` var ddl = $("#select"); $("p a").each(function () { var link = $(this); ddl.append($("<option></option>").val(link.text()).html(link.text())); }); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
``` $('#new_organizations').click(loadOrgTypes); function loadOrgTypes() { console.log('retrieving all Org Types'); $.ajax({ type: 'GET', url: rootURL+'org_types', dataType: "json", // data type of response success: renderOrgTypes, error: function(err){ console.log('Error'); console.log("AJAX error in request: " + JSON.stringify(err, null, 2)); } }); } function renderOrgTypes(data){ var list = data == null ? [] : (data instanceof Array ? data : [data]); var select = $("#org_types_select"); select.empty(); $.each(list , function(index, org_types) { var content='<option org_type_id="' + org_types.id + '">' + org_types.name_loc + '</option>'; select.append(content); }); } ```
To make the loop in your elements use [$.each](http://api.jquery.com/each/) --- You dont need extend jQuery unless you want to make it reusable. `[**LIVE DEMO**](http://jsfiddle.net/pT6rs/)` ``` $.fn.populate = function(el) { var options = ''; $(el).each(function(i, e) { options += '<option>' + $(this).text() + '</option>'; }); this.append(options); return this; } $('#select').populate('p > a'); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
A **Cleaner and more jQuery-oriented solution** of *James Montagne*'s answer: ``` $this.append( $('<option/>').val('').text($(this).text()) ); ``` or the alternative with properties mapping: ``` $this.append($("<option/>", { value: '', text: $(this).text() })); ```
No need for a function unless you are planning to use it for sever drop downs. ``` var ddl = $("#select"); $("p a").each(function () { var link = $(this); ddl.append($("<option></option>").val(link.text()).html(link.text())); }); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
<http://jsfiddle.net/kasperfish/RY3U9/4/> ``` var selectbox=$("#select");//cache our slectbox, so jquery doesn't have to look for it in every loop. $('p > a').each(function(){//select all a tags in p (loop through them) var text=$(this).text();//cache the link text in a variable because we need it twice. selectbox.append($('<option>').text(text).val(text));//add new option with value en text to selectbox }) ```
To make the loop in your elements use [$.each](http://api.jquery.com/each/) --- You dont need extend jQuery unless you want to make it reusable. `[**LIVE DEMO**](http://jsfiddle.net/pT6rs/)` ``` $.fn.populate = function(el) { var options = ''; $(el).each(function(i, e) { options += '<option>' + $(this).text() + '</option>'; }); this.append(options); return this; } $('#select').populate('p > a'); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
``` var $this = $(this); $('p a').each(function(){ $this.append('<option value="">' + $(this).text() + '</option>'); }); ``` <http://jsfiddle.net/QgCqE/1/>
<http://jsfiddle.net/kasperfish/RY3U9/4/> ``` var selectbox=$("#select");//cache our slectbox, so jquery doesn't have to look for it in every loop. $('p > a').each(function(){//select all a tags in p (loop through them) var text=$(this).text();//cache the link text in a variable because we need it twice. selectbox.append($('<option>').text(text).val(text));//add new option with value en text to selectbox }) ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
``` $('#new_organizations').click(loadOrgTypes); function loadOrgTypes() { console.log('retrieving all Org Types'); $.ajax({ type: 'GET', url: rootURL+'org_types', dataType: "json", // data type of response success: renderOrgTypes, error: function(err){ console.log('Error'); console.log("AJAX error in request: " + JSON.stringify(err, null, 2)); } }); } function renderOrgTypes(data){ var list = data == null ? [] : (data instanceof Array ? data : [data]); var select = $("#org_types_select"); select.empty(); $.each(list , function(index, org_types) { var content='<option org_type_id="' + org_types.id + '">' + org_types.name_loc + '</option>'; select.append(content); }); } ```
No need for a function unless you are planning to use it for sever drop downs. ``` var ddl = $("#select"); $("p a").each(function () { var link = $(this); ddl.append($("<option></option>").val(link.text()).html(link.text())); }); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
``` var $this = $(this); $('p a').each(function(){ $this.append('<option value="">' + $(this).text() + '</option>'); }); ``` <http://jsfiddle.net/QgCqE/1/>
A **Cleaner and more jQuery-oriented solution** of *James Montagne*'s answer: ``` $this.append( $('<option/>').val('').text($(this).text()) ); ``` or the alternative with properties mapping: ``` $this.append($("<option/>", { value: '', text: $(this).text() })); ```
19,436,277
I am writing an ember app, and not using rails nor grunt for anything. I previously had a short python program that took text files and did some `markdown` stuff with them, and then compiled them all to a `templates.js` file using `ember-precompile`: ``` ember-precompile templates/*.hbs -f templates/templates.js ``` This worked great until I upgraded ember, and now I'm getting this error. ``` Uncaught Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (>= 1.0.0) or downgrade your runtime to an older version (== 1.0.0-rc.3). ``` I need to upgrade my ember-precompile program, but solutions like [changing a grunt config](https://stackoverflow.com/questions/17131611/not-possible-to-use-the-latest-ember-with-pre-compiled-templates) or [changing gemfiles](https://stackoverflow.com/questions/16894417/handlebar-precompile-version-error-in-ember-rc5) are no good for me, since I'm not using either of those tools. Also, attempts to [upgrade](http://www.continuousthinking.com/2013/05/19/ember-precompile-for-ember-1-0-0-rc-3.html) or [reinstall](https://npmjs.org/package/ember-precompile) haven't made any changes at all. Ember version `Version: v1.0.0 Last commit: e2ea0cf (2013-08-31 23:47:39 -0700)` Handlebars version `Handlebars.VERSION = "1.0.0";` Feel free to fill in any gaps in my understanding. For short term development purposes I'm just going to put my templates in `index.html` but I want to do markdown stuff to my templates first, so that won't do forever.
2013/10/17
[ "https://Stackoverflow.com/questions/19436277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988335/" ]
``` var $this = $(this); $('p a').each(function(){ $this.append('<option value="">' + $(this).text() + '</option>'); }); ``` <http://jsfiddle.net/QgCqE/1/>
To make the loop in your elements use [$.each](http://api.jquery.com/each/) --- You dont need extend jQuery unless you want to make it reusable. `[**LIVE DEMO**](http://jsfiddle.net/pT6rs/)` ``` $.fn.populate = function(el) { var options = ''; $(el).each(function(i, e) { options += '<option>' + $(this).text() + '</option>'; }); this.append(options); return this; } $('#select').populate('p > a'); ```
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
You seek the all-powerful `*?` From the docs, [Greedy versus Non-Greedy](http://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy) > > the non-greedy qualifiers `*?`, `+?`, `??`, or `{m,n}?` [...] match as *little* > text as possible. > > >
Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of `.*` -- what about this? ``` groups = re.search(r"\([^)]*\)", x) ```
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of `.*` -- what about this? ``` groups = re.search(r"\([^)]*\)", x) ```
To start with, I do not suggest using "\*" in regexes. Yes, I know, it is the most used multi-character delimiter, but it is nevertheless a bad idea. This is because, while it does match any amount of repetition for that character, "any" includes 0, which is usually something you want to throw a syntax error for, not accept. Instead, I suggest using the `+` sign, which matches any repetition of length > 1. What's more, from what I can see, you are dealing with fixed-length parenthesized expressions. As a result, you can probably use the `{x, y}` syntax to specifically specify the desired length. However, if you really do need non-greedy repetition, I suggest consulting the all-powerful `?`. This, when placed after at the end of any regex repetition specifier, will force that part of the regex to find the least amount of text possible. That being said, I would be very careful with the `?` as it, like the Sonic Screwdriver in Dr. Who, has a tendency to do, how should I put it, "slightly" undesired things if not carefully calibrated. For example, to use your example input, it would identify `((1)` (note the lack of a second rparen) as a match.
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
Would not `\\(.*?\\)` work? That is the non-greedy syntax.
To start with, I do not suggest using "\*" in regexes. Yes, I know, it is the most used multi-character delimiter, but it is nevertheless a bad idea. This is because, while it does match any amount of repetition for that character, "any" includes 0, which is usually something you want to throw a syntax error for, not accept. Instead, I suggest using the `+` sign, which matches any repetition of length > 1. What's more, from what I can see, you are dealing with fixed-length parenthesized expressions. As a result, you can probably use the `{x, y}` syntax to specifically specify the desired length. However, if you really do need non-greedy repetition, I suggest consulting the all-powerful `?`. This, when placed after at the end of any regex repetition specifier, will force that part of the regex to find the least amount of text possible. That being said, I would be very careful with the `?` as it, like the Sonic Screwdriver in Dr. Who, has a tendency to do, how should I put it, "slightly" undesired things if not carefully calibrated. For example, to use your example input, it would identify `((1)` (note the lack of a second rparen) as a match.
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
You seek the all-powerful `*?` From the docs, [Greedy versus Non-Greedy](http://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy) > > the non-greedy qualifiers `*?`, `+?`, `??`, or `{m,n}?` [...] match as *little* > text as possible. > > >
``` >>> x = "a (b) c (d) e" >>> re.search(r"\(.*\)", x).group() '(b) c (d)' >>> re.search(r"\(.*?\)", x).group() '(b)' ``` [According to the docs](http://docs.python.org/library/re.html#regular-expression-syntax): > > The '`*`', '`+`', and '`?`' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE `<.*>` is matched against '`<H1>title</H1>`', it will match the entire string, and not just '`<H1>`'. Adding '`?`' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using `.*?` in the previous expression will match only '`<H1>`'. > > >
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
``` >>> x = "a (b) c (d) e" >>> re.search(r"\(.*\)", x).group() '(b) c (d)' >>> re.search(r"\(.*?\)", x).group() '(b)' ``` [According to the docs](http://docs.python.org/library/re.html#regular-expression-syntax): > > The '`*`', '`+`', and '`?`' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE `<.*>` is matched against '`<H1>title</H1>`', it will match the entire string, and not just '`<H1>`'. Adding '`?`' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using `.*?` in the previous expression will match only '`<H1>`'. > > >
Would not `\\(.*?\\)` work? That is the non-greedy syntax.
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
``` >>> x = "a (b) c (d) e" >>> re.search(r"\(.*\)", x).group() '(b) c (d)' >>> re.search(r"\(.*?\)", x).group() '(b)' ``` [According to the docs](http://docs.python.org/library/re.html#regular-expression-syntax): > > The '`*`', '`+`', and '`?`' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE `<.*>` is matched against '`<H1>title</H1>`', it will match the entire string, and not just '`<H1>`'. Adding '`?`' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using `.*?` in the previous expression will match only '`<H1>`'. > > >
As the others have said using the ? modifier on the \* quantifier will solve your immediate problem, but be careful, you are starting to stray into areas where regexes stop working and you need a parser instead. For instance, the string "(foo (bar)) baz" will cause you problems.
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
``` >>> x = "a (b) c (d) e" >>> re.search(r"\(.*\)", x).group() '(b) c (d)' >>> re.search(r"\(.*?\)", x).group() '(b)' ``` [According to the docs](http://docs.python.org/library/re.html#regular-expression-syntax): > > The '`*`', '`+`', and '`?`' qualifiers are all greedy; they match as much text as possible. Sometimes this behavior isn’t desired; if the RE `<.*>` is matched against '`<H1>title</H1>`', it will match the entire string, and not just '`<H1>`'. Adding '`?`' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using `.*?` in the previous expression will match only '`<H1>`'. > > >
Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of `.*` -- what about this? ``` groups = re.search(r"\([^)]*\)", x) ```
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
You seek the all-powerful `*?` From the docs, [Greedy versus Non-Greedy](http://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy) > > the non-greedy qualifiers `*?`, `+?`, `??`, or `{m,n}?` [...] match as *little* > text as possible. > > >
Do you want it to match "(b)"? Do as Zitrax and Paolo have suggested. Do you want it to match "b"? Do ``` >>> x = "a (b) c (d) e" >>> re.search(r"\((.*?)\)", x).group(1) 'b' ```
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
You seek the all-powerful `*?` From the docs, [Greedy versus Non-Greedy](http://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy) > > the non-greedy qualifiers `*?`, `+?`, `??`, or `{m,n}?` [...] match as *little* > text as possible. > > >
As the others have said using the ? modifier on the \* quantifier will solve your immediate problem, but be careful, you are starting to stray into areas where regexes stop working and you need a parser instead. For instance, the string "(foo (bar)) baz" will cause you problems.
766,372
How do I make a python regex like `"(.*)"` such that, given `"a (b) c (d) e"` python matches `"b"` instead of `"b) c (d"`? I know that I can use `"[^)]"` instead of `"."`, but I'm looking for a more general solution that keeps my regex a little cleaner. Is there any way to tell python "hey, match this as soon as possible"?
2009/04/19
[ "https://Stackoverflow.com/questions/766372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83435/" ]
Would not `\\(.*?\\)` work? That is the non-greedy syntax.
Using an ungreedy match is a good start, but I'd also suggest that you reconsider any use of `.*` -- what about this? ``` groups = re.search(r"\([^)]*\)", x) ```
2,246,571
I'm trying to encrypt/decrypt files in flex (AIR) using the *as3crypto* package. the problem is that when attempting to process slightly large files (over 5M) the process time gets ridiculously long and the client freezes (get the "not responding" title) so i tried to go Async and encrypt/decrypt a chunk at a time and interlace it with the frame refresh rate. the encryption goes smooth, or so it seems, but when i try to decrypt the result back to the original document i get a padding error: "**Error: PKCS#5:unpad: Invalid padding value. expected [252], found [152]**" my code is like so (between initiation and finalization): * the **run** method gets called repeatedly until the file is completed * \_**buffer** contains the byte array from the source file * \_**result** the result * **CHUNK** is the bite size of bytes that i process each time * the cipher is initiated as: Crypto.getCipher("aes-ecb", \_key, Crypto.getPad("pkcs5")); ``` public function run(data:Object):Boolean{ if((_buffer.length-_position)>CHUNK){ processChunk(_position,CHUNK); _position += CHUNK; var e:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS,false,false,_position,_buffer.length); this.dispatchEvent(e); return true; }else if(!_isFinnalized){ processChunk(_position,_buffer.length - _position); this.dispatchEvent(new Event(Event.COMPLETE)); finnalize(); } return false; } private function processChunk(position:uint,chunk:uint):void{ var buffer:ByteArray = new ByteArray(); buffer.writeBytes(_buffer,position,chunk); if(_action==ENCRYPT){ _aes.encrypt(buffer); }else{ _aes.decrypt(buffer); } _result.writeBytes(buffer); } ``` help me, please!
2010/02/11
[ "https://Stackoverflow.com/questions/2246571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242796/" ]
At first glance it looks like this line: ``` string lastrec = ds.Tables[0].Rows[cnt+1][1].ToString(); ``` cnt+1 is out of the bounds of the collection, and an exception probably told you this. You are probably looking for cnt-1.
I'd probably write ``` int newpcode = int.Parse(lastrec) - 1; ``` as ``` int newpcode = 0; if(Int32.TryParse(lastrec, out newpcode)) { newpcode--; } ``` That way, if it can successfully parse the lastrec, it will decrement. If it can't successfully parse, your newpcode will be 0, but will not throw an error.
14,910,554
I'm trying to disable some portions of my html pages. I read that you can use a transparent div with absolute position on top of your page to prevent clicking on elements beyond it, but is there a way to accomplish this only on a portion of a page (let's assume this portion is all contained in a div) without the use of absolute position?
2013/02/16
[ "https://Stackoverflow.com/questions/14910554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/517354/" ]
Put `position: relative` on the div you want to disable, then add the transparent blocking div as a child of this div with `position: absolute` and `top`, `bottom`, `left`, `right` equal to 0. If you are unable to put `position: relative` on the div you want to disable then it will be a bit more difficult as you need to compute it's dimensions and offset and then position the transparent mask as a child of the body and at the exact same position as the element you need to disable. JS frameworks (as jQuery) usually provide you with ways to determine a box's [offset relative to the document](http://api.jquery.com/offset/).
Make a little 1px x 1px transparent image and save it as a .png file. In the CSS for your DIV, use this code ``` background:transparent url('/images/transparent-bg.png') repeat center top; ``` Remember to change the file path to your transperant image. I think this solution works in all browsers, maybe except for IE 6, but I haven't tested it.
23,954,898
I am having a bit of an issue here. I have an MVC application that has been deployed to IIS 7 on Windows Server 2008. In Visual Studio 2012, whenever an internal server error occurs i.e. http 500, it shows the page I designed for it. However, when I deploy it to IIS, it shows a blank page which could be very annoying because one does not see the application's page at all. All I need is for the error page to display instead of the blank page that it currently displays as a deployed application in the client's site. I can then work on fixing the error in Visual Studio. Kindly pardon me if I broke any rules of S.O. Here is what I have setup in my ErrorController.cs ``` public ActionResult ForbiddenPage() { Response.StatusCode = 403; Response.TrySkipIisCustomErrors = true; // add this line return View(); } // // GET: /Error/ public ActionResult PageNotFound() { Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; // add this line return View(); } // // GET: /Error/ public ActionResult InternalServerError() { Response.StatusCode = 500; Response.TrySkipIisCustomErrors = true; // add this line return View(); } ``` In web.config, this is what I have: ``` <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." ... </handlers> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="403" /> <error statusCode="403" responseMode="ExecuteURL" path="/Error/ForbiddenPage" /> <remove statusCode="404" /> <error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" /> <remove statusCode="500" /> <error statusCode="500" responseMode="ExecuteURL" path="/Error/InternalServerError"/> </httpErrors> </system.webServer> ``` My RouteConfig.cs Looks like this ``` routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "LogIn",id = UrlParameter.Optional } ); routes.MapRoute( "403-ForbiddenPage", "{*url}", new { controller = "Error", action = "ForbiddenPage" } ); routes.MapRoute( "404-PageNotFound", "{*url}", new { controller = "Error", action = "PageNotFound" } ); routes.MapRoute( "500-InternalServerError", "{*url}", new { controller = "Error", action = "InternalServerError" } ); ``` The View that should be displayed is below: ``` @{ ViewBag.Title = "Internal Server Error"; Layout = "~/Views/Shared/_LayoutError.cshtml"; } <h2></h2> <div class="list-header clearfix"> <span>Internal Server Error</span> </div> <div class="list-sfs-holder"> <div class="alert alert-error"> An unexpected error has occurred.... click<a href ="/Home/LogIn"><i><u>here</u></i> </a> to login again.. </div> </div> ``` If there is any thing that I should have included to aid you in proffering a solution, please let me know in the comments.
2014/05/30
[ "https://Stackoverflow.com/questions/23954898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/464512/" ]
`file:///android_asset` is only for use with `WebView`. I do not know what `ImageLoader` is, but see if it accepts an `InputStream`. If so, use `AssetManager` and `open()` to get an `InputStream` on your desired asset.
I think the URI usage is something like this for assests folder ``` String imageUri = "assets://image.png"; imageLoader.displayImage(imageUri, imageView); ``` Just check [this](https://github.com/nostra13/Android-Universal-Image-Loader#acceptable-uris-examples) reference So your change your code something like this ``` ImageLoader.getInstance().displayImage(String.format("assets:///img/categories/%d.JPG", category.getId()), mImageIv); ``` or even load it from SDCard like this ``` String imageUri = "file:///mnt/sdcard/image.png"; ``` Let me know if this works
23,954,898
I am having a bit of an issue here. I have an MVC application that has been deployed to IIS 7 on Windows Server 2008. In Visual Studio 2012, whenever an internal server error occurs i.e. http 500, it shows the page I designed for it. However, when I deploy it to IIS, it shows a blank page which could be very annoying because one does not see the application's page at all. All I need is for the error page to display instead of the blank page that it currently displays as a deployed application in the client's site. I can then work on fixing the error in Visual Studio. Kindly pardon me if I broke any rules of S.O. Here is what I have setup in my ErrorController.cs ``` public ActionResult ForbiddenPage() { Response.StatusCode = 403; Response.TrySkipIisCustomErrors = true; // add this line return View(); } // // GET: /Error/ public ActionResult PageNotFound() { Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; // add this line return View(); } // // GET: /Error/ public ActionResult InternalServerError() { Response.StatusCode = 500; Response.TrySkipIisCustomErrors = true; // add this line return View(); } ``` In web.config, this is what I have: ``` <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." ... </handlers> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="403" /> <error statusCode="403" responseMode="ExecuteURL" path="/Error/ForbiddenPage" /> <remove statusCode="404" /> <error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" /> <remove statusCode="500" /> <error statusCode="500" responseMode="ExecuteURL" path="/Error/InternalServerError"/> </httpErrors> </system.webServer> ``` My RouteConfig.cs Looks like this ``` routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "LogIn",id = UrlParameter.Optional } ); routes.MapRoute( "403-ForbiddenPage", "{*url}", new { controller = "Error", action = "ForbiddenPage" } ); routes.MapRoute( "404-PageNotFound", "{*url}", new { controller = "Error", action = "PageNotFound" } ); routes.MapRoute( "500-InternalServerError", "{*url}", new { controller = "Error", action = "InternalServerError" } ); ``` The View that should be displayed is below: ``` @{ ViewBag.Title = "Internal Server Error"; Layout = "~/Views/Shared/_LayoutError.cshtml"; } <h2></h2> <div class="list-header clearfix"> <span>Internal Server Error</span> </div> <div class="list-sfs-holder"> <div class="alert alert-error"> An unexpected error has occurred.... click<a href ="/Home/LogIn"><i><u>here</u></i> </a> to login again.. </div> </div> ``` If there is any thing that I should have included to aid you in proffering a solution, please let me know in the comments.
2014/05/30
[ "https://Stackoverflow.com/questions/23954898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/464512/" ]
`file:///android_asset` is only for use with `WebView`. I do not know what `ImageLoader` is, but see if it accepts an `InputStream`. If so, use `AssetManager` and `open()` to get an `InputStream` on your desired asset.
Here's a (simplified!) helper routine that will open the asset as an `InputStream` if the URI uses the `file:///android_asset/` pattern: ``` public static InputStream open(String urlString, Context context) throws IOException { URI uri = URI.create(urlString); if (uri.getScheme().equals("file") && uri.getPath().startsWith("/android_asset/")) { String path = uri.getPath().replace("/android_asset/", ""); // TODO: should be at start only return context.getAssets().open(path); } else { return uri.toURL().openStream(); } } ``` Usage like: ``` InputSteam is = Helper.open("file:///android_asset/img/categories/001.JPG", this); // "this" is an Activity, for example ``` Not shown: exception handling.
23,954,898
I am having a bit of an issue here. I have an MVC application that has been deployed to IIS 7 on Windows Server 2008. In Visual Studio 2012, whenever an internal server error occurs i.e. http 500, it shows the page I designed for it. However, when I deploy it to IIS, it shows a blank page which could be very annoying because one does not see the application's page at all. All I need is for the error page to display instead of the blank page that it currently displays as a deployed application in the client's site. I can then work on fixing the error in Visual Studio. Kindly pardon me if I broke any rules of S.O. Here is what I have setup in my ErrorController.cs ``` public ActionResult ForbiddenPage() { Response.StatusCode = 403; Response.TrySkipIisCustomErrors = true; // add this line return View(); } // // GET: /Error/ public ActionResult PageNotFound() { Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; // add this line return View(); } // // GET: /Error/ public ActionResult InternalServerError() { Response.StatusCode = 500; Response.TrySkipIisCustomErrors = true; // add this line return View(); } ``` In web.config, this is what I have: ``` <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." ... </handlers> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="403" /> <error statusCode="403" responseMode="ExecuteURL" path="/Error/ForbiddenPage" /> <remove statusCode="404" /> <error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" /> <remove statusCode="500" /> <error statusCode="500" responseMode="ExecuteURL" path="/Error/InternalServerError"/> </httpErrors> </system.webServer> ``` My RouteConfig.cs Looks like this ``` routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "LogIn",id = UrlParameter.Optional } ); routes.MapRoute( "403-ForbiddenPage", "{*url}", new { controller = "Error", action = "ForbiddenPage" } ); routes.MapRoute( "404-PageNotFound", "{*url}", new { controller = "Error", action = "PageNotFound" } ); routes.MapRoute( "500-InternalServerError", "{*url}", new { controller = "Error", action = "InternalServerError" } ); ``` The View that should be displayed is below: ``` @{ ViewBag.Title = "Internal Server Error"; Layout = "~/Views/Shared/_LayoutError.cshtml"; } <h2></h2> <div class="list-header clearfix"> <span>Internal Server Error</span> </div> <div class="list-sfs-holder"> <div class="alert alert-error"> An unexpected error has occurred.... click<a href ="/Home/LogIn"><i><u>here</u></i> </a> to login again.. </div> </div> ``` If there is any thing that I should have included to aid you in proffering a solution, please let me know in the comments.
2014/05/30
[ "https://Stackoverflow.com/questions/23954898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/464512/" ]
I think the URI usage is something like this for assests folder ``` String imageUri = "assets://image.png"; imageLoader.displayImage(imageUri, imageView); ``` Just check [this](https://github.com/nostra13/Android-Universal-Image-Loader#acceptable-uris-examples) reference So your change your code something like this ``` ImageLoader.getInstance().displayImage(String.format("assets:///img/categories/%d.JPG", category.getId()), mImageIv); ``` or even load it from SDCard like this ``` String imageUri = "file:///mnt/sdcard/image.png"; ``` Let me know if this works
Here's a (simplified!) helper routine that will open the asset as an `InputStream` if the URI uses the `file:///android_asset/` pattern: ``` public static InputStream open(String urlString, Context context) throws IOException { URI uri = URI.create(urlString); if (uri.getScheme().equals("file") && uri.getPath().startsWith("/android_asset/")) { String path = uri.getPath().replace("/android_asset/", ""); // TODO: should be at start only return context.getAssets().open(path); } else { return uri.toURL().openStream(); } } ``` Usage like: ``` InputSteam is = Helper.open("file:///android_asset/img/categories/001.JPG", this); // "this" is an Activity, for example ``` Not shown: exception handling.
35,290,070
Story for context: I have an ePetition type service running on my site which I email people a link where they can 'agree' to the petition. This link will only contain the 'petitionID' and 'username' of the person who sent it. This information isn't particularly sensitive but I still require it to be tamper-proof because I want them to be able to accept without signing in or storing values in the database. I thought of using Java's String.hashCode() function. Maybe having the url as: username, petitionId and then a hash ``` www.website.com/accept.jsp?user='username'&id='petid'&token='1039678106' ``` The token could be made up of username + id(from the link) + datePetitionStarted(like the salt not exposed in the url) like: ``` String test = "mike.Who@petitionwebsite.com+1524+09/02/2016"; System.out.println(test.hashCode()); ``` This would give me a hash of '1039678106' which means server side, I can take the ID parameter, the username of the person and use the datePetitionStarted, get the hashcode and compare them. Do you think this is a valid way of preventing tampering? I'm really after a token-type method of accepting petitions so if anyone has any other ideas that would be awesome. thanks, Mike
2016/02/09
[ "https://Stackoverflow.com/questions/35290070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3364482/" ]
Here's what I did (which is practically tamper-proof). I don't use java script as users can disable it anyway. I simply create a UUID, (which is stored in a database next to user details) and then create a link sent in an email during the registration process. ``` http://my_domain_name/Activate?key=6faeecf5-9ab3-46f4-9785-321a5bbe2ace ``` When the user clicks on the link above, the server side code checks that this key actually exists in the database, in which case it activates the user account.
While the String.hashcode() may return the same value for the same string across instances, this is not guaranteed. > > Whenever it is invoked on the same object more than once during an > execution of a Java application, the hashCode method must consistently > return the same integer, provided no information used in equals > comparisons on the object is modified. **This integer need not remain > consistent from one execution of an application to another execution > of the same application.** > > > API docs for [Object.hashcode](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()). As such, if you were to down down this route you should use your own hash.
196,146
I have andersen 400-series windows throughout the house. I'm renovating the attic so the trim and wallboard are off revealing this situation: [![photo of window in rough opening](https://i.stack.imgur.com/8m7M0.jpg)](https://i.stack.imgur.com/8m7M0.jpg) The window is not attached to the rough opening on the sides or top. It just sits on that stack of 2x4s at the bottom and the flange is nailed to the sheathing on the outside. I checked Andersen install instructions and they don't specify that you have to nail to the rough opening but they do say to shim them; no shims anywhere (the thing on the left is a cut strap). If I push on the window frame, the whole thing moves a bit as the flange flexes. The stack of 2x4s that it's sitting on seems to be nailed together top to bottom but not toe-nailed to the sides of the rough opening so that rocks slightly too. Fiberglass insulation tucked in on the sides but not the top. This window has maybe 1/2" space there but the other one (other side of house, same situation) has about 1-1/2" of empty gap. I see some sunlight through the gap and flange but I don't see any signs of leakage. I had some of the other windows replaced and I don't think there's flashing tape over the flanges on the outside. No flashing over sill. Wimpy looking header, and those are collar ties above, not joists, so there's only a few feet between the top of that window and the ridge of the roof. All the windows were installed at once around 2000 under previous owners so it survived like this for nearly 20 years. My guess all the windows are installed about the same. I'll toe-nail that stack of 2x's to the trimmers on the sides and foam the gap around the windows. Should I be concerned or is this ok? Does the window need to be attach the inside of the rough opening somehow? Does there need to be a proper header above the window? **Edit**: The house was built in the early 50s. These windows were installed around 2000. The dark brown wood (full studs and top header board) are original construction, old growth douglas fir lumber, generally very solid. The lighter wood inside that was added during the window replacement. Reasonably certain the frames originally held larger windows. They built up the sides of the rough opening to hold smaller flanged replacement units. The outside was wood shakes originally and vinyl siding was installed *over* that at the same time as these windows went in.
2020/06/26
[ "https://diy.stackexchange.com/questions/196146", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/-1/" ]
There are a lot of problems with that install. But I do know that you do NOT want to nail the window frame to the rough opening on the sides. The flanges that are nailed to the sheathing provide all of the support. Usually there are shims underneath the window at the bottom to 1) bring the window up to the right height in the opening and 2) ensure that the bottom of the window is horizontal. I used these windows myself. Note that most of the movement you noticed would be prevented when the inside trim is installed, which would tie the inside of the window to the walls. **EDIT 1 - Other Shortcomings** A header, of the appropriate size for the opening, is definitely needed if the the wall is load bearing, Even if that's not the case, I would frame the window with a minimum header just to strengthen the opening. I notice that there is a header of sorts - two 2x4s laid on their sides. I have to defer to those with more experience as to whether this meets my "minimum header" need. I would also have done the standard king-jack stub framing for the window. There definitely should be flashing at the bottom of the rough opening, the sides, and the top of the outside of the window. The Anderson installation instructions provide details on this, and there are lots of on-line resources you can consult also. Finally, 20 years is not a very long time for a window. I still have 65 year old original windows in parts of my house, and many historic structures have windows going back hundreds of years. **EDIT 2 - Added picture** Here's a picture with the low-expansion rate foam used. [![enter image description here](https://i.stack.imgur.com/RhJwo.png)](https://i.stack.imgur.com/RhJwo.png)
+1 For getting the Andersen instructions. I installed 21 Series 400 replacement windows a few years back. Not sure what you have here. The basic flow for them, is to level the sill, caulk it, and drop the frame in. Then you start with screws from the top, within the track, from the frame into the rough in, shimming and checking for plumb and square. I think there were 4 screws per side, you also have to check to keep the width even. When you're all done, then you insulate the gaps and cut the exterior trim to fit.
29,511
When I try to view a public document ([example found on the net](https://docs.google.com/document/d/101OVq5lIYOJANVvTGuWCcmlA9XIHL5iUymU6noOApbI/edit)) with my Google Apps account I get this screen: ![Google Drive. You need permission to access this item.](https://i.stack.imgur.com/8oKLS.png) Clicking on the button will send an email to whoever created it, and then I have to wait for them to give me permission. On my standard Google Account, I can view public documents straightaway. Why is this? Note: I have my Apps account set up to use Docs, and have been using them myself. **Edit: I tried in another browser, without even being signed in I can view these docs.**
2012/07/31
[ "https://webapps.stackexchange.com/questions/29511", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/10400/" ]
**Your Google Apps admin has not allowed users to receive documents from outside your domain.** One of the [sharing options you can set for Docs & Drive within a Google Apps account](http://support.google.com/a/bin/answer.py?hl=en&answer=60781) is weither or not users can share documents to people outside the organisation. One sub-option of this is that they can separately allow or deny users from receiving outside documents > > As the administrator, you determine whether users can share their > Google Docs (documents, presentations, spreadsheets, and drawings) > outside your organization, **whether they can access docs created > outside your organization**, and the default visibility level for new > docs. > > > ![Google Apps admin Document sharing options](https://i.stack.imgur.com/vozAF.jpg) --- **If you are the administrator of the domain you can change the settings via:** 1. Sign in to the Google Apps administrator control panel. 2. Click the Settings tab and then select Drive and Docs in the left column. 3. In the Sharing options section, choose whether users can share docs outside your organization. 4. Hit Save I'm not sure if this is on or off by default but just ask your admin if they can allow outside sharing. Worst case is they will say no because of X.
Unexpectedly last week, my visitors couldn't access my public docs. I verified had "Users can share". Was still getting errors. My solution was to: 1. Select **Users cannot share**. 2. Save. 3. Select **Users can share**. 4. Save. This was enough to fix the permissions.
3,658,571
I have this code that adds dotted lines under text in text box: ``` // Create an underline text decoration. Default is underline. TextDecoration myUnderline = new TextDecoration(); // Create a linear gradient pen for the text decoration. Pen myPen = new Pen(); myPen.Brush = new LinearGradientBrush(Colors.White, Colors.White, new Point(0, 0.5), new Point(1, 0.5)); myPen.Brush.Opacity = 0.5; myPen.Thickness = 1.0; myPen.DashStyle = DashStyles.Dash; myUnderline.Pen = myPen; myUnderline.PenThicknessUnit = TextDecorationUnit.FontRecommended; // Set the underline decoration to a TextDecorationCollection and add it to the text block. TextDecorationCollection myCollection = new TextDecorationCollection(); myCollection.Add(myUnderline); PasswordSendMessage.TextDecorations = myCollection; ``` My problem is I need only the last 6 characters in the text to be formatted! Any idea how can I achieve that?
2010/09/07
[ "https://Stackoverflow.com/questions/3658571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441418/" ]
Instead of setting the property on the entire TextBlock, create a TextRange for the last six characters and apply the formatting to that: ``` var end = PasswordSendMessage.ContentEnd; var start = end.GetPositionAtOffset(-6) ?? PasswordSendMessage.ContentStart; var range = new TextRange(start, end); range.ApplyPropertyValue(Inline.TextDecorationsProperty, myCollection); ``` If PasswordSendMessage is a TextBox rather than a TextBlock, then you cannot use rich text like this. You can use a RichTextBox, in which case this technique will work but you will need to use `PasswordSendMessage.Document.ContentEnd` and `PasswordSendMessage.Document.ContentStart` instead of `PasswordSendMessage.ContentEnd` and `PasswordSendMessage.ContentStart`.
You could databind your text to the Inlines property of TextBox and make a converter to build the run collection with a seperate Run for the last 6 characters applying your decorations
7,535,530
I want to implement a JQuery script that requires the browser's width at 100% which depends solely on the user's viewing resolution. Can i prepare multiple scripts for the different resolutions for the browser to automatically detect and choose or does there need to be a single script with if/then clauses?
2011/09/23
[ "https://Stackoverflow.com/questions/7535530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962058/" ]
The success callback doesn't operate on the same `this` that the click handler does. Save it in a variable: ``` $('.deleteQuestion').live('click', function(){ var element = $(this); $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){ //this has to be a function, not a jQuery chain. $('[what="question"][name="' + element.attr('name') + '"]').remove();} } }); }); ```
In the first version `$(this).attr('name')` is evaluated right away. In the second version `this` is not pointing to the current element since it only gets evaluated when the callback function executes, which is in a different context - so it won't work correctly.
7,535,530
I want to implement a JQuery script that requires the browser's width at 100% which depends solely on the user's viewing resolution. Can i prepare multiple scripts for the different resolutions for the browser to automatically detect and choose or does there need to be a single script with if/then clauses?
2011/09/23
[ "https://Stackoverflow.com/questions/7535530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962058/" ]
The success callback doesn't operate on the same `this` that the click handler does. Save it in a variable: ``` $('.deleteQuestion').live('click', function(){ var element = $(this); $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){ //this has to be a function, not a jQuery chain. $('[what="question"][name="' + element.attr('name') + '"]').remove();} } }); }); ```
I think in this instance neither are working as you intend. In the first version, you have the following: ``` success: $('[what="question"][name="' + $(this).attr('name') + '"]').remove() ``` This is executed as soon as the line is reached and not on the success callback. In the 2nd version, you lose the context of this in your callback: ``` success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();} ``` Also, it looks like you have an additional end brace. ``` remove();} } ``` Try the following: ``` $('.deleteQuestion').live('click', function(){ var self = this; $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){$('[what="question"][name="' + $(self).attr('name') + '"]').remove();} }); }); ```
7,535,530
I want to implement a JQuery script that requires the browser's width at 100% which depends solely on the user's viewing resolution. Can i prepare multiple scripts for the different resolutions for the browser to automatically detect and choose or does there need to be a single script with if/then clauses?
2011/09/23
[ "https://Stackoverflow.com/questions/7535530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962058/" ]
The success callback doesn't operate on the same `this` that the click handler does. Save it in a variable: ``` $('.deleteQuestion').live('click', function(){ var element = $(this); $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){ //this has to be a function, not a jQuery chain. $('[what="question"][name="' + element.attr('name') + '"]').remove();} } }); }); ```
`this` is not pointing to what you what in the success function. Try this instead: ``` $('.deleteQuestion').live('click', function() { var that = this; $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function() { $('[what="question"][name="' + $(that).attr('name') + '"]').remove(); } }); }); ```
25,191,954
I am learning qt, and experimenting with examples from a textbook. The original textbook code has the following, set up to save and close on the x button: ``` void MainWindow::closeEvent(QCloseEvent *event) { if (okToContinue()) { writeSettings(); event->accept(); } else { event->ignore(); } } ``` i experimented with a simple exit in its menu - and it works: ``` void MainWindow::close() { if (okToContinue()) { QApplication::quit(); } } ``` But I want to take advantage of the already written closeEvent, so i replaced the code above with ``` void MainWindow::close() { QCloseEvent *event = new QCloseEvent(); closeEvent(event); } ``` I get the checking for changes and saving app, implemented through the okToContinue function. But the application does not close. i tried to follow through debugging and.. with my small understanding, it seems that there is a close signal being sent... I don't have a good understanding of this, can somebody please help me figure out what am i doing wrong and how to fix it ? (the sample code is from C++ GUI Programming with Qt 4, chapter 3)
2014/08/07
[ "https://Stackoverflow.com/questions/25191954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1217150/" ]
You don't have to reimplement MainWindow::close() in your subclass. From the Qt Docs: > > ...QCloseEvent sent when you call QWidget::close() to close a widget > programmatically... > > > So you just have to reimplement MainWindow::closeEvent(QCloseEvent \*event) if you want to control this event. This event fires when you click `x` or call close() from the code.
The `closeEvent` and related methods don't actually execute the action that happens when a given event is received. They merely allow you to act on the event and perhaps disable its further processing. The closing of the window is done within `QWidget::event`, where `closeEvent` is called from.
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
This is the "problem" that all of the myriad money laundering schemes attempt to solve. One of the fastest and most common ways to steal money and get away with it is by purchasing online giftcards to merchants like Amazon, Best Buy, Google Play, iTunes, etc. There are several online platforms where owners of giftcards can sell them to others. Typically they're sold at a discount to their face value. This is essentially the "fee" the criminals pay to launder their stolen money. In many cases, they will exchange the giftcards for cryptocurrencies such as bitcoin. The crypto can then be sent to a [coin mixing](https://en.m.wikipedia.org/wiki/Cryptocurrency_tumbler) service, which essentially disconnects the proceeds from the previous sequence of transactions beginning with the stolen money. They now can move this laundered crypto to their own accounts or sell it to get fiat currency back. The stolen money cannot be traced back to them. So to summarize, the steps are as follows: * Using the compromised banking information, purchase online giftcards. * Find a buyer and sell the giftcards online in exchange for cryptocurrency. * Send the crypto to a mixing service to disconnect from the previous chain of transactions * Transfer the crypto to your own custody or sell it on an exchange for fiat. If you're familiar with the three steps of money laundering, the first bullet point above is the "placement" step. The second and third bullet points are "layering." And the final bullet is "integration."
Some transfer methods are NOT reversible. They transfer your money to another victim, and trick them into sending Western Union or Bitcoin. ------------------------------------------------------------------------------------------------- Scammers work as teams and are running several scams at once. The other victim is in a scam like: * Overpayment scam: "I want to buy your €300 boogie board. Oops, I accidentally sent you €3000. Can you send the €2700 back Western Union?" * Employment scam: "We do QA testing of Bitcoin ATMs. Your job is to physically go to Bitcoin ATMs and make test deposits. We have sent you €3000. Deduct your €300 salary, then make this list of deposits summing to €2700". The other victim cannot reverse the money forwarding they did, because Western Union, Bitcoin, Venmo and several other transfer methods are non-reversible. Now you are in a "victim vs. victim" situation. One of you is left holding the bag.
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
There are wagonloads of schemes for making unsuspecting victims convert money from stolen accounts to real money, making others hold the bag. You can combine this with a dating scam: an online acquaintance in Russia becomes totally infatuated with you and wants to come over for a visit or marriage or whatever. But she insists on doing it on her own dime and transfers visa fees/ticket price/bribes/whatever to your bank account and needs you to pass this on to embassy/travel agency/officials/whatever with the account number and credentials she sends you. So it's "her" money; can't be a scam, can it? The police going after money transferred from an account via stolen credentials begs to differ. There are also online ads offering well-paying "jobs" for doing "payment processing" for a "foreign company". You receive money to your account and pass it on for a "fee". Again, until the police comes calling and you have to return the money (which you no longer have) that you sent elsewhere with a service that cannot be traced. Then there is "overpayment" for wares or services where you are to pass on the majority for "convenience" or whatever. There is no serious shortage of gullible fools for converting traceable money to untraceable money.
The answer is sometimes **not much**. Once in any of my (French) bank accounts, the hacker can obviously see what I have. In order to make a wire transfer * either the target account is "verified" and no extra steps are needed → but in order to "verify" an account there is an extra factor that is needed (an SMS to the registered number) * or the extra step above must be done ad-hoc. This means that, in theory at least, there is a "multifactor authentication" done on the wire transfer. Why "in theory"? Because there is the social engineering case @me mentions in another question, though access to the bank account ma help but is not the core of the fraud (some banks will ask you how much money you have with them as a "security question"). If you consolidated your accounts information in the hacked account, this can be used to prepare an attack on the other ones (also via social engineering, or hoping that the password is the same)
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
This is the "problem" that all of the myriad money laundering schemes attempt to solve. One of the fastest and most common ways to steal money and get away with it is by purchasing online giftcards to merchants like Amazon, Best Buy, Google Play, iTunes, etc. There are several online platforms where owners of giftcards can sell them to others. Typically they're sold at a discount to their face value. This is essentially the "fee" the criminals pay to launder their stolen money. In many cases, they will exchange the giftcards for cryptocurrencies such as bitcoin. The crypto can then be sent to a [coin mixing](https://en.m.wikipedia.org/wiki/Cryptocurrency_tumbler) service, which essentially disconnects the proceeds from the previous sequence of transactions beginning with the stolen money. They now can move this laundered crypto to their own accounts or sell it to get fiat currency back. The stolen money cannot be traced back to them. So to summarize, the steps are as follows: * Using the compromised banking information, purchase online giftcards. * Find a buyer and sell the giftcards online in exchange for cryptocurrency. * Send the crypto to a mixing service to disconnect from the previous chain of transactions * Transfer the crypto to your own custody or sell it on an exchange for fiat. If you're familiar with the three steps of money laundering, the first bullet point above is the "placement" step. The second and third bullet points are "layering." And the final bullet is "integration."
There are wagonloads of schemes for making unsuspecting victims convert money from stolen accounts to real money, making others hold the bag. You can combine this with a dating scam: an online acquaintance in Russia becomes totally infatuated with you and wants to come over for a visit or marriage or whatever. But she insists on doing it on her own dime and transfers visa fees/ticket price/bribes/whatever to your bank account and needs you to pass this on to embassy/travel agency/officials/whatever with the account number and credentials she sends you. So it's "her" money; can't be a scam, can it? The police going after money transferred from an account via stolen credentials begs to differ. There are also online ads offering well-paying "jobs" for doing "payment processing" for a "foreign company". You receive money to your account and pass it on for a "fee". Again, until the police comes calling and you have to return the money (which you no longer have) that you sent elsewhere with a service that cannot be traced. Then there is "overpayment" for wares or services where you are to pass on the majority for "convenience" or whatever. There is no serious shortage of gullible fools for converting traceable money to untraceable money.
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
Some transfer methods are NOT reversible. They transfer your money to another victim, and trick them into sending Western Union or Bitcoin. ------------------------------------------------------------------------------------------------- Scammers work as teams and are running several scams at once. The other victim is in a scam like: * Overpayment scam: "I want to buy your €300 boogie board. Oops, I accidentally sent you €3000. Can you send the €2700 back Western Union?" * Employment scam: "We do QA testing of Bitcoin ATMs. Your job is to physically go to Bitcoin ATMs and make test deposits. We have sent you €3000. Deduct your €300 salary, then make this list of deposits summing to €2700". The other victim cannot reverse the money forwarding they did, because Western Union, Bitcoin, Venmo and several other transfer methods are non-reversible. Now you are in a "victim vs. victim" situation. One of you is left holding the bag.
In addition to the many other cases described in the other answers: * If they managed to get an ATM card or other means of making withdrawals on an account (which is not theirs, obviously, or one they managed to create in the name of someone else), then they just transfer money from your account to that account, withdraw the money, and the trail ends. * They (directly or indirectly) transfer money to accounts in not-very-cooperative jurisdictions. Possibly add a few hops, and the trail becomes very difficult to trace. * They fund prepaid cards, and withdraw the money. Note how prepaid cards have become a lot less prevalent over the last few years, this is due to the headache for them to remain compliant with KYC/AML/CTF (Know Your Customer, Anti-Money Laundering, Counter Terrorism Financing) rules. Basically, the goal is to end up with the money in a form that is out of reach of the good guys. Cash, bitcoin, anonymous prepaid cards...
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
Compromised accounts are the backbone of a common "overpayment" scam. It works like this: Scammer takes control of Person A's bank account and uses it to overpay for something they buy from Person B on eBay, Nextdoor, etc. "Oops I accidentally sent you too much money. Please send the difference back to me with Western Union or Bitcoin or Apple gift cards or another non-reversible form." Person B complies. Person A discovers the fraudulent payment and reports it. Banks reverse it, money drains out of person B's account. But Person B's payment is gone forever. Person A has a major hassle to get their money back. Person B has no hope. They may additionally have overdrafts if they've moved money out of their account in the meantime. And technically they may fall afoul of money laundering rules. So the scammer gets paid without actually directing any money from Person A's account to themself.
Your doubts should be shared by everyone who comes to this afresh: the money trail should be traceable. May I assume everyone here understands the concept of a "burner" phone; one used for a very few calls - sometimes, only one - then thrown away? It's much harder to get a bank account than a phone subscription but when we compare "much harder" to "imposible", which one wins? At the end of a trail, the bad guys convert electric currency into either cash, or cashable vouchers, then close - or simply for evermore ignore - that account. Separately, this whole Question is one of the reasons no-one should be allowed an on-line banking account without first passing an industry-standard exam… Does anyone doubt that?
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
Your doubts should be shared by everyone who comes to this afresh: the money trail should be traceable. May I assume everyone here understands the concept of a "burner" phone; one used for a very few calls - sometimes, only one - then thrown away? It's much harder to get a bank account than a phone subscription but when we compare "much harder" to "imposible", which one wins? At the end of a trail, the bad guys convert electric currency into either cash, or cashable vouchers, then close - or simply for evermore ignore - that account. Separately, this whole Question is one of the reasons no-one should be allowed an on-line banking account without first passing an industry-standard exam… Does anyone doubt that?
The answer is sometimes **not much**. Once in any of my (French) bank accounts, the hacker can obviously see what I have. In order to make a wire transfer * either the target account is "verified" and no extra steps are needed → but in order to "verify" an account there is an extra factor that is needed (an SMS to the registered number) * or the extra step above must be done ad-hoc. This means that, in theory at least, there is a "multifactor authentication" done on the wire transfer. Why "in theory"? Because there is the social engineering case @me mentions in another question, though access to the bank account ma help but is not the core of the fraud (some banks will ask you how much money you have with them as a "security question"). If you consolidated your accounts information in the hacked account, this can be used to prepare an attack on the other ones (also via social engineering, or hoping that the password is the same)
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
In the United States, at least from my personal experience around 2017, they take the banking information, get an ATM card, and then start pulling cash from ATMs at convenience stores. Cash is harder to trace and easy to convert, and circumventing the security cameras on the ATMs basically comes down to wearing a hat and sunglasses such that you look like everyone else.
The answer is sometimes **not much**. Once in any of my (French) bank accounts, the hacker can obviously see what I have. In order to make a wire transfer * either the target account is "verified" and no extra steps are needed → but in order to "verify" an account there is an extra factor that is needed (an SMS to the registered number) * or the extra step above must be done ad-hoc. This means that, in theory at least, there is a "multifactor authentication" done on the wire transfer. Why "in theory"? Because there is the social engineering case @me mentions in another question, though access to the bank account ma help but is not the core of the fraud (some banks will ask you how much money you have with them as a "security question"). If you consolidated your accounts information in the hacked account, this can be used to prepare an attack on the other ones (also via social engineering, or hoping that the password is the same)
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
This is the "problem" that all of the myriad money laundering schemes attempt to solve. One of the fastest and most common ways to steal money and get away with it is by purchasing online giftcards to merchants like Amazon, Best Buy, Google Play, iTunes, etc. There are several online platforms where owners of giftcards can sell them to others. Typically they're sold at a discount to their face value. This is essentially the "fee" the criminals pay to launder their stolen money. In many cases, they will exchange the giftcards for cryptocurrencies such as bitcoin. The crypto can then be sent to a [coin mixing](https://en.m.wikipedia.org/wiki/Cryptocurrency_tumbler) service, which essentially disconnects the proceeds from the previous sequence of transactions beginning with the stolen money. They now can move this laundered crypto to their own accounts or sell it to get fiat currency back. The stolen money cannot be traced back to them. So to summarize, the steps are as follows: * Using the compromised banking information, purchase online giftcards. * Find a buyer and sell the giftcards online in exchange for cryptocurrency. * Send the crypto to a mixing service to disconnect from the previous chain of transactions * Transfer the crypto to your own custody or sell it on an exchange for fiat. If you're familiar with the three steps of money laundering, the first bullet point above is the "placement" step. The second and third bullet points are "layering." And the final bullet is "integration."
Your doubts should be shared by everyone who comes to this afresh: the money trail should be traceable. May I assume everyone here understands the concept of a "burner" phone; one used for a very few calls - sometimes, only one - then thrown away? It's much harder to get a bank account than a phone subscription but when we compare "much harder" to "imposible", which one wins? At the end of a trail, the bad guys convert electric currency into either cash, or cashable vouchers, then close - or simply for evermore ignore - that account. Separately, this whole Question is one of the reasons no-one should be allowed an on-line banking account without first passing an industry-standard exam… Does anyone doubt that?
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
This is the "problem" that all of the myriad money laundering schemes attempt to solve. One of the fastest and most common ways to steal money and get away with it is by purchasing online giftcards to merchants like Amazon, Best Buy, Google Play, iTunes, etc. There are several online platforms where owners of giftcards can sell them to others. Typically they're sold at a discount to their face value. This is essentially the "fee" the criminals pay to launder their stolen money. In many cases, they will exchange the giftcards for cryptocurrencies such as bitcoin. The crypto can then be sent to a [coin mixing](https://en.m.wikipedia.org/wiki/Cryptocurrency_tumbler) service, which essentially disconnects the proceeds from the previous sequence of transactions beginning with the stolen money. They now can move this laundered crypto to their own accounts or sell it to get fiat currency back. The stolen money cannot be traced back to them. So to summarize, the steps are as follows: * Using the compromised banking information, purchase online giftcards. * Find a buyer and sell the giftcards online in exchange for cryptocurrency. * Send the crypto to a mixing service to disconnect from the previous chain of transactions * Transfer the crypto to your own custody or sell it on an exchange for fiat. If you're familiar with the three steps of money laundering, the first bullet point above is the "placement" step. The second and third bullet points are "layering." And the final bullet is "integration."
In addition to the many other cases described in the other answers: * If they managed to get an ATM card or other means of making withdrawals on an account (which is not theirs, obviously, or one they managed to create in the name of someone else), then they just transfer money from your account to that account, withdraw the money, and the trail ends. * They (directly or indirectly) transfer money to accounts in not-very-cooperative jurisdictions. Possibly add a few hops, and the trail becomes very difficult to trace. * They fund prepaid cards, and withdraw the money. Note how prepaid cards have become a lot less prevalent over the last few years, this is due to the headache for them to remain compliant with KYC/AML/CTF (Know Your Customer, Anti-Money Laundering, Counter Terrorism Financing) rules. Basically, the goal is to end up with the money in a form that is out of reach of the good guys. Cash, bitcoin, anonymous prepaid cards...
146,435
Lately all the banks around here (Latvia) have been sending out warnings about scammers that try to get access to your online banking. Fair enough. But what confuses me is - so, what can they do after that? I mean, obviously they can transfer my money wherever, but... those transactions will be traceable. They'll just be leaving a trail of breadcrumbs leading straight to them. Sure, if they hoodwink just one or two people the bank might not notice (and not believe the victims, since all the operations will be properly authorized), however it's obviously gotten to the point where the banks are quite annoyed and would probably be very interested in tracking them down. So why don't they? What can the scammers do that can get them money yet leave them untraceable?
2021/11/21
[ "https://money.stackexchange.com/questions/146435", "https://money.stackexchange.com", "https://money.stackexchange.com/users/71680/" ]
Compromised accounts are the backbone of a common "overpayment" scam. It works like this: Scammer takes control of Person A's bank account and uses it to overpay for something they buy from Person B on eBay, Nextdoor, etc. "Oops I accidentally sent you too much money. Please send the difference back to me with Western Union or Bitcoin or Apple gift cards or another non-reversible form." Person B complies. Person A discovers the fraudulent payment and reports it. Banks reverse it, money drains out of person B's account. But Person B's payment is gone forever. Person A has a major hassle to get their money back. Person B has no hope. They may additionally have overdrafts if they've moved money out of their account in the meantime. And technically they may fall afoul of money laundering rules. So the scammer gets paid without actually directing any money from Person A's account to themself.
In addition to the many other cases described in the other answers: * If they managed to get an ATM card or other means of making withdrawals on an account (which is not theirs, obviously, or one they managed to create in the name of someone else), then they just transfer money from your account to that account, withdraw the money, and the trail ends. * They (directly or indirectly) transfer money to accounts in not-very-cooperative jurisdictions. Possibly add a few hops, and the trail becomes very difficult to trace. * They fund prepaid cards, and withdraw the money. Note how prepaid cards have become a lot less prevalent over the last few years, this is due to the headache for them to remain compliant with KYC/AML/CTF (Know Your Customer, Anti-Money Laundering, Counter Terrorism Financing) rules. Basically, the goal is to end up with the money in a form that is out of reach of the good guys. Cash, bitcoin, anonymous prepaid cards...
74,314,510
I am working on a Nodejs Express project and I keep getting 'Cannot GET /' error on Localhost. This is my server.js file ``` console.clear(); const express = require("express"); const app = express(); const dbConnect = require("./config/dbConnect"); require("dotenv").config(); dbConnect(); app.use(express.json()); app.use("/api/user", require("./routes/user")); app.use("/api/restaurant", require("./routes/restaurant")); app.use("/api/item", require("./routes/item")); app.use("/api/cart", require("./routes/cart")); app.use("/api/order", require("./routes/order")); const PORT = process.env.PORT; app.listen(PORT, (err) => err ? console.error(err) : console.log(` server is running on http://Localhost:${PORT}..`) ); ``` Can someone please tell me how to solve this?
2022/11/04
[ "https://Stackoverflow.com/questions/74314510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19801522/" ]
You can use the filter 'woocommerce\_sale\_flash' to remove default sale flash badge. try out this code. ``` add_action( 'woocommerce_before_shop_loop_item_title', 'new_badge', 3 ); function new_badge() { global $product; if ( $product->is_on_backorder(1) ) { add_filter('woocommerce_sale_flash', function (){return false;}); echo '<span class="out-of-stock-badge" data-shape="type-3">' . esc_html__( 'Out Of Stock', 'woocommerce' ) . '</span>'; } } ```
Add WooCommerce Sold Out Badge Storewide The most common scenario is the placement of the WooCommerce Sold Out badge across the store for all the products that have been sold out. This can be accomplished by placing the following code snippet in the functions.php file of the theme. add\_action( 'woocommerce\_before\_shop\_loop\_item\_title', function() { global $product; if ( !$product->is\_in\_stock() ) { ``` echo '<span class="now_sold">Now Sold</span>'; ``` } }); Place the following CSS code in the style.css file (located in the theme folder): .now\_sold { ``` background: #000080; color: #fff; font-size: 14px; font-weight: 700; padding: 6px 12px; position: absolute; right: 0; top: 0; ``` }
22,161,552
long time searcher but first time I'm posting a question. I am an IT student going into [haven't started yet] my second programming class. The first was just an intro to Java (we're talking basics really). I have been having a hard time with calling methods within the same class. I have attempted search-foo with poor results. A few articles pop up but they don't cover exactly what I'm looking for. Included is an example (quickly and probably poorly written) to get across what I'm asking. The basic gist [remember to stay with me since I'm new to programming in general] is that I want to add two numbers, creating a third, and have the system display the result... ``` public class MethodCallExample{ public static void main(String[] args){ int valueTwo = 3; MethodToCall(); int valueOne; int TrueValue = valueOne + valueTwo; System.out.println("The total value is " + TrueValue + "!"); } public static int MethodToCall(){ int valueOne = 2; return valueOne; } } ``` When I go to compile I get one of two errors depending on which derp I try to underp. If I compile as its' written, I receive a "valueOne might not have been initialized" error, and if I either move or remove -int valueOne - I receive "cannot find symbol" referring to valueOne. Any help is greatly appreciated since I am still learning. Sincerely, Hubert Farnsworth
2014/03/04
[ "https://Stackoverflow.com/questions/22161552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377218/" ]
When you call `MethodToCall`, you aren't doing anything with the returned value. You need to store the returned value in your variable i.e. ``` int valueOne = MethodToCall(); ```
It looks like you are confused with the variable scopes. Try doing ``` int valueOne = MethodToCall(); ``` Inside your main.
22,161,552
long time searcher but first time I'm posting a question. I am an IT student going into [haven't started yet] my second programming class. The first was just an intro to Java (we're talking basics really). I have been having a hard time with calling methods within the same class. I have attempted search-foo with poor results. A few articles pop up but they don't cover exactly what I'm looking for. Included is an example (quickly and probably poorly written) to get across what I'm asking. The basic gist [remember to stay with me since I'm new to programming in general] is that I want to add two numbers, creating a third, and have the system display the result... ``` public class MethodCallExample{ public static void main(String[] args){ int valueTwo = 3; MethodToCall(); int valueOne; int TrueValue = valueOne + valueTwo; System.out.println("The total value is " + TrueValue + "!"); } public static int MethodToCall(){ int valueOne = 2; return valueOne; } } ``` When I go to compile I get one of two errors depending on which derp I try to underp. If I compile as its' written, I receive a "valueOne might not have been initialized" error, and if I either move or remove -int valueOne - I receive "cannot find symbol" referring to valueOne. Any help is greatly appreciated since I am still learning. Sincerely, Hubert Farnsworth
2014/03/04
[ "https://Stackoverflow.com/questions/22161552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3377218/" ]
When you call `MethodToCall`, you aren't doing anything with the returned value. You need to store the returned value in your variable i.e. ``` int valueOne = MethodToCall(); ```
When you return something then you need a variable to hold the returned value.. so int valueone = methodtovalue(); would be correct.. Also note that the variable declared in a function would lose its scope when it is reaches the main program because the variable is declared in function. So valueone in function is different from the valueone declared in main() because valueone in function has its scope only within function and valueone in main has its scope till the end of mainprogram
223,143
I just bought a Powersaves Pro system four days ago, with no problems, except with one game. Animal Crossing: New Leaf. This game was the one I was actually most excited to use. Whenever I tried using the 999,999,999 bells code it always stopped in the second loading section "Uploading Save" about a quarter into it. This also happened with the other codes. Although, I tried getting codes for other games and it worked perfectly. (Mario Kart 7, Pokèmon Omega Ruby) I've taken down my firewall, restarted my computer, downloaded the program again, checked my Internet, (which was at 3 bars) checked the servers, (which were all running) tried a different Animal Crossing: New Leaf cartridge, all without any luck. I've looked into the problem on the Internet and many people have similar problems with just this one game, though I haven't found any solutions yet. Is anyone else having this same problem, and is there any possible ways of fixing this?
2015/06/10
[ "https://gaming.stackexchange.com/questions/223143", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/115123/" ]
I think you might have done too many system updates for the codes to work on your system. It is entirely possible that the latest system update prevents you from using powersaves in animal crossing new leaf. Try using a Nintendo 3ds that is older and hasn't been updated for a long time. If that doesn't work, I don't know what to tell you. Hopefully that works.
It happened to me, And It's a problem with the cord. I had to hold it in a really weird way because My game was heavier than my others (I used an old scale thingy) But, It could be your cartridge
20,927,207
I'm trying to make a basic JDBC connection to MySQL. I deployed application on openshift server (tomcat7, mysql) but I can't connect with my db (I use phpmyadmin to create db and tables). I'am using Spring 3.1 MVC, JSF and Primefaces. I deployed some time ago a simple java web application and I used a **class conection**: ``` String driver = "com.mysql.jdbc.Driver"; String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST"); String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT"); String url = "jdbc:mysql://"+host+":"+port+"/demo01"; String user = "adminujFVYBF"; String password = "EIyNRbHNBxN_"; ``` This time I wanted to use a **jdbc.properties file** with Spring MVC in order to manage the values ``` jdbc.driverClassName=com.mysql.jdbc.Driver jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT)}/libreriaapp jdbc.username=adminCnH8p6r jdbc.password=EhBHSvIqHFAz ``` So I tried unsuccessfully to figure out how can I use environmental variables in the jdbc url in order to get working my db . **This is my application Context** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <context:component-scan base-package="pe.egcc.eureka.app.layer.controller"/> </beans> ``` [**Project Repository**] <https://github.com/cachuan07/libreriaapp> [1](https://github.com/cachuan07/libreriaapp) If anyone can point me in the right direction that'd be great. Sorry for the huge post, it needed a bit of explaining to make it coherent. Hopefully it makes sense. Thanks.
2014/01/04
[ "https://Stackoverflow.com/questions/20927207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2283314/" ]
HI you can simply write a code like this.. ``` try{Class.forName("com.mysql.jdbc.Driver").newInstance(); username=asfksjfjs; password=sflkaskfjhsjk; url="jdbc:mysql://178.360.01:3306/demo01"; con = (Connection) DriverManager.getConnection(url,username,password);} ``` just copy those port no and host name from your phpmyadmin... It will work surly.
I don't think you can use environment variables in a jdbc.properties file, I don't think they will get parsed (as answered here [Regarding application.properties file and environment variable](https://stackoverflow.com/questions/2263929/regarding-application-properties-file-and-environment-variable)). You MIGHT be able to use the environment variables right in your xml file if that xml file gets parsed correctly by something that will substitute them (like it does for a standalone.xml or context.xml file)
20,927,207
I'm trying to make a basic JDBC connection to MySQL. I deployed application on openshift server (tomcat7, mysql) but I can't connect with my db (I use phpmyadmin to create db and tables). I'am using Spring 3.1 MVC, JSF and Primefaces. I deployed some time ago a simple java web application and I used a **class conection**: ``` String driver = "com.mysql.jdbc.Driver"; String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST"); String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT"); String url = "jdbc:mysql://"+host+":"+port+"/demo01"; String user = "adminujFVYBF"; String password = "EIyNRbHNBxN_"; ``` This time I wanted to use a **jdbc.properties file** with Spring MVC in order to manage the values ``` jdbc.driverClassName=com.mysql.jdbc.Driver jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT)}/libreriaapp jdbc.username=adminCnH8p6r jdbc.password=EhBHSvIqHFAz ``` So I tried unsuccessfully to figure out how can I use environmental variables in the jdbc url in order to get working my db . **This is my application Context** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> <context:component-scan base-package="pe.egcc.eureka.app.layer.controller"/> </beans> ``` [**Project Repository**] <https://github.com/cachuan07/libreriaapp> [1](https://github.com/cachuan07/libreriaapp) If anyone can point me in the right direction that'd be great. Sorry for the huge post, it needed a bit of explaining to make it coherent. Hopefully it makes sense. Thanks.
2014/01/04
[ "https://Stackoverflow.com/questions/20927207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2283314/" ]
HI you can simply write a code like this.. ``` try{Class.forName("com.mysql.jdbc.Driver").newInstance(); username=asfksjfjs; password=sflkaskfjhsjk; url="jdbc:mysql://178.360.01:3306/demo01"; con = (Connection) DriverManager.getConnection(url,username,password);} ``` just copy those port no and host name from your phpmyadmin... It will work surly.
Activate phpmyadmin, and open it you will find the ip in the header, take it and replace it in the OPENSHIFT\_MYSQL\_DB\_HOST variable, the port is the default mysql : 3306.
8,089,232
I am trying to save the selectedIndex of actionsheet into an object. But why does it always read 0? ``` -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { NSNumber *type, *count; if ([actionSheet.title isEqualToString:@"Select Taxi Type"]) { if (buttonIndex !=3) { type = [NSNumber numberWithInteger:buttonIndex]; UIActionSheet *taxiCountQuery = [[UIActionSheet alloc] initWithTitle:@"Select Taxi Count" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"1", @"2", @"3", nil]; taxiCountQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque; taxiCountQuery.tag = actionSheet.tag; [taxiCountQuery showFromTabBar:self.tabBarController.tabBar]; [taxiCountQuery release]; } } else if ([actionSheet.title isEqualToString:@"Select Taxi Count"]){ if (buttonIndex !=3) { NSLog(@"buttonIndex:%i", buttonIndex); count = [NSNumber numberWithInteger:buttonIndex]; NSLog(@"type:%f", type); // always read 0 NSLog(@"count:%f", count); // always read 0 } } } ``` EDIT - 2nd part ``` -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { NSNumber *type = [[NSNumber alloc] init]; if ([actionSheet.title isEqualToString:@"Select Taxi Type"]) { if (buttonIndex !=3) { type = [NSNumber numberWithInteger:buttonIndex]; UIActionSheet *taxiCountQuery = [[UIActionSheet alloc] initWithTitle:@"Select Taxi Count" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"1", @"2", @"3", nil]; taxiCountQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque; taxiCountQuery.tag = actionSheet.tag; [taxiCountQuery showFromTabBar:self.tabBarController.tabBar]; [taxiCountQuery release]; } } else if ([actionSheet.title isEqualToString:@"Select Taxi Count"]){ if (buttonIndex !=3) { NSNumber *count = [[NSNumber alloc] initWithInteger:buttonIndex+1]; NSLog(@"buttonIndex:%i", buttonIndex); count = [NSNumber numberWithInteger:buttonIndex +1]; NSLog(@"type:%i", [type intValue]); // always read 0 NSLog(@"count:%i", [count intValue]); // reads fine now [count release]; } } } ```
2011/11/11
[ "https://Stackoverflow.com/questions/8089232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/771355/" ]
NSNumber is an object that can hold basic types for storing in data structures like NSDictionary and NSArray. The %f in the NSLog is looking for a double. This code should be giving you a warning. If you do NSLog(@"%i",[type intValue]) you will get the right answer.
Please check out this code. ``` NSNumber *numberNs = [[NSNumber alloc] initWithInteger:buttonIndex]; ``` Hope this helps you.
49,078,971
``` If trigger = "Reconcile" Then If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) End If If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If Else: Call SenseCheck(location, location2, location7, checkmi) End If End If ``` I want my code to check if `Checkmi` is equal to one of the hardcoded codes(XX1000, XX1001) and to then call the appropriate VBA code. If however, there is no specific VBA module for that specific code, I want it to call the generic `SenseCheck`. Currently it executes `SenseChec`k if the initial condition `If InStr(XXlist, checkmi) > 0` is wrong, which is not what I want. And I am not entirely sure how to fix that.
2018/03/02
[ "https://Stackoverflow.com/questions/49078971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9361028/" ]
This might be a good spot for a SELECT...CASE Syntax ``` SELECT CASE checkmi CASE "XX1000" a = a + 1 Call XX1000Check(location, a, checkmi) CASE "XX1001" Call XX1001Check(location, checkmi) CASE ELSE SenseCheck(location, location2, location7, checkmi) END SELECT ```
You already terminated the `If` statement by `End If` below: ``` If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If '<~~ termination point ``` And you have an open `If` statement where you placed your `Else` statement. ``` If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) End If If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If '<~~ termination point as pointed above Else: Call SenseCheck(location, location2, location7, checkmi) End If '<~~ termination point ``` So the `Else` statement will be associated to the top most *non-terminated* `If` statement. And that is your very first `If` statement `If InStr(XXlist, checkmi) > 0 Then`. **Edit1:** To correct your code, include `Else` statement before terminating the entire `If` statement and also incorporate using `ElseIf` although if you have more conditions, using `Select Case` is desirable. ``` If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) ElseIf checkmi = "XX1001" Then '<~~ incorporate ElseIf statement Call XX1001Check(location, checkmi) Else '<~~ transfer the Else statement here Call SenseCheck(location, location2, location7, checkmi) End If End If ```
49,078,971
``` If trigger = "Reconcile" Then If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) End If If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If Else: Call SenseCheck(location, location2, location7, checkmi) End If End If ``` I want my code to check if `Checkmi` is equal to one of the hardcoded codes(XX1000, XX1001) and to then call the appropriate VBA code. If however, there is no specific VBA module for that specific code, I want it to call the generic `SenseCheck`. Currently it executes `SenseChec`k if the initial condition `If InStr(XXlist, checkmi) > 0` is wrong, which is not what I want. And I am not entirely sure how to fix that.
2018/03/02
[ "https://Stackoverflow.com/questions/49078971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9361028/" ]
This might be a good spot for a SELECT...CASE Syntax ``` SELECT CASE checkmi CASE "XX1000" a = a + 1 Call XX1000Check(location, a, checkmi) CASE "XX1001" Call XX1001Check(location, checkmi) CASE ELSE SenseCheck(location, location2, location7, checkmi) END SELECT ```
expanding on given answers, just to add that you may consider enhancing your code and improving its maintenance by adopting the same sub for both "XX1000" and "XX1001" `checkmi` values this by means of "optional" parameters that a Sub/Function can have with the only requirement they must be kept as the last ones in their *signature* for instance: ``` Sub XX100XCheck(checkmi As String, location As Long, Optional a As Variant) ``` would require the first two parameters to be passed and leaving the third one as optional. and by declaring this latter of `Variant` type you can check whether it has actually been passed or not: ``` Sub XX100XCheck(checkmi As String, location As Long, Optional a As Variant) If Not IsMissing(a) Then 'if "optional" 'a' parameter has actually been passed ' here place the code to process "optional" 'a' parameter End If '... rest of your code to handle "fixed" parameters End Sub ``` so that your question code would be: ``` Select Case checkmi Case "XX1000" a = a + 1 XX100XCheck checkmi, location, a ' call XX100Check sub passing all kind of parameters ("fixed" and "optional") Case "XX1001" XX100XCheck checkmi, location ' call the same sub as above, but now you're not passing it the "optional" a parameter Case Else SenseCheck(location, location2, location7, checkmi) End Select ``` where you can use (and maintain) one sub only (i.e. `XX100XCheck()`) instead of two (i.e. `XX1000Check()` and `XX1001Check()`) of course this is may not be taken as a *mandatory* coding pattern, since it may get at odds with another "good practice" one which calls for plain and simple routines as opposite to "all-in-one " ones so it's a matter of balance (as always) and my proposal went out of a guessing from your code that the two `XX...Check()` subs would have minimal variations between them
49,078,971
``` If trigger = "Reconcile" Then If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) End If If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If Else: Call SenseCheck(location, location2, location7, checkmi) End If End If ``` I want my code to check if `Checkmi` is equal to one of the hardcoded codes(XX1000, XX1001) and to then call the appropriate VBA code. If however, there is no specific VBA module for that specific code, I want it to call the generic `SenseCheck`. Currently it executes `SenseChec`k if the initial condition `If InStr(XXlist, checkmi) > 0` is wrong, which is not what I want. And I am not entirely sure how to fix that.
2018/03/02
[ "https://Stackoverflow.com/questions/49078971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9361028/" ]
You already terminated the `If` statement by `End If` below: ``` If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If '<~~ termination point ``` And you have an open `If` statement where you placed your `Else` statement. ``` If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) End If If checkmi = "XX1001" Then Call XX1001Check(location, checkmi) End If '<~~ termination point as pointed above Else: Call SenseCheck(location, location2, location7, checkmi) End If '<~~ termination point ``` So the `Else` statement will be associated to the top most *non-terminated* `If` statement. And that is your very first `If` statement `If InStr(XXlist, checkmi) > 0 Then`. **Edit1:** To correct your code, include `Else` statement before terminating the entire `If` statement and also incorporate using `ElseIf` although if you have more conditions, using `Select Case` is desirable. ``` If InStr(XXlist, checkmi) > 0 Then If checkmi = "XX1000" Then a = a + 1 Call XX1000Check(location, a, checkmi) ElseIf checkmi = "XX1001" Then '<~~ incorporate ElseIf statement Call XX1001Check(location, checkmi) Else '<~~ transfer the Else statement here Call SenseCheck(location, location2, location7, checkmi) End If End If ```
expanding on given answers, just to add that you may consider enhancing your code and improving its maintenance by adopting the same sub for both "XX1000" and "XX1001" `checkmi` values this by means of "optional" parameters that a Sub/Function can have with the only requirement they must be kept as the last ones in their *signature* for instance: ``` Sub XX100XCheck(checkmi As String, location As Long, Optional a As Variant) ``` would require the first two parameters to be passed and leaving the third one as optional. and by declaring this latter of `Variant` type you can check whether it has actually been passed or not: ``` Sub XX100XCheck(checkmi As String, location As Long, Optional a As Variant) If Not IsMissing(a) Then 'if "optional" 'a' parameter has actually been passed ' here place the code to process "optional" 'a' parameter End If '... rest of your code to handle "fixed" parameters End Sub ``` so that your question code would be: ``` Select Case checkmi Case "XX1000" a = a + 1 XX100XCheck checkmi, location, a ' call XX100Check sub passing all kind of parameters ("fixed" and "optional") Case "XX1001" XX100XCheck checkmi, location ' call the same sub as above, but now you're not passing it the "optional" a parameter Case Else SenseCheck(location, location2, location7, checkmi) End Select ``` where you can use (and maintain) one sub only (i.e. `XX100XCheck()`) instead of two (i.e. `XX1000Check()` and `XX1001Check()`) of course this is may not be taken as a *mandatory* coding pattern, since it may get at odds with another "good practice" one which calls for plain and simple routines as opposite to "all-in-one " ones so it's a matter of balance (as always) and my proposal went out of a guessing from your code that the two `XX...Check()` subs would have minimal variations between them
36,711,939
I have a `Recyclerview` that holds `ratingbar` in list\_items If I user **rtBar.setOnRatingBarChangeListener** , then I get not results , nothing happens in rating bar , not even clickable If I use **rtBar.setOnTouchListener** , it works , but my code does't works when clicked on 4th start ``` public EmployeeViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); rtBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { utilMethods.showToast(mContext, "" + rating); } }); } ```
2016/04/19
[ "https://Stackoverflow.com/questions/36711939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4432176/" ]
If your RatingBar is not clickable then check in your xml file where RatingBar has attribute `android:isIndicator="false"`. > > If **isIndicator** is **true** then you couldn't able to rate > > >
use interface like that ``` public interface OnRecordEventListener { void onRatingBarChange(Record item,float value); } ``` you create ViewHolder pass listener into constructor like this. ``` public ViewHolder(View itemView, OnRecordEventListener listener) { super(itemView); textViewTitle = (TextView) itemView.findViewById(R.id.text_view_title); ratingBar = (RatingBar) itemView.findViewById(R.id.rating_bar_rating); bar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (fromUser) { listener.onRatingBarChange(mRecords.get(getLayoutPosition()), rating); } } }); } ``` And update in onCreateViewHolder ``` @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_item, viewGroup, false); return new ViewHolder(v,mClickListener); } ``` you can use interface for other events also, you just need to add method into interface,implement it and bind in ViewHolder constructor. UPDATE Consider you are using *RecyclerView* in Activity ``` public class RecyclerActivity extends Activity implements OnRecordEventListener { // all institutionalization, callbacks, hook methods @Override public void onCreate() { // Initialization ..... mRecyclerView.setLayoutManager(...); // Passing this because this class implements interface mRecyclerView.setAdapter(new RecyclerViewAdapter(mRecord,this)); } @Override void onRatingBarChange(Record item,float value) { // do Something } } ```
47,313,619
I have recently started working with VBA and I have to filter a column with string 'NEWV' and to count number of rows that end after that filtering,Currently am using the below code but that doesnt seem to work, ``` ByrNbr = Watchlist.Range("B" & i).Value LookFor = ByrNbr Set Age_rng = Total.Sheets("Counts").Range("A:S") If Total.Sheets("Counts").Range("G:G").Value = "NEWV" Then .Range("L27").Value = Application.WorksheetFunction.CountIf(Age_rng, Range("A:A")) End If ```
2017/11/15
[ "https://Stackoverflow.com/questions/47313619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490346/" ]
Not sure what workbook and worksheet these ranges are on, but you could use something like this, just have to clarify where each range resides. ``` ByrNbr = Watchlist.Range("B" & i).Value Worksheets(???).Range("L27").Value =WorksheetFunction.CountIfs(Watchlist.Range("B:B" ), ByrNbr, Watchlist.Range("G:G"), "NEWV") ```
Try testing this line without the `If` statement ``` Range("L27").Value = Application.WorksheetFunction.COUNTIF(Age_rng,"NEWV") ```
47,313,619
I have recently started working with VBA and I have to filter a column with string 'NEWV' and to count number of rows that end after that filtering,Currently am using the below code but that doesnt seem to work, ``` ByrNbr = Watchlist.Range("B" & i).Value LookFor = ByrNbr Set Age_rng = Total.Sheets("Counts").Range("A:S") If Total.Sheets("Counts").Range("G:G").Value = "NEWV" Then .Range("L27").Value = Application.WorksheetFunction.CountIf(Age_rng, Range("A:A")) End If ```
2017/11/15
[ "https://Stackoverflow.com/questions/47313619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490346/" ]
Not sure what workbook and worksheet these ranges are on, but you could use something like this, just have to clarify where each range resides. ``` ByrNbr = Watchlist.Range("B" & i).Value Worksheets(???).Range("L27").Value =WorksheetFunction.CountIfs(Watchlist.Range("B:B" ), ByrNbr, Watchlist.Range("G:G"), "NEWV") ```
[![enter image description here](https://i.stack.imgur.com/p6Psk.png)](https://i.stack.imgur.com/p6Psk.png) ``` Sub formulatest() MsgBox Application.WorksheetFunction.CountIfs(Sheet1.Range("B13:B16"), Sheet1.Range("C12").Value, Sheet1.Range("G13:G16"), Sheet1.Range("D12").Value) '~~Returns 2 End Sub ```
213,910
I have posts in two languages, managed by WPML. In one post, I share multiple links which are updated in a regular basis. Updating the same links for both languages is not an option (for now I only added this post in one language). Which is the best way to define links text and URL only once, and reuse them in both languages? I could code a shortcode and manage the links by code, but I would like to know if there is any plugin or other approach to accomplish this (I already did my research with no luck).
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59235/" ]
Your arguments for both [`wp_get_attachment_image_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/) and [`wp_get_attachment_image()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image) are in the wrong order - check the linked documentation for details. Additionally, `wp_get_attachment_image_url()` returns a URL - not an actual image element. > > Removing the `width` and `height` attributes from `<img>` elements is > inadvisable: if the layout of the page is in any way influenced by the > size of the image, the layout will "glitch" as soon as the CSS which > specifies the image's dimensions, or the image itself loads. > > > Unfortunately, the `wp_get_attachment_image()` function is currently (as of WordPress 4.4.1) hard-coded to output the `width` and `height` `<img>` attributes (see [ticket #14110](https://core.trac.wordpress.org/ticket/14110)), so you'll need to build the image markup yourself. This can be done by taking cues from [`wp_get_attachment_image()`'s source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800): ``` <?php $attachment = get_post( $entry['slide_image_id'] ); if( $attachment ) { $img_size_class = 'full'; $img_atts = array( 'src' => wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ), 'class' => 'attachment-' . $img_size_class . ' size-' . $img_size_class, 'alt' => trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) ) ); //If an 'alt' attribute was not specified, try to create one from attachment post data if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_excerpt )); if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_title )); $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class ); echo( '<img ' ); foreach( $img_atts as $name => $value ) { echo( $name . '="' . $value . '" '; } echo( '/>' ); } ?> ```
I simply used CSS for this one. It doesn't work in all scenario's, but often enough it will. Let's take a 300px x 300px image: ``` max-height: 300px; max-width: 300px; width: auto; ``` This constrains the dimensions of the image without losing its width to height ratio. Otherwise you can also use REGEX: ``` $html = preg_replace(array('/width="[^"]*"/', '/height="[^"]*"/'), '', $html); ``` These were some alternatives. Good luck.
213,910
I have posts in two languages, managed by WPML. In one post, I share multiple links which are updated in a regular basis. Updating the same links for both languages is not an option (for now I only added this post in one language). Which is the best way to define links text and URL only once, and reuse them in both languages? I could code a shortcode and manage the links by code, but I would like to know if there is any plugin or other approach to accomplish this (I already did my research with no luck).
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59235/" ]
Your arguments for both [`wp_get_attachment_image_url()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image_url/) and [`wp_get_attachment_image()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_image) are in the wrong order - check the linked documentation for details. Additionally, `wp_get_attachment_image_url()` returns a URL - not an actual image element. > > Removing the `width` and `height` attributes from `<img>` elements is > inadvisable: if the layout of the page is in any way influenced by the > size of the image, the layout will "glitch" as soon as the CSS which > specifies the image's dimensions, or the image itself loads. > > > Unfortunately, the `wp_get_attachment_image()` function is currently (as of WordPress 4.4.1) hard-coded to output the `width` and `height` `<img>` attributes (see [ticket #14110](https://core.trac.wordpress.org/ticket/14110)), so you'll need to build the image markup yourself. This can be done by taking cues from [`wp_get_attachment_image()`'s source](https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/media.php#L800): ``` <?php $attachment = get_post( $entry['slide_image_id'] ); if( $attachment ) { $img_size_class = 'full'; $img_atts = array( 'src' => wp_get_attachment_image_url( $entry['slide_image_id'], $img_size_class, false ), 'class' => 'attachment-' . $img_size_class . ' size-' . $img_size_class, 'alt' => trim(strip_tags( get_post_meta( $entry['slide_image_id'], '_wp_attachment_image_alt', true) ) ) ); //If an 'alt' attribute was not specified, try to create one from attachment post data if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_excerpt )); if( empty( $img_atts[ 'alt' ] ) ) $img_atts[ 'alt' ] = trim(strip_tags( $attachment->post_title )); $img_atts = apply_filters( 'wp_get_attachment_image_attributes', $img_atts, $attachment, $img_size_class ); echo( '<img ' ); foreach( $img_atts as $name => $value ) { echo( $name . '="' . $value . '" '; } echo( '/>' ); } ?> ```
**Regex approach** After retrieving the raw image output that will include the width and height attributes, simply remove them with a regex replace of an empty string: ``` <?php $raw_image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full'); $final_image = preg_replace('/(height|width)="\d*"\s/', "", $raw_image); echo $final_image; ?> ``` In the future, it would be great if WordPress supplied a filter to get suppress these attributes.
213,910
I have posts in two languages, managed by WPML. In one post, I share multiple links which are updated in a regular basis. Updating the same links for both languages is not an option (for now I only added this post in one language). Which is the best way to define links text and URL only once, and reuse them in both languages? I could code a shortcode and manage the links by code, but I would like to know if there is any plugin or other approach to accomplish this (I already did my research with no luck).
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59235/" ]
Workaround ---------- I did some core digging/testing and found a workaround through the `wp_constrain_dimensions` filter: ``` // Add filter to empty the height/width array add_filter( 'wp_constrain_dimensions', '__return_empty_array' ); // Display image html echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true ); // Remove filter again remove_filter( 'wp_constrain_dimensions', '__return_empty_array' ); ``` This seems to allow us to remove the *height* and *width* attributes from the generated image html of `wp_get_attachment_image()`, without getting out the reg-ex canons. We could also use the `wp_get_attachment_image_src` filter in a similar way to remove the *width*/*height* but keep the *url*. Notes ----- This workaround will remove the `srcset` and `sizes` attributes as well. But it's also possible to set the *srcset* and *sizes* attributes through the fourth `$attr` input argument. As mentioned by @bosco, you've switched the *icon* and *size* input arguments in: ``` echo wp_get_attachment_image( $entry['slide_image_id'], true, 'full' ); ``` Use this instead: ``` echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true ); ```
I simply used CSS for this one. It doesn't work in all scenario's, but often enough it will. Let's take a 300px x 300px image: ``` max-height: 300px; max-width: 300px; width: auto; ``` This constrains the dimensions of the image without losing its width to height ratio. Otherwise you can also use REGEX: ``` $html = preg_replace(array('/width="[^"]*"/', '/height="[^"]*"/'), '', $html); ``` These were some alternatives. Good luck.
213,910
I have posts in two languages, managed by WPML. In one post, I share multiple links which are updated in a regular basis. Updating the same links for both languages is not an option (for now I only added this post in one language). Which is the best way to define links text and URL only once, and reuse them in both languages? I could code a shortcode and manage the links by code, but I would like to know if there is any plugin or other approach to accomplish this (I already did my research with no luck).
2016/01/07
[ "https://wordpress.stackexchange.com/questions/213910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59235/" ]
Workaround ---------- I did some core digging/testing and found a workaround through the `wp_constrain_dimensions` filter: ``` // Add filter to empty the height/width array add_filter( 'wp_constrain_dimensions', '__return_empty_array' ); // Display image html echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true ); // Remove filter again remove_filter( 'wp_constrain_dimensions', '__return_empty_array' ); ``` This seems to allow us to remove the *height* and *width* attributes from the generated image html of `wp_get_attachment_image()`, without getting out the reg-ex canons. We could also use the `wp_get_attachment_image_src` filter in a similar way to remove the *width*/*height* but keep the *url*. Notes ----- This workaround will remove the `srcset` and `sizes` attributes as well. But it's also possible to set the *srcset* and *sizes* attributes through the fourth `$attr` input argument. As mentioned by @bosco, you've switched the *icon* and *size* input arguments in: ``` echo wp_get_attachment_image( $entry['slide_image_id'], true, 'full' ); ``` Use this instead: ``` echo wp_get_attachment_image( $entry['slide_image_id'], 'full', true ); ```
**Regex approach** After retrieving the raw image output that will include the width and height attributes, simply remove them with a regex replace of an empty string: ``` <?php $raw_image = wp_get_attachment_image( $entry['slide_image_id'], true, 'full'); $final_image = preg_replace('/(height|width)="\d*"\s/', "", $raw_image); echo $final_image; ?> ``` In the future, it would be great if WordPress supplied a filter to get suppress these attributes.
14,714,892
I have a div that needs to be hidden by default. It then can be toggled by a button: ``` <script type="text/javascript"> function toggle() { text = document.getElementById('add_view'); var isHidden = text.style.display == 'none'; text.style.display = isHidden ? 'block' : 'none'; } $(document).ready ( function () { toggle(); $("#add_view, #btnToggle").click(function (e) { e.stopPropagation(); }); $(document).click(function () { toggle(); }); } ); </script> ``` It is working fine. The only problem is, when I refresh the page, I momentarily see the div before it is hidden. What could I do to prevent that? Thanks
2013/02/05
[ "https://Stackoverflow.com/questions/14714892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2043533/" ]
You probably need to hide your element by default, and then use the button to toggle visibility. Try this: ``` <div id="add_view" style="display:none">....</div> ```
Make the element hidden in your html to begin with. ``` <div id="add_view" style="display: none;"></div> ```
14,714,892
I have a div that needs to be hidden by default. It then can be toggled by a button: ``` <script type="text/javascript"> function toggle() { text = document.getElementById('add_view'); var isHidden = text.style.display == 'none'; text.style.display = isHidden ? 'block' : 'none'; } $(document).ready ( function () { toggle(); $("#add_view, #btnToggle").click(function (e) { e.stopPropagation(); }); $(document).click(function () { toggle(); }); } ); </script> ``` It is working fine. The only problem is, when I refresh the page, I momentarily see the div before it is hidden. What could I do to prevent that? Thanks
2013/02/05
[ "https://Stackoverflow.com/questions/14714892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2043533/" ]
You probably need to hide your element by default, and then use the button to toggle visibility. Try this: ``` <div id="add_view" style="display:none">....</div> ```
Initially, you have to hide it by setting `style="display:none;"` of the div. Once when u want to toggle it, you have to use it as ``` document.getElementById(Id).style.display=""; ``` in javascript.
14,714,892
I have a div that needs to be hidden by default. It then can be toggled by a button: ``` <script type="text/javascript"> function toggle() { text = document.getElementById('add_view'); var isHidden = text.style.display == 'none'; text.style.display = isHidden ? 'block' : 'none'; } $(document).ready ( function () { toggle(); $("#add_view, #btnToggle").click(function (e) { e.stopPropagation(); }); $(document).click(function () { toggle(); }); } ); </script> ``` It is working fine. The only problem is, when I refresh the page, I momentarily see the div before it is hidden. What could I do to prevent that? Thanks
2013/02/05
[ "https://Stackoverflow.com/questions/14714892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2043533/" ]
Make the element hidden in your html to begin with. ``` <div id="add_view" style="display: none;"></div> ```
Initially, you have to hide it by setting `style="display:none;"` of the div. Once when u want to toggle it, you have to use it as ``` document.getElementById(Id).style.display=""; ``` in javascript.
50,529,319
I'm trying to send a POST request to [Ghostbin](https://ghostbin.com) via Node.JS and its `request` NPM module. Here's what my code looks like: Attempt 1: ``` reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post" }, function (err, res, body) { console.log(res) }) ``` Attempt 2: ``` reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": 9 } }, function (err, res, body) { console.log(res) }) ``` Attempt 3: ``` reqest.post("https://ghostbin.com/paste/new", {form: {text: "test post"}}, function (err, res, body) { console.log(res) }) ``` All of these attempts ended up logging: ``` <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>406 Not Acceptable</title>\n</head><body>\n<h1>Not Acceptable</h1>\n<p>An appropriate representation of the requested resource /paste/new could not be found on this server.</p>\n<hr>\n<address>Apache/2.4.18 (Ubuntu) Server at ghostbin.com Port 443</address>\n</body></html> ``` Is there something I'm missing regarding the `request` library, or with [the documentation of the Ghostbin API](https://ghostbin.com/paste/p3qcy)?
2018/05/25
[ "https://Stackoverflow.com/questions/50529319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8961491/" ]
You can use `tf.cond`: ``` idx0 = tf.shape(row_index)[0] loss_f_G_filtered = tf.cond(idx0 == 0, lambda: tf.constant(0, tf.float32), lambda: ...another function...) ```
``` loss_f_G = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y1_filterred, labels=y__filtered), name = "filtered_reg") idx0 = tf.shape(row_index)[0] loss_f_G_filtered = tf.cond(tf.cast(idx0 == 0, tf.bool), lambda: tf.constant(0, tf.float32), lambda:loss_f_G) ``` The problem is that idx0 == 0 is never true even when row\_index = []. [![enter image description here](https://i.stack.imgur.com/iK8Ef.png)](https://i.stack.imgur.com/iK8Ef.png)
50,529,319
I'm trying to send a POST request to [Ghostbin](https://ghostbin.com) via Node.JS and its `request` NPM module. Here's what my code looks like: Attempt 1: ``` reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post" }, function (err, res, body) { console.log(res) }) ``` Attempt 2: ``` reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": 9 } }, function (err, res, body) { console.log(res) }) ``` Attempt 3: ``` reqest.post("https://ghostbin.com/paste/new", {form: {text: "test post"}}, function (err, res, body) { console.log(res) }) ``` All of these attempts ended up logging: ``` <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>406 Not Acceptable</title>\n</head><body>\n<h1>Not Acceptable</h1>\n<p>An appropriate representation of the requested resource /paste/new could not be found on this server.</p>\n<hr>\n<address>Apache/2.4.18 (Ubuntu) Server at ghostbin.com Port 443</address>\n</body></html> ``` Is there something I'm missing regarding the `request` library, or with [the documentation of the Ghostbin API](https://ghostbin.com/paste/p3qcy)?
2018/05/25
[ "https://Stackoverflow.com/questions/50529319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8961491/" ]
``` is_empty = tf.equal(tf.size(row_index), 0) ```
You can use `tf.cond`: ``` idx0 = tf.shape(row_index)[0] loss_f_G_filtered = tf.cond(idx0 == 0, lambda: tf.constant(0, tf.float32), lambda: ...another function...) ```
50,529,319
I'm trying to send a POST request to [Ghostbin](https://ghostbin.com) via Node.JS and its `request` NPM module. Here's what my code looks like: Attempt 1: ``` reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post" }, function (err, res, body) { console.log(res) }) ``` Attempt 2: ``` reqest.post({ url: "https://ghostbin.com/paste/new", text: "test post", headers: { "Content-Type": "application/x-www-form-urlencoded", "Content-Length": 9 } }, function (err, res, body) { console.log(res) }) ``` Attempt 3: ``` reqest.post("https://ghostbin.com/paste/new", {form: {text: "test post"}}, function (err, res, body) { console.log(res) }) ``` All of these attempts ended up logging: ``` <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>406 Not Acceptable</title>\n</head><body>\n<h1>Not Acceptable</h1>\n<p>An appropriate representation of the requested resource /paste/new could not be found on this server.</p>\n<hr>\n<address>Apache/2.4.18 (Ubuntu) Server at ghostbin.com Port 443</address>\n</body></html> ``` Is there something I'm missing regarding the `request` library, or with [the documentation of the Ghostbin API](https://ghostbin.com/paste/p3qcy)?
2018/05/25
[ "https://Stackoverflow.com/questions/50529319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8961491/" ]
``` is_empty = tf.equal(tf.size(row_index), 0) ```
``` loss_f_G = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y1_filterred, labels=y__filtered), name = "filtered_reg") idx0 = tf.shape(row_index)[0] loss_f_G_filtered = tf.cond(tf.cast(idx0 == 0, tf.bool), lambda: tf.constant(0, tf.float32), lambda:loss_f_G) ``` The problem is that idx0 == 0 is never true even when row\_index = []. [![enter image description here](https://i.stack.imgur.com/iK8Ef.png)](https://i.stack.imgur.com/iK8Ef.png)
41,951,231
I have to send mail using Amazon AWS with PHP, I am able to send simple mail but got following Error, I used many codes get from Google but still I got the same error every time. > > Fatal error: Cannot redeclare Aws\constantly() (previously declared > in /path/vendor/aws/aws-sdk-php/src/functions.php:20) in > phar:///opt/lampp/htdocs/path/amazon/aws.phar/Aws/functions.php on > line 22 > > > Code I used:- ``` require_once '/mypath/vendor/autoload.php'; include_once("SESUtils.php"); $subject_str = "Some Subject"; $body_str = "<strong>Some email body</strong>"; $attachment_str = file_get_contents("mypdf_file.pdf"); //send the email $params = array("to" => "to@xyz.com", "subject" => "Some subject", "message" => "<strong>Some email body</strong>", "from" => "from@xyz.com", "replyTo" => "reply_to@gmail.com", "files" => array( "1" => array( "name" => "filename1", "filepath" => "/path/to/mypdf_file.pdf", "mime" => "application/pdf" ), ) ); $res = SESUtils::sendMail($params); ``` aws version:- 3.21.6 AND SESUtils.php ``` require_once('aws.phar'); use Aws\Ses\SesClient; class SESUtils { const version = "1.0"; const AWS_KEY = "AWS_KEY"; const AWS_SEC = "AWS_SEC"; const AWS_REGION = "us-east-1"; const MAX_ATTACHMENT_NAME_LEN = 60; public static function sendMail($params) { $to = self::getParam($params, 'to', true); $subject = self::getParam($params, 'subject', true); $body = self::getParam($params, 'message', true); $from = self::getParam($params, 'from', true); $replyTo = self::getParam($params, 'replyTo'); $files = self::getParam($params, 'files'); $res = new ResultHelper(); // get the client ready $client = SesClient::factory(array( 'key' => self::AWS_KEY, 'secret' => self::AWS_SEC, 'region' => self::AWS_REGION )); // build the message if (is_array($to)) { $to_str = rtrim(implode(',', $to), ','); } else { $to_str = $to; } $msg = "To: $to_str\n"; $msg .= "From: $from\n"; if ($replyTo) { $msg .= "Reply-To: $replyTo\n"; } // in case you have funny characters in the subject $subject = mb_encode_mimeheader($subject, 'UTF-8'); $msg .= "Subject: $subject\n"; $msg .= "MIME-Version: 1.0\n"; $msg .= "Content-Type: multipart/mixed;\n"; $boundary = uniqid("_Part_".time(), true); //random unique string $boundary2 = uniqid("_Part2_".time(), true); //random unique string $msg .= " boundary=\"$boundary\"\n"; $msg .= "\n"; $msg .= "--$boundary\n"; $msg .= "Content-Type: multipart/alternative;\n"; $msg .= " boundary=\"$boundary2\"\n"; $msg .= "\n"; $msg .= "--$boundary2\n"; $msg .= "Content-Type: text/plain; charset=utf-8\n"; $msg .= "Content-Transfer-Encoding: 7bit\n"; $msg .= "\n"; $msg .= strip_tags($body); //remove any HTML tags $msg .= "\n"; // now, the html text $msg .= "--$boundary2\n"; $msg .= "Content-Type: text/html; charset=utf-8\n"; $msg .= "Content-Transfer-Encoding: 7bit\n"; $msg .= "\n"; $msg .= $body; $msg .= "\n"; $msg .= "--$boundary2--\n"; // add attachments if (is_array($files)) { $count = count($files); foreach ($files as $file) { $msg .= "\n"; $msg .= "--$boundary\n"; $msg .= "Content-Transfer-Encoding: base64\n"; $clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN); $msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n"; $msg .= "Content-Disposition: attachment; filename=$clean_filename;\n"; $msg .= "\n"; $msg .= base64_encode(file_get_contents($file['filepath'])); $msg .= "\n--$boundary"; } // close email $msg .= "--\n"; } // now send the email out try { $ses_result = $client->sendRawEmail( array( 'RawMessage' => array( 'Data' => base64_encode($msg) ) ), array( 'Source' => $from, 'Destinations' => $to_str ) ); if ($ses_result) { $res->message_id = $ses_result->get('MessageId'); } else { $res->success = false; $res->result_text = "Amazon SES did not return a MessageId"; } } catch (Exception $e) { $res->success = false; $res->result_text = $e->getMessage(). " - To: $to_str, Sender: $from, Subject: $subject"; } return $res; } private static function getParam($params, $param, $required = false) { $value = isset($params[$param]) ? $params[$param] : null; if ($required && empty($value)) { throw new Exception('"'.$param.'" parameter is required.'); } else { return $value; } } /** Clean filename function - to be mail friendly **/ public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') { if( !empty($replace) ) { $str = str_replace((array)$replace, ' ', $str); } $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str); $clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean); $clean = preg_replace("/[\/| -]+/", '-', $clean); if ($limit > 0) { //don't truncate file extension $arr = explode(".", $clean); $size = count($arr); $base = ""; $ext = ""; if ($size > 0) { for ($i = 0; $i < $size; $i++) { if ($i < $size - 1) { //if it's not the last item, add to $bn $base .= $arr[$i]; //if next one isn't last, add a dot if ($i < $size - 2) $base .= "."; } else { if ($i > 0) $ext = "."; $ext .= $arr[$i]; } } } $bn_size = mb_strlen($base); $ex_size = mb_strlen($ext); $bn_new = mb_substr($base, 0, $limit - $ex_size); // doing again in case extension is long $clean = mb_substr($bn_new.$ext, 0, $limit); } return $clean; } } class ResultHelper { public $success = true; public $result_text = ""; public $message_id = ""; } ```
2017/01/31
[ "https://Stackoverflow.com/questions/41951231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7348556/" ]
I had this error about redeclaring `constantly()` and the problem was resolved in our code by simply changing: ``` include('/PATH/TO/aws-sdk-3/aws-autoloader.php'); ``` to ``` include_once('/PATH/TO/aws-sdk-3/aws-autoloader.php'); ``` Maybe that will help you or the next person to Google this error message!
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example: ``` use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; //Load composer's autoloader require 'vendor/autoload.php'; ```
39,427,339
I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right? ```css body { margin: 0; font-family: Arial; font-size: 1em; } .navbar-ul, a { margin: 0; color: white; overflow: hidden; } li, a { text-decoration: none; display: inline-block; padding: 10px; background: black; } li a :hover { background-color: blue; } li { list-style-type: none; float: left; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dark Website Template by Jordan Baron</title> <link rel="stylesheet" href="styles-main.css"> </head> <body> <div class="navbar"> <ul class="navbar-ul"> <li><a href="#">HOME</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> </ul> </div> </body> </html> ``` Please help!
2016/09/10
[ "https://Stackoverflow.com/questions/39427339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $ cat ip.txt A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 0 0 . . 0 . ./. . . . $ perl -ne '(@c)=/\.\/\.|\./g; print if $#c < 1' ip.txt A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` * `(@c)=/\.\/\.|\./g` array of `./.` or `.` matches from current line * `$#c` indicates index of last element, i.e (size of array - 1) * So, to ignore lines containing 3 elements like `./.` or `.` use `$#c < 2`
Perhaps this is alright. ``` awk '$0 !~/\. \./' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ```
39,427,339
I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right? ```css body { margin: 0; font-family: Arial; font-size: 1em; } .navbar-ul, a { margin: 0; color: white; overflow: hidden; } li, a { text-decoration: none; display: inline-block; padding: 10px; background: black; } li a :hover { background-color: blue; } li { list-style-type: none; float: left; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dark Website Template by Jordan Baron</title> <link rel="stylesheet" href="styles-main.css"> </head> <body> <div class="navbar"> <ul class="navbar-ul"> <li><a href="#">HOME</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> </ul> </div> </body> </html> ``` Please help!
2016/09/10
[ "https://Stackoverflow.com/questions/39427339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $ awk '{delete a; for(i=1;i<=NF;i++) a[$i]++; if(a["."]>=2) next} 1' foo A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` It iterates all fields (`for`), counts field values and `if` 2 or more `.` in a record, restrains from printing (`next`). If you want to count the periods only from field 3 onward, change the start value of `i` in the `for`: `for(i=3; ...)`.
``` $ cat ip.txt A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 0 0 . . 0 . ./. . . . $ perl -ne '(@c)=/\.\/\.|\./g; print if $#c < 1' ip.txt A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` * `(@c)=/\.\/\.|\./g` array of `./.` or `.` matches from current line * `$#c` indicates index of last element, i.e (size of array - 1) * So, to ignore lines containing 3 elements like `./.` or `.` use `$#c < 2`
39,427,339
I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right? ```css body { margin: 0; font-family: Arial; font-size: 1em; } .navbar-ul, a { margin: 0; color: white; overflow: hidden; } li, a { text-decoration: none; display: inline-block; padding: 10px; background: black; } li a :hover { background-color: blue; } li { list-style-type: none; float: left; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dark Website Template by Jordan Baron</title> <link rel="stylesheet" href="styles-main.css"> </head> <body> <div class="navbar"> <ul class="navbar-ul"> <li><a href="#">HOME</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> </ul> </div> </body> </html> ``` Please help!
2016/09/10
[ "https://Stackoverflow.com/questions/39427339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
With awk: ``` $ awk '{c=0;for(i=1;i<NF;i++) c += ($i == ".")}c<2' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` Basically it iterates each column and add one to the counter if the column equals a period (`.`). The `c<2` part will only print the line if there is less than two columns with periods. With sed one can use: ``` $ sed -r 'h;s/[^. ]+//g;s/\.\. *//g;/\. \./d;x' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` `-r` enables extended regular expressions (`-E` on \*BSD). Basically a copy of the pattern space is stored in the `h`old buffer, then all but spaces and periods is removed. Now if the pattern space contains two separate periods it can be deleted if not the pattern space can be e`x`changed with the hold buffer.
``` $ cat ip.txt A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 0 0 . . 0 . ./. . . . $ perl -ne '(@c)=/\.\/\.|\./g; print if $#c < 1' ip.txt A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` * `(@c)=/\.\/\.|\./g` array of `./.` or `.` matches from current line * `$#c` indicates index of last element, i.e (size of array - 1) * So, to ignore lines containing 3 elements like `./.` or `.` use `$#c < 2`
39,427,339
I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right? ```css body { margin: 0; font-family: Arial; font-size: 1em; } .navbar-ul, a { margin: 0; color: white; overflow: hidden; } li, a { text-decoration: none; display: inline-block; padding: 10px; background: black; } li a :hover { background-color: blue; } li { list-style-type: none; float: left; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dark Website Template by Jordan Baron</title> <link rel="stylesheet" href="styles-main.css"> </head> <body> <div class="navbar"> <ul class="navbar-ul"> <li><a href="#">HOME</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> </ul> </div> </body> </html> ``` Please help!
2016/09/10
[ "https://Stackoverflow.com/questions/39427339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Similar to @spasic's answer, but easier (for me) to read! ``` perl -ane 'print if (grep { /^\.$/} @F) < 2' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` The `-a` separates the space-separated fields into an array called `@F` for me. I then grep in the array `@F` looking for elements that consist of just a period - i.e. those that start with a period and end immediately after the period. That counts the lone periods in each line and I print the line if that number is less than 2.
Perhaps this is alright. ``` awk '$0 !~/\. \./' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ```
39,427,339
I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right? ```css body { margin: 0; font-family: Arial; font-size: 1em; } .navbar-ul, a { margin: 0; color: white; overflow: hidden; } li, a { text-decoration: none; display: inline-block; padding: 10px; background: black; } li a :hover { background-color: blue; } li { list-style-type: none; float: left; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dark Website Template by Jordan Baron</title> <link rel="stylesheet" href="styles-main.css"> </head> <body> <div class="navbar"> <ul class="navbar-ul"> <li><a href="#">HOME</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> </ul> </div> </body> </html> ``` Please help!
2016/09/10
[ "https://Stackoverflow.com/questions/39427339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $ awk '{delete a; for(i=1;i<=NF;i++) a[$i]++; if(a["."]>=2) next} 1' foo A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` It iterates all fields (`for`), counts field values and `if` 2 or more `.` in a record, restrains from printing (`next`). If you want to count the periods only from field 3 onward, change the start value of `i` in the `for`: `for(i=3; ...)`.
Similar to @spasic's answer, but easier (for me) to read! ``` perl -ane 'print if (grep { /^\.$/} @F) < 2' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` The `-a` separates the space-separated fields into an array called `@F` for me. I then grep in the array `@F` looking for elements that consist of just a period - i.e. those that start with a period and end immediately after the period. That counts the lone periods in each line and I print the line if that number is less than 2.
39,427,339
I am trying to use CSS so when you hover on something it changes background colors. The code I am using does not work though. I can't seem to find out why though. It should work, right? ```css body { margin: 0; font-family: Arial; font-size: 1em; } .navbar-ul, a { margin: 0; color: white; overflow: hidden; } li, a { text-decoration: none; display: inline-block; padding: 10px; background: black; } li a :hover { background-color: blue; } li { list-style-type: none; float: left; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dark Website Template by Jordan Baron</title> <link rel="stylesheet" href="styles-main.css"> </head> <body> <div class="navbar"> <ul class="navbar-ul"> <li><a href="#">HOME</a></li> <li><a href="#">CONTACT</a></li> <li><a href="#">ABOUT</a></li> </ul> </div> </body> </html> ``` Please help!
2016/09/10
[ "https://Stackoverflow.com/questions/39427339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
With awk: ``` $ awk '{c=0;for(i=1;i<NF;i++) c += ($i == ".")}c<2' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` Basically it iterates each column and add one to the counter if the column equals a period (`.`). The `c<2` part will only print the line if there is less than two columns with periods. With sed one can use: ``` $ sed -r 'h;s/[^. ]+//g;s/\.\. *//g;/\. \./d;x' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` `-r` enables extended regular expressions (`-E` on \*BSD). Basically a copy of the pattern space is stored in the `h`old buffer, then all but spaces and periods is removed. Now if the pattern space contains two separate periods it can be deleted if not the pattern space can be e`x`changed with the hold buffer.
Similar to @spasic's answer, but easier (for me) to read! ``` perl -ane 'print if (grep { /^\.$/} @F) < 2' file A B C D E 0 1 . 0 0 1 ./. 0 1 1 1 1 0 0 0 ``` The `-a` separates the space-separated fields into an array called `@F` for me. I then grep in the array `@F` looking for elements that consist of just a period - i.e. those that start with a period and end immediately after the period. That counts the lone periods in each line and I print the line if that number is less than 2.