Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message
I.e. this causes an issue with Process.Start() not finding your exe:
PATH="C:\my program\bin";c:\windows\system32
Maybe it helps someone.
Adding to what @KyleMit said, consider using:
col-md-*
classes for the larger outer columnscol-xs-*
classes for the smaller inner columnsThis will be useful when you view the page on different screen sizes.
On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible
We can manage it by hiding the icon as i did:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner android:id="@+id/fragment_filter_sp_users"
android:layout_width="match_parent"
android:background="@color/colorTransparent"
android:layout_height="wrap_content"/>
<ImageView
android:layout_gravity="end|bottom"
android:contentDescription="@null"
android:layout_marginBottom="@dimen/_5sdp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_arrow_bottom"
/>
</FrameLayout>
Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");
Full option searchable select box
This also supports Control buttons keyboards such as ArrowDown
ArrowUp
and Enter
keys
function filterFunction(that, event) {_x000D_
let container, input, filter, li, input_val;_x000D_
container = $(that).closest(".searchable");_x000D_
input_val = container.find("input").val().toUpperCase();_x000D_
_x000D_
if (["ArrowDown", "ArrowUp", "Enter"].indexOf(event.key) != -1) {_x000D_
keyControl(event, container)_x000D_
} else {_x000D_
li = container.find("ul li");_x000D_
li.each(function (i, obj) {_x000D_
if ($(this).text().toUpperCase().indexOf(input_val) > -1) {_x000D_
$(this).show();_x000D_
} else {_x000D_
$(this).hide();_x000D_
}_x000D_
});_x000D_
_x000D_
container.find("ul li").removeClass("selected");_x000D_
setTimeout(function () {_x000D_
container.find("ul li:visible").first().addClass("selected");_x000D_
}, 100)_x000D_
}_x000D_
}_x000D_
_x000D_
function keyControl(e, container) {_x000D_
if (e.key == "ArrowDown") {_x000D_
_x000D_
if (container.find("ul li").hasClass("selected")) {_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) + 1 < container.find("ul li:visible").length) {_x000D_
container.find("ul li.selected").removeClass("selected").nextAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
_x000D_
} else {_x000D_
container.find("ul li:first-child").addClass("selected");_x000D_
}_x000D_
_x000D_
} else if (e.key == "ArrowUp") {_x000D_
_x000D_
if (container.find("ul li:visible").index(container.find("ul li.selected")) > 0) {_x000D_
container.find("ul li.selected").removeClass("selected").prevAll().not('[style*="display: none"]').first().addClass("selected");_x000D_
}_x000D_
} else if (e.key == "Enter") {_x000D_
container.find("input").val(container.find("ul li.selected").text()).blur();_x000D_
onSelect(container.find("ul li.selected").text())_x000D_
}_x000D_
_x000D_
container.find("ul li.selected")[0].scrollIntoView({_x000D_
behavior: "smooth",_x000D_
});_x000D_
}_x000D_
_x000D_
function onSelect(val) {_x000D_
alert(val)_x000D_
}_x000D_
_x000D_
$(".searchable input").focus(function () {_x000D_
$(this).closest(".searchable").find("ul").show();_x000D_
$(this).closest(".searchable").find("ul li").show();_x000D_
});_x000D_
$(".searchable input").blur(function () {_x000D_
let that = this;_x000D_
setTimeout(function () {_x000D_
$(that).closest(".searchable").find("ul").hide();_x000D_
}, 300);_x000D_
});_x000D_
_x000D_
$(document).on('click', '.searchable ul li', function () {_x000D_
$(this).closest(".searchable").find("input").val($(this).text()).blur();_x000D_
onSelect($(this).text())_x000D_
});_x000D_
_x000D_
$(".searchable ul li").hover(function () {_x000D_
$(this).closest(".searchable").find("ul li.selected").removeClass("selected");_x000D_
$(this).addClass("selected");_x000D_
});
_x000D_
div.searchable {_x000D_
width: 300px;_x000D_
float: left;_x000D_
margin: 0 15px;_x000D_
}_x000D_
_x000D_
.searchable input {_x000D_
width: 100%;_x000D_
height: 50px;_x000D_
font-size: 18px;_x000D_
padding: 10px;_x000D_
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */_x000D_
-moz-box-sizing: border-box; /* Firefox, other Gecko */_x000D_
box-sizing: border-box; /* Opera/IE 8+ */_x000D_
display: block;_x000D_
font-weight: 400;_x000D_
line-height: 1.6;_x000D_
color: #495057;_x000D_
background-color: #fff;_x000D_
background-clip: padding-box;_x000D_
border: 1px solid #ced4da;_x000D_
border-radius: .25rem;_x000D_
transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;_x000D_
background: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center/8px 10px;_x000D_
}_x000D_
_x000D_
.searchable ul {_x000D_
display: none;_x000D_
list-style-type: none;_x000D_
background-color: #fff;_x000D_
border-radius: 0 0 5px 5px;_x000D_
border: 1px solid #add8e6;_x000D_
border-top: none;_x000D_
max-height: 180px;_x000D_
margin: 0;_x000D_
overflow-y: scroll;_x000D_
overflow-x: hidden;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.searchable ul li {_x000D_
padding: 7px 9px;_x000D_
border-bottom: 1px solid #e1e1e1;_x000D_
cursor: pointer;_x000D_
color: #6e6e6e;_x000D_
}_x000D_
_x000D_
.searchable ul li.selected {_x000D_
background-color: #e8e8e8;_x000D_
color: #333;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="searchable">_x000D_
<input type="text" placeholder="search countries" onkeyup="filterFunction(this,event)">_x000D_
<ul>_x000D_
<li>Algeria</li>_x000D_
<li>Bulgaria</li>_x000D_
<li>Canada</li>_x000D_
<li>Egypt</li>_x000D_
<li>Fiji</li>_x000D_
<li>India</li>_x000D_
<li>Japan</li>_x000D_
<li>Iran (Islamic Republic of)</li>_x000D_
<li>Lao People's Democratic Republic</li>_x000D_
<li>Micronesia (Federated States of)</li>_x000D_
<li>Nicaragua</li>_x000D_
<li>Senegal</li>_x000D_
<li>Tajikistan</li>_x000D_
<li>Yemen</li>_x000D_
</ul>_x000D_
</div>
_x000D_
You can use these two libs to download files http://danml.com/download.html https://github.com/eligrey/FileSaver.js/#filesaverjs
example
// for FileSaver
import FileSaver from 'file-saver';
export function exportRecordToExcel(record) {
return ({fetch}) => ({
type: EXPORT_RECORD_TO_EXCEL,
payload: {
promise: fetch('/records/export', {
credentials: 'same-origin',
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function(response) {
return response.blob();
}).then(function(blob) {
FileSaver.saveAs(blob, 'nameFile.zip');
})
}
});
// for download
let download = require('./download.min');
export function exportRecordToExcel(record) {
return ({fetch}) => ({
type: EXPORT_RECORD_TO_EXCEL,
payload: {
promise: fetch('/records/export', {
credentials: 'same-origin',
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(function(response) {
return response.blob();
}).then(function(blob) {
download (blob);
})
}
});
i want to mention some important point to bare in mind while implementing class binding.
[ngClass] = "{
'badge-secondary': somevariable === value1,
'badge-danger': somevariable === value1,
'badge-warning': somevariable === value1,
'badge-warning': somevariable === value1,
'badge-success': somevariable === value1 }"
class here is not binding correctly because one condition is to be met, whereas you have two identical classes 'badge-warning' that may have two different condition. To correct this
[ngClass] = "{
'badge-secondary': somevariable === value1,
'badge-danger': somevariable === value1,
'badge-warning': somevariable === value1 || somevariable === value1,
'badge-success': somevariable === value1 }"
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
Start the Mosquitto Broker
Open the terminal and type
mosquitto_sub -h 127.0.0.1 -t topic
Open another terminal and type
mosquitto_pub -h 127.0.0.1 -t topic -m "Hello"
Now you can switch to the previous terminal and there you can able to see the "Hello" Message.One terminal acts as publisher and another one subscriber.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class form_city : System.Web.UI.Page
{
connection con = new connection();
DataTable dtable;
string status = "";
protected void Page_Load(object sender, EventArgs e)
{
TextBoxWatermarkExtender1.WatermarkText = "Enter State Name !";
if (!IsPostBack)
{
status = "Active";
fillgrid();
Session.Add("ope", "Listing");
}
}
protected void fillgrid()
{
//Session.Add("ope", "Listing");
string query = "select *";
query += "from State_Detail where Status='" + status + "'";
dtable = con.sqlSelect(query);
grdList.DataSource = dtable;
grdList.DataBind();
lbtnBack.Visible = false;
}
protected void grdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdList.PageIndex = e.NewPageIndex;
string operation = Session["ope"].ToString();
if (operation == "ViewLog")
status = "Inactive";
else if (operation == "Listing")
status = "Active";
fillgrid();
}
public string GetImage(string status)
{
if (status == "Active")
return "~/images/green_acti.png";
else
return "~/images/red_acti.png";
}
protected void grdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string st = "Inactive";
int State_Id = Convert.ToInt32(grdList.DataKeys[e.RowIndex].Values[0]);
string query = "update State_Detail set Status='" + st + "'";
query += " where State_Id=" + State_Id;
con.sqlInsUpdDel(query);
status = "Active";
fillgrid();
}
protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Select"))
{
string query = "select * ";
query += "from State_Detail where State_Id=" + e.CommandArgument;
dtable = con.sqlSelect(query);
grdList.DataSource = dtable;
grdList.DataBind();
lbtnBack.Visible = true;
}
}
protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
{
Session.Add("ope", "Listing");
if (txtDepId.Text != "")
{
string query = "select * from State_Detail where State_Name like '" + txtDepId.Text + "%'";
dtable = con.sqlSelect(query);
grdList.DataSource = dtable;
grdList.DataBind();
txtDepId.Text = "";
}
}
protected void grdList_RowEditing(object sender, GridViewEditEventArgs e)
{
int State_Id = Convert.ToInt32(grdList.DataKeys[e.NewEditIndex].Values[0]);
Session.Add("ope", "Edit");
Session.Add("State_Id", State_Id);
Response.Redirect("form_state.aspx");
}
protected void grdList_Sorting(object sender, GridViewSortEventArgs e)
{
string operation = Session["ope"].ToString();
if (operation == "ViewLog")
status = "Inactive";
else if (operation == "Listing")
status = "Active";
string query = "select * from State_Detail";
query += " where Status='" + status + "'";
dtable = con.sqlSelect(query);
DataView dview = new DataView(dtable);
dview.Sort = e.SortExpression + " asc";
grdList.DataSource = dview;
grdList.DataBind();
}
}
<asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "Status")))%>' AlternateText='<%# Bind("Status") %>' runat="server" />
this will set your session to keep everything till the browser is closed
session.setMaxinactiveinterval(-1);
and this should set it for 1 day
session.setMaxInactiveInterval(60*60*24);
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
this is my test function that I use to check Memcache on the server
<?php
public function test()
{
// memcache test - make sure you have memcache extension installed and the deamon is up and running
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
var_dump($get_result);
}
if you see something like this
Server's version: 1.4.5_4_gaa7839e
Store data in the cache (data will expire in 10 seconds)
Data from the cache:
object(stdClass)#3 (2) { ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }
it means that everything is okay
Cheers!
update 2017.12.25
"react-router-dom": "^4.2.2"
url like
BrowserHistory
: http://localhost:3000/demo-7/detail/2?sort=name
HashHistory
: http://localhost:3000/demo-7/#/detail/2?sort=name
with query-string dependency:
this.id = props.match.params.id;
this.searchObj = queryString.parse(props.location.search);
this.from = props.location.state.from;
console.log(this.id, this.searchObj, this.from);
results:
2 {sort: "name"} home
"react-router": "^2.4.1"
Url like http://localhost:8080/react-router01/1?name=novaline&age=26
const queryParams = this.props.location.query;
queryParams is a object contains the query params: {name: novaline, age: 26}
Xamarin.iOS
NSMutableParagraphStyle paragraphStyle = new NSMutableParagraphStyle();
paragraphStyle.HyphenationFactor = 1.0f;
var hyphenAttribute = new UIStringAttributes();
hyphenAttribute.ParagraphStyle = paragraphStyle;
var attributedString = new NSAttributedString(str: name, attributes: hyphenAttribute);
finally I got eclipse 3.7 working behind company firewall. I set to true "java.net.useSystemProxies" option on file "net.properties" located on "C:\Program Files\Java\jre6\lib" (this path could be different for your JRE installation). After that,set Active provider to Native on Eclipse preferences. No need to provide any proxy details anywhere, it just pick it up from system default browser settings
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Have you tried (from a command line)
java -jar jbpm-installer-3.2.7.jar
or double clicking it with the mouse ?
Found this and this by googling.
Hope it helps
The other answers require the response body to be downloaded. But there's a way to make a POST request that will only fetch the header:
curl -s -I -X POST http://www.google.com
An -I
by itself performs a HEAD request which can be overridden by -X POST
to perform a POST (or any other) request and still only get the header data.
It is not very good to re-write the history. If we use git revert <commit_id>
, it creates a clean reverse-commit of the said commit id.
This way, the history is not re-written, instead, everyone knows that there has been a revert.
I've done some workaround utility function, using imagesLoaded jquery plugin: https://github.com/desandro/imagesloaded
function waitForImageSize(src, func, ctx){
if(!ctx)ctx = window;
var img = new Image();
img.src = src;
$(img).imagesLoaded($.proxy(function(){
var w = this.img.innerWidth||this.img.naturalWidth;
var h = this.img.innerHeight||this.img.naturalHeight;
this.func.call(this.ctx, w, h, this.img);
},{img: img, func: func, ctx: ctx}));
},
You can use this by passing url, function and its context. Function is performed after image is loaded and return created image, its width and height.
waitForImageSize("image.png", function(w,h){alert(w+","+h)},this)
I couldn't get it to work using Calendar. You have to use DateFormat
//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());
//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());
//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());
userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
If this is for a non-Rails project, I'd use String#index
:
"foobar".index("foo") == 0 # => true
Just use a LinearLayout and pretend it's a Button
- setting background
and clickable is the key:
<LinearLayout
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_default"
android:clickable="true"
android:orientation="horizontal" >
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:src="@drawable/image" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_margin="5dp"
android:text="Do stuff" />
</LinearLayout>
I always try to stick with POSIX sh
instead of using Bash extensions, since one of the major points of scripting is portability (besides connecting programs, not replacing them).
In sh
, there is an easy way to check for an "is-prefix" condition.
case $HOST in node*)
# Your code here
esac
Given how old, arcane and crufty sh is (and Bash is not the cure: It's more complicated, less consistent and less portable), I'd like to point out a very nice functional aspect: While some syntax elements like case
are built-in, the resulting constructs are no different than any other job. They can be composed in the same way:
if case $HOST in node*) true;; *) false;; esac; then
# Your code here
fi
Or even shorter
if case $HOST in node*) ;; *) false;; esac; then
# Your code here
fi
Or even shorter (just to present !
as a language element -- but this is bad style now)
if ! case $HOST in node*) false;; esac; then
# Your code here
fi
If you like being explicit, build your own language element:
beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
Isn't this actually quite nice?
if beginswith node "$HOST"; then
# Your code here
fi
And since sh
is basically only jobs and string-lists (and internally processes, out of which jobs are composed), we can now even do some light functional programming:
beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
checkresult() { if [ $? = 0 ]; then echo TRUE; else echo FALSE; fi; }
all() {
test=$1; shift
for i in "$@"; do
$test "$i" || return
done
}
all "beginswith x" x xy xyz ; checkresult # Prints TRUE
all "beginswith x" x xy abc ; checkresult # Prints FALSE
This is elegant. Not that I'd advocate using sh
for anything serious -- it breaks all too quickly on real world requirements (no lambdas, so we must use strings. But nesting function calls with strings is not possible, pipes are not possible, etc.)
Here we go... just copy the code to a module, it's ready to use
Private Type hashtable
key As Variant
value As Variant
End Type
Private GetErrMsg As String
Private Function CreateHashTable(htable() As hashtable) As Boolean
GetErrMsg = ""
On Error GoTo CreateErr
ReDim htable(0)
CreateHashTable = True
Exit Function
CreateErr:
CreateHashTable = False
GetErrMsg = Err.Description
End Function
Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
GetErrMsg = ""
On Error GoTo AddErr
Dim idx As Long
idx = UBound(htable) + 1
Dim htVal As hashtable
htVal.key = key
htVal.value = value
Dim i As Long
For i = 1 To UBound(htable)
If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
Next i
ReDim Preserve htable(idx)
htable(idx) = htVal
AddValue = idx
Exit Function
AddErr:
AddValue = 0
GetErrMsg = Err.Description
End Function
Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
GetErrMsg = ""
On Error GoTo RemoveErr
Dim i As Long, idx As Long
Dim htTemp() As hashtable
idx = 0
For i = 1 To UBound(htable)
If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
ReDim Preserve htTemp(idx)
AddValue htTemp, htable(i).key, htable(i).value
idx = idx + 1
End If
Next i
If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"
htable = htTemp
RemoveValue = True
Exit Function
RemoveErr:
RemoveValue = False
GetErrMsg = Err.Description
End Function
Private Function GetValue(htable() As hashtable, key As Variant) As Variant
GetErrMsg = ""
On Error GoTo GetValueErr
Dim found As Boolean
found = False
For i = 1 To UBound(htable)
If htable(i).key = key And IsEmpty(htable(i).key) = False Then
GetValue = htable(i).value
Exit Function
End If
Next i
Err.Raise 9997, , "Key [" & CStr(key) & "] not found"
Exit Function
GetValueErr:
GetValue = ""
GetErrMsg = Err.Description
End Function
Private Function GetValueCount(htable() As hashtable) As Long
GetErrMsg = ""
On Error GoTo GetValueCountErr
GetValueCount = UBound(htable)
Exit Function
GetValueCountErr:
GetValueCount = 0
GetErrMsg = Err.Description
End Function
To use in your VB(A) App:
Public Sub Test()
Dim hashtbl() As hashtable
Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
Debug.Print ""
Debug.Print "ID Test Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
Debug.Print ""
Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
Debug.Print ""
Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
Debug.Print ""
Debug.Print "Hashtable Content:"
For i = 1 To UBound(hashtbl)
Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
Next i
Debug.Print ""
Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub
Yes:
float[] values = {0.1f, 0.2f, 0.3f};
This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:
values = new float[3];
or
values = new float[] {0.1f, 0.2f, 0.3f};
Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?
With regard to LittleBobbyTable's answer - NET SEND does not work on Vista or Windows 7. It has been replaced by MSG.EXE
There is a crude solution that works on all versions of Windows - A crude popup message can be sent by STARTing a new cmd.exe window that closes once a key is pressed.
start "" cmd /c "echo Hello world!&echo(&pause"
If you want your script to pause until the message box is dismissed, then you can add the /WAIT option.
start "" /wait cmd /c "echo Hello world!&echo(&pause"
Just push to the branch that the pull request references. As long as the pull request is still open, it should get updated with any added commits automatically.
I don't if anybody else has a better option...
<% if (Model.VariableName == "" || Model.VariableName== null) { %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "",
new{stlye=" "})%>
<% } else{ %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"],
Model.VariableName, new{stlye=" "})%>
<% }>
Never. You can never be sure that the application is able to execute the next line of code. If you get an OutOfMemoryError
, you have no guarantee that you will be able to do anything reliably. Catch RuntimeException and checked Exceptions, but never Errors.
The easiest way to fix this was to press (CTRL) and (,) in VS Code to open Settings.
After that, on the search bar search for code runner, then scroll down and search for Run In Terminal and check that box as highlighted in the below image:
Just one note I could not find in the answers above. In this code:
context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)
What the third parameter context_instance
actually does? Being RequestContext it sets up some basic context which is then added to user_context
. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS
in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user
and variable perm
which are then accessible in the template.
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
***LOGIN script that doesnt link to a database or external file. Good for a global password -
Place on Login form page - place this at the top of the login page - above everything else***
<?php
if(isset($_POST['Login'])){
if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");
}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>
*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *
<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){
header("Location: ./YourLoginPage.php");
}
?>
The syntax for REPLACE:
REPLACE (string_expression,string_pattern,string_replacement)
So that the SQL you need should be:
UPDATE [DataTable] SET [ColumnValue] = REPLACE([ColumnValue], 'domain2', 'domain1')
The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.
The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.
The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.
$(document).ready(
var xhr;
var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};
var interval = setInterval(fn, 500);
);
We face this issue but had different reason, here is the reason:
In our project found multiple bean entry with same bean name. 1 in applicationcontext.xml & 1 in dispatcherServlet.xml
Example:
<bean name="dataService" class="com.app.DataServiceImpl">
<bean name="dataService" class="com.app.DataServiceController">
& we are trying to autowired by dataService name.
Solution: we changed the bean name & its solved.
I came across this question as I was attempting to focus the ChromeVox screen reader to the top of the "screen" after navigating to a new screen in a React single page app. Basically trying to emulate what would happen if this page was loaded by following a link to a new server-rendered web page.
This solution doesn't require any listeners, it uses withRouter()
and the componentDidUpdate()
lifecycle method to trigger a click to focus ChromeVox on the desired element when navigating to a new url path.
I created a "Screen" component which is wrapped around the react-router switch tag which contains all the apps screens.
<Screen>
<Switch>
... add <Route> for each screen here...
</Switch>
</Screen>
Screen.tsx
ComponentNote: This component uses React + TypeScript
import React from 'react'
import { RouteComponentProps, withRouter } from 'react-router'
class Screen extends React.Component<RouteComponentProps> {
public screen = React.createRef<HTMLDivElement>()
public componentDidUpdate = (prevProps: RouteComponentProps) => {
if (this.props.location.pathname !== prevProps.location.pathname) {
// Hack: setTimeout delays click until end of current
// event loop to ensure new screen has mounted.
window.setTimeout(() => {
this.screen.current!.click()
}, 0)
}
}
public render() {
return <div ref={this.screen}>{this.props.children}</div>
}
}
export default withRouter(Screen)
I had tried using focus()
instead of click()
, but click causes ChromeVox to stop reading whatever it is currently reading and start again where I tell it to start.
Advanced note: In this solution, the navigation <nav>
which inside the Screen component and rendered after the <main>
content is visually positioned above the main
using css order: -1;
. So in pseudo code:
<Screen style={{ display: 'flex' }}>
<main>
<nav style={{ order: -1 }}>
<Screen>
If you have any thoughts, comments, or tips about this solution, please add a comment.
If you installed mysql through brew then we can use command to uninstall mysql.
$ brew uninstall mysql
Uninstalling /usr/local/Cellar/mysql/5.6.19...
This worked for me.
Try this instead in the end:
exec (@query)
If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.
OR
EXECUTE sp_executesql @query
And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.
Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.
On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?
As you mentioned, prompt
works for browsers all the way back to IE:
var answer = prompt('question', 'defaultAnswer');
For Node.js > v7.6, you can use console-read-write
, which is a wrapper around the low-level readline
module:
const io = require('console-read-write');
async function main() {
// Simple readline scenario
io.write('I will echo whatever you write!');
io.write(await io.read());
// Simple question scenario
io.write(`hello ${await io.ask('Who are you?')}!`);
// Since you are not blocking the IO, you can go wild with while loops!
let saidHi = false;
while (!saidHi) {
io.write('Say hi or I will repeat...');
saidHi = await io.read() === 'hi';
}
io.write('Thanks! Now you may leave.');
}
main();
// I will echo whatever you write!
// > ok
// ok
// Who are you? someone
// hello someone!
// Say hi or I will repeat...
// > no
// Say hi or I will repeat...
// > ok
// Say hi or I will repeat...
// > hi
// Thanks! Now you may leave.
Disclosure I'm author and maintainer of console-read-write
For SpiderMonkey, simple readline
as suggested by @MooGoo and @Zaz.
To append a new data element,just do this...
Document doc = docBuilder.parse(is);
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);
easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
import csv
with open('file_name.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(('colum1', 'colum2', 'colum3'))
for key, value in dictionary.items():
writer.writerow([key, value[0], value[1]])
This would be the simplest way to write data to .csv file
one could also use a fixed lengths vector and access it with indexing
int Lcs(string a, string b)
{
int x = a.size() + 1;
int y = b.size() + 1;
vector<vector<int>> L(x, vector<int>(y));
for (int i = 1; i < x; i++)
{
for (int j = 1; j < y; j++)
{
L[i][j] = a[i - 1] == b[j - 1] ?
L[i - 1][j - 1] + 1 :
max(L[i - 1][j], L[i][j - 1]);
}
}
return L[a.size()][b.size()];
}
GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.
A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB
here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
Target server must allowed cross-origin request. In order to allow it through express, simply handle http options request :
app.options('/url...', function(req, res, next){
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'POST');
res.header("Access-Control-Allow-Headers", "accept, content-type");
res.header("Access-Control-Max-Age", "1728000");
return res.sendStatus(200);
});
I used this configurations and still have the problem of pixelization :
Bitmap bmpOriginal = BitmapFactory.decodeResource(this.getResources(), R.drawable.map_pin);
Bitmap targetBitmap = Bitmap.createBitmap((bmpOriginal.getWidth()),
(bmpOriginal.getHeight()),
Bitmap.Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Matrix matrix = new Matrix();
matrix.setRotate((float) lock.getDirection(),(float) (bmpOriginal.getWidth()/2),
(float)(bmpOriginal.getHeight()/2));
RectF rectF = new RectF(0, 0, bmpOriginal.getWidth(), bmpOriginal.getHeight());
matrix.mapRect(rectF);
targetBitmap = Bitmap.createBitmap((int)rectF.width(), (int)rectF.height(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas(targetBitmap);
tempCanvas.drawBitmap(bmpOriginal, matrix, p);
**Solution which worked for me
Use NestedScrollView with height as wrap_content
<br> RecyclerView
android:layout_width="match_parent"<br>
android:layout_height="wrap_content"<br>
android:nestedScrollingEnabled="false"<br>
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
tools:targetApi="lollipop"<br><br> and view holder layout
<br> android:layout_width="match_parent"<br>
android:layout_height="wrap_content"
//Your row content goes here
This may help you find what you're looking for... Batch script loop
My answer is as follows:
@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start
:end
echo var has reached %var%.
pause
exit
The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.
I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.
The solution was as simple as closing the tab and opening a fresh one!
Java 8 datetime
API
made it so much easier :
LocalDate.now().getDayOfWeek().name()
Will return you the name of the day as String
Output : THURSDAY
Try this:
rows = tabDelimitedTable.split("[\\r\\n]+");
This should work regardless of what line delimiters are in the input, and will ignore blank lines.
I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:
private DataTable GetDataTableFromDGV(DataGridView dgv) {
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns) {
if (column.Visible) {
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows) {
for (int i = 0; i < row.Cells.Count; i++) {
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL)
, you can do arithmetic within the brackets of malloc
but you shouldnt because you should use calloc
which has the definition of void calloc(count, size)
which means how many items you want to store ie count and size of data ie int
, char
etc.
void 0
mean?void
[MDN] is a prefix keyword that takes one argument and always returns undefined
.
Examples
void 0
void (0)
void "hello"
void (new Date())
//all will return undefined
It seems pretty useless, doesn't it? If it always returns undefined
, what's wrong with just using undefined
itself?
In a perfect world we would be able to safely just use undefined
: it's much simpler and easier to understand than void 0
. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.
The problem with using undefined
was that undefined
is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined
is a permissible variable name, so you could assign a new value to it at your own caprice.
alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"
Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined
property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.
alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"
void
, on the other hand, cannot be overidden. void 0
will always return undefined
. undefined
, on the other hand, can be whatever Mr. Javascript decides he wants it to be.
void 0
, specifically?Why should we use void 0
? What's so special about 0
? Couldn't we just as easily use 1
, or 42
, or 1000000
or "Hello, world!"
?
And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0
instead of some other argument is that 0
is short and idiomatic.
Although undefined
can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0
: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined
with void 0
to reduce the number of bytes sent to the browser.
Before running ./configure
try running autoreconf -f -i
. The autoreconf program automatically runs autoheader, aclocal, automake, autopoint and libtoolize as required.
Edit to add: This is usually caused by checking out code from Git instead of extracting it from a .zip
or .tar.gz
archive. In order to trigger rebuilds when files change, Git does not preserve files' timestamps, so the configure
script might appear to be out of date. As others have mentioned, there are ways to get around this if you don't have a sufficiently recent version of autoreconf
.
Another edit: This error can also be caused by copying the source folder extracted from an archive with scp to another machine. The timestamps can be updated, suggesting that a rebuild is necessary. To avoid this, copy the archive and extract it in place.
Set it the same way you'd set the width of any other HTML element, with CSS:
audio { width: 200px; }
Note that audio
is an inline element by default in Firefox, so you might also want to set it to display: block
. Here's an example.
This is because Java Generics are implemented with Type Erasure.
Your methods would be translated, at compile time, to something like:
Method resolution occurs at compile time and doesn't consider type parameters. (see erickson's answer)
void add(Set ii);
void add(Set ss);
Both methods have the same signature without the type parameters, hence the error.
Also, be wary of additional top level domains that aren't included in some of the answers above.
For example .info, .biz, .ru, .online will throw some sentence parsers but aren't included above.
Here's some info on frequency of top level domains: https://www.westhost.com/blog/the-most-popular-top-level-domains-in-2017/
That could be addressed by editing the code above to read:
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov|ai|edu|co.uk|ru|info|biz|online)"
If you want to do this without VBA, you can use a combination of IF
, ISERROR
, and MATCH
.
So if all values are in column A, enter this formula in column B:
=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))
This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH
returns "#N/A" and ISERROR
tries to catch that.
If you want to use VBA, the quickest way is to use a FOR loop:
Sub FindMatchingValue()
Dim i as Integer, intValueToFind as integer
intValueToFind = 12345
For i = 1 to 500 ' Revise the 500 to include all of your values
If Cells(i,1).Value = intValueToFind then
MsgBox("Found value on row " & i)
Exit Sub
End If
Next i
' This MsgBox will only show if the loop completes with no success
MsgBox("Value not found in the range!")
End Sub
You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR
loop is pretty foolproof.
$(function() {_x000D_
$('#datepicker').datepicker({ dateFormat: 'yy-d-m ' }).val();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">_x000D_
<title>snippet</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input type="text" id="datepicker">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
_x000D_
In Sqlite
:
CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;
Here is an example of using the loop:
echo off
cls
:begin
set /P M=Input text to encode md5, press ENTER to exit:
if %M%==%M1% goto end
echo.|set /p ="%M%" | openssl md5
set M1=%M%
Goto begin
This is the simple batch i use when i need to encrypt any message into md5 hash on Windows(openssl required), and the program would loyally repeat itself except given Ctrl+C or empty input.
tl;dr 2016 Use RxJava and a PublishSubject to expose an Observable for the clicks.
public class ReactiveAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String[] mDataset = { "Data", "In", "Adapter" };
private final PublishSubject<String> onClickSubject = PublishSubject.create();
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final String element = mDataset[position];
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickSubject.onNext(element);
}
});
}
public Observable<String> getPositionClicks(){
return onClickSubject.asObservable();
}
}
Original Post:
Since the introduction of ListView
, onItemClickListener
has been problematic. The moment you have a click listener for any of the internal elements the callback would not be triggered but it wasn't notified or well documented (if at all) so there was a lot of confusion and SO questions about it.
Given that RecyclerView
takes it a step further and doesn't have a concept of a row/column, but rather an arbitrarily laid out amount of children, they have delegated the onClick to each one of them, or to programmer implementation.
Think of Recyclerview
not as a ListView
1:1 replacement but rather as a more flexible component for complex use cases. And as you say, your solution is what google expected of you. Now you have an adapter who can delegate onClick to an interface passed on the constructor, which is the correct pattern for both ListView
and Recyclerview
.
public static class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
public TextView txtViewTitle;
public ImageView imgViewIcon;
public IMyViewHolderClicks mListener;
public ViewHolder(View itemLayoutView, IMyViewHolderClicks listener) {
super(itemLayoutView);
mListener = listener;
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
imgViewIcon.setOnClickListener(this);
itemLayoutView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v instanceof ImageView){
mListener.onTomato((ImageView)v);
} else {
mListener.onPotato(v);
}
}
public static interface IMyViewHolderClicks {
public void onPotato(View caller);
public void onTomato(ImageView callerImage);
}
}
and then on your adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String[] mDataset = { "Data" };
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout, parent, false);
MyAdapter.ViewHolder vh = new ViewHolder(v, new MyAdapter.ViewHolder.IMyViewHolderClicks() {
public void onPotato(View caller) { Log.d("VEGETABLES", "Poh-tah-tos"); };
public void onTomato(ImageView callerImage) {Â Log.d("VEGETABLES", "To-m8-tohs"); }
});
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Get element from your dataset at this position
// Replace the contents of the view with that element
// Clear the ones that won't be used
holder.txtViewTitle.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
...
Now look into that last piece of code: onCreateViewHolder(ViewGroup parent, int viewType)
the signature already suggest different view types. For each one of them you'll require a different viewholder too, and subsequently each one of them can have a different set of clicks. Or you can just create a generic viewholder that takes any view and one onClickListener
and applies accordingly. Or delegate up one level to the orchestrator so several fragments/activities have the same list with different click behaviour. Again, all flexibility is on your side.
It is a really needed component and fairly close to what our internal implementations and improvements to ListView
were until now. It's good that Google finally acknowledges it.
For the benefit of others, here is my decryption implementation which I got to by combining the answers of @Cyril and @Marcus. This assumes that this coming in via HTTP Request with the encryptedText quoted and base64 encoded.
import base64
import urllib2
from Crypto.Cipher import AES
def decrypt(quotedEncodedEncrypted):
key = 'SecretKey'
encodedEncrypted = urllib2.unquote(quotedEncodedEncrypted)
cipher = AES.new(key)
decrypted = cipher.decrypt(base64.b64decode(encodedEncrypted))[:16]
for i in range(1, len(base64.b64decode(encodedEncrypted))/16):
cipher = AES.new(key, AES.MODE_CBC, base64.b64decode(encodedEncrypted)[(i-1)*16:i*16])
decrypted += cipher.decrypt(base64.b64decode(encodedEncrypted)[i*16:])[:16]
return decrypted.strip()
Override the onBackPressed method and do nothing if you meant to handle the back button on the device.
@Override
public void onBackPressed() {
if (shouldAllowBack()) {
super.onBackPressed();
} else {
doSomething();
}
}
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
Source code How to fetch Local Json from Assets folder
https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p
{
"responseCode": "200",
"responseMessage": "Recode Fetch Successfully!",
"responseTime": "10:22",
"employeesList": [
{
"empId": "1",
"empName": "Keshav",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9654267338",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "2",
"empName": "Ram",
"empFatherName": "Mr Dasrath ji",
"empSalary": "9999999999",
"empDesignation": "Sr. Java Developer",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "3",
"empName": "Manisha",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "8826420999",
"empDesignation": "BusinessMan",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "4",
"empName": "Happy",
"empFatherName": "Mr Ramesh Chand Gera",
"empSalary": "9582401701",
"empDesignation": "Two Wheeler",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
},
{
"empId": "5",
"empName": "Ritu",
"empFatherName": "Mr Keshav Gera",
"empSalary": "8888888888",
"empDesignation": "Sararat Vibhag",
"leaveBalance": "3",
"pfBalance": "60,000",
"pfAccountNo.": "12345678"
}
]
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee);
emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);
emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this,
LinearLayoutManager.VERTICAL, false));
emp_recycler_view.setItemAnimator(new DefaultItemAnimator());
employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);
emp_recycler_view.setAdapter(employeeAdapter);
getJsonFileFromLocally();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = EmployeeActivity.this.getAssets().open("employees.json"); //TODO Json File name from assets folder
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getJsonFileFromLocally() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
String responseCode = jsonObject.getString("responseCode");
String responseMessage = jsonObject.getString("responseMessage");
String responseTime = jsonObject.getString("responseTime");
Log.e("keshav", "responseCode -->" + responseCode);
Log.e("keshav", "responseMessage -->" + responseMessage);
Log.e("keshav", "responseTime -->" + responseTime);
if(responseCode.equals("200")){
}else{
Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
}
JSONArray jsonArray = jsonObject.getJSONArray("employeesList"); //TODO pass array object name
Log.e("keshav", "m_jArry -->" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
EmployeeModel employeeModel = new EmployeeModel();
JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);
String empId = jsonObjectEmployee.getString("empId");
String empName = jsonObjectEmployee.getString("empName");
String empDesignation = jsonObjectEmployee.getString("empDesignation");
String empSalary = jsonObjectEmployee.getString("empSalary");
String empFatherName = jsonObjectEmployee.getString("empFatherName");
employeeModel.setEmpId(""+empId);
employeeModel.setEmpName(""+empName);
employeeModel.setEmpDesignation(""+empDesignation);
employeeModel.setEmpSalary(""+empSalary);
employeeModel.setEmpFatherNamer(""+empFatherName);
employeeModelArrayList.add(employeeModel);
} // for
if(employeeModelArrayList!=null) {
employeeAdapter.dataChanged(employeeModelArrayList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
.modal.in .modal-dialog {
width:100% !important;
min-height: 100%;
margin: 0 0 0 0 !important;
bottom: 0px !important;
top: 0px;
}
.modal-content {
border:0px solid rgba(0,0,0,.2) !important;
border-radius: 0px !important;
-webkit-box-shadow: 0 0px 0px rgba(0,0,0,.5) !important;
box-shadow: 0 3px 9px rgba(0,0,0,.5) !important;
height: auto;
min-height: 100%;
}
.modal-dialog {
position: fixed !important;
margin:0px !important;
}
.bootstrap-dialog .modal-header {
border-top-left-radius: 0px !important;
border-top-right-radius: 0px !important;
}
@media (min-width: 768px)
.modal-dialog {
width: 100% !important;
margin: 0 !important;
}
You might want to look at the DecimalFormat
class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57
instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
U can get column name and value from resultSet.getMetaData(); This code work for me:
Connection conn = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = MySQLJDBCUtil.getConnection();
preparedStatement = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.size(); i++) {
preparedStatement.setObject(i + 1, params.get(i).getSqlValue());
}
ResultSet resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData();
while (resultSet.next()) {
int counter = md.getColumnCount();
String colName[] = new String[counter];
Map<String, Object> field = new HashMap<>();
for (int loop = 1; loop <= counter; loop++) {
int index = loop - 1;
colName[index] = md.getColumnLabel(loop);
field.put(colName[index], resultSet.getObject(colName[index]));
}
rows.add(field);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
}catch (Exception e1) {
e1.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return rows;
Try FileUtils
from Apache commons-io (listFiles
and iterateFiles
methods):
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
To solve your issue with the TestX
folders, I would first iterate through the list of folders:
File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
File dir = dirs[i];
if (dir.isDirectory()) {
File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
}
}
Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the RegexFileFilter.
I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model
def update_state(chat_id, state):
try:
value = Users.query.filter(Users.chat_id == str(chat_id)).first()
value.state = str(state)
db.session.flush()
db.session.commit()
#db.session.close()
except:
print('Error in def update_state')
Why use db.session.flush()
? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?
Create a function in SQL Server as below and replace the DECODE
with dbo.DECODE
CREATE FUNCTION DECODE(@CondField as nvarchar(100),@Criteria as nvarchar(100),
@True Value as nvarchar(100), @FalseValue as nvarchar(100))
returns nvarchar(100)
begin
return case when @CondField = @Criteria then @TrueValue
else @FalseValue end
end
While iterating through the loop, you are trying to change the List value in the remove() operation. This will result in ConcurrentModificationException.
Follow the below code, which will achieve what you want and yet will not throw any exceptions
private String toString(List aDrugStrengthList) {
StringBuilder str = new StringBuilder();
List removalList = new ArrayList();
for (DrugStrength aDrugStrength : aDrugStrengthList) {
if (!aDrugStrength.isValidDrugDescription()) {
removalList.add(aDrugStrength);
}
}
aDrugStrengthList.removeAll(removalList);
str.append(aDrugStrengthList);
if (str.indexOf("]") != -1) {
str.insert(str.lastIndexOf("]"), "\n " );
}
return str.toString();
}
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Try This:
<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">_x000D_
<a href="{{ url('/Dashboard') }}">_x000D_
<i class="fa fa-dashboard"></i> <span>Dashboard</span>_x000D_
</a>_x000D_
</li>
_x000D_
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
Following your comment posted to ceejayoz's answer, two things are messed up a litte:
$first
is not an array, it's a string. Replace $first = $first[0] . "%"
by $first .= "%"
. Just for simplicity. (PHP string operators)
The string being compared with LIKE
operator should be quoted. Replace LIKE ".$first."")
by LIKE '".$first."'")
. (MySQL String Comparison Functions)
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
Use a couple of functions and a boolean. Here's a pattern, not full code:
var state = false,
oddONes = function () {...},
evenOnes = function() {...};
$("#time").click(function(){
if(!state){
evenOnes();
} else {
oddOnes();
}
state = !state;
});
Or
var cases[] = {
function evenOnes(){...}, // these could even be anonymous functions
function oddOnes(){...} // function(){...}
};
var idx = 0; // should always be 0 or 1
$("#time").click(function(idx){cases[idx = ((idx+1)%2)]()}); // corrected
(Note the second is off the top of my head and I mix languages a lot, so the exact syntax isn't guaranteed. Should be close to real Javascript through.)
You can call any language from java using Java Native Interface
You should use formControlName="surveyType"
on an input
and not on a div
If you only need the standard functionality of hide only with visibility:hidden to keep the current layout you can use the callback function of hide to alter the css in the tag. Hide docs in jquery
An example :
$('#subs_selection_box').fadeOut('slow', function() {
$(this).css({"visibility":"hidden"});
$(this).css({"display":"block"});
});
This will use the normal cool animation to hide the div, but after the animation finish you set the visibility to hidden and display to block.
An example : http://jsfiddle.net/bTkKG/1/
I know you didnt want the $("#aa").css() solution, but you did not specify if it was because using only the css() method you lose the animation.
I think this may solve your problem:
in config/application.rb:
config.autoload_paths << Rails.root.join('lib')
and keep the right naming convention in lib.
in lib/foo.rb:
class Foo
end
in lib/foo/bar.rb:
class Foo::Bar
end
if you really wanna do some monkey patches in file like lib/extensions.rb, you may manually require it:
in config/initializers/require.rb:
require "#{Rails.root}/lib/extensions"
P.S.
Rails 3 Autoload Modules/Classes by Bill Harding.
And to understand what does Rails exactly do about auto-loading?
read Rails autoloading — how it works, and when it doesn't by Simon Coffey.
Use
const StartContainer = connect(null, mapDispatchToProps)(Start)
instead of
const StartContainer = connect(mapDispatchToProps)(Start)
div.style
yields an object (CSSStyleDeclaration). Since it's an object, you can alternatively use the following:
div.style["top"] = "200px";
div.style["left"] = "200px";
This is useful, for example, if you need to access a "variable" property:
div.style[prop] = "200px";
I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:
Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused
& I resolved it following way.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://hostname:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
Assume you wanna create folder abc/123/ in your bucket, it's a piece of cake with Boto
k = bucket.new_key('abc/123/')
k.set_contents_from_string('')
Or use the console
The servlet container's implementation of HttpServlet.service()
method will automatically forward to doGet()
or doPost()
as necessary, so you shouldn't need to override the service method.
I learned this from http://www.pcsalt.com/android/edittext-with-single-line-line-wrapping-and-done-action-in-android/, though I don't like the website myself. If you want multiline BUT want to retain the enter button as a post button, set the listview's "horizontally scrolling" to false.
android:scrollHorizontally="false"
If it doesn't work in xml, doing it programmatically weirdly works.
listView.setHorizontallyScrolling(false);
document.addEventListener('DOMContentLoaded', (e)=>{
print();
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {//expresion regular evalua navegador
window.onfocus = function(){window.close();}
} else {
window.onafterprint = function(e){
window.close();
}
}
});
onafterprint works good to me on desktop browser, no with smartphone, so y make something like this and work, there are many solutions, so try many anyway.
Table variables are just like int or varchar variables.
You don't need to drop them. They have the same scope rules as int or varchar variables
The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.
Laravel makes it very easy to manage your database connections through app/config/database.php
.
As you noted, it is looking for a database called 'database'. The reason being that this is the default name in the database configuration file.
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database', <------ Default name for database
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Change this to the name of the database that you would like to connect to like this:
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'my_awesome_data', <------ change name for database
'username' => 'root', <------ remember credentials
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Once you have this configured correctly you will easily be able to access your database!
Happy Coding!
In your Component you can add .class to your host element if you would have some general styles that you want to apply.
export class MyComponent{
@HostBinding('class') classes = 'classA classB';
The previous answers assume that you always have a signed index. Sadly, std::vector
uses size_type
for indexing, and difference_type
for iterator arithmetic, so they don't work together if you have "-Wconversion" and friends enabled. This is another way to answer the question, while being able to handle both signed and unsigned:
To remove:
template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
void remove(std::vector<T> &v, I index)
{
const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);
v.erase(iter);
}
To take:
template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
T take(std::vector<T> &v, I index)
{
const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);
auto val = *iter;
v.erase(iter);
return val;
}
There is a computer vision package called HALCON from MVTec whose demos could give you good algorithm ideas. There is plenty of examples similar to your problem that you could run in demo mode and then look at the operators in the code and see how to implement them from existing OpenCV operators.
I have used this package to quickly prototype complex algorithms for problems like this and then find how to implement them using existing OpenCV features. In particular for your case you could try to implement in OpenCV the functionality embedded in the operator find_scaled_shape_model. Some operators point to the scientific paper regarding algorithm implementation which can help to find out how to do something similar in OpenCV. Hope this helps...
Default-Values are only considered for parameters NOT given to the function.
So given a function
procedure foo( bar1 IN number DEFAULT 3,
bar2 IN number DEFAULT 5,
bar3 IN number DEFAULT 8 );
if you call this procedure with no arguments then it will behave as if called with
foo( bar1 => 3,
bar2 => 5,
bar3 => 8 );
but 'NULL' is still a parameter.
foo( 4,
bar3 => NULL );
This will then act like
foo( bar1 => 4,
bar2 => 5,
bar3 => Null );
( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )
one way to treat NULL the same as a default value would be to default the value to NULL
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL );
and using a variable with the desired value then
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL )
AS
v_bar1 number := NVL( bar1, 3);
v_bar2 number := NVL( bar2, 5);
v_bar3 number := NVL( bar3, 8);
You want:
git rm --cached [file]
If you omit the --cached
option, it will also delete it from the working tree. git rm
is slightly safer than git reset
, because you'll be warned if the staged content doesn't match either the tip of the branch or the file on disk. (If it doesn't, you have to add --force
.)
For me, this simply works:
error: function(xhr, status, error) {
alert(xhr.responseText);
}
(char)myint;
for example:
Console.WriteLine("(char)122 is {0}", (char)122);
yields:
(char)122 is z
Use &
SCSS
.container {
background:red;
color:white;
&.hello {
padding-left:50px;
}
}
https://sass-lang.com/documentation/style-rules/parent-selector
If s is your string:
s.replace(/^[^(]*\(/, "") // trim everything before first parenthesis
.replace(/\)[^(]*$/, "") // trim everything after last parenthesis
.split(/\)[^(]*\(/); // split between parenthesis
Specify path after entered commit message, like:
git commit -m "commit message" path/to/file.extention
I think functional requirement is from client to developer side that is regarding functionality to the user by the software and non-functional requirement is from developer to client i.e. the requirement is not given by client but it is provided by developer to run the system smoothly e.g. safety, security, flexibility, scalability, availability, etc.
Sample 3 would be the worst performer out of them all because you are hitting up the database countless times for no apparent reason.
Loading the data into a temp table and then joining on that would be by far the fastest. After that the IN should work slightly faster than the group of ORs.
Other answers have already given you the code you need to iterate though a string using a while
loop (or a for
loop) but I thought it might be useful to explain the difference between the two types of loops.
while
loops repeat some code until a certain condition is met. For example:
import random
sum = 0
while sum < 100:
sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
print sum
This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.
for
loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java for
loops usually use some sort of a counter variable (below I use i
), and generally makes the similarity between while
and for
loops much more explicit.
for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
System.out.println(i);
}
This loop will run exactly 10 times. This is just a nicer way to write this:
int i = 0;
while (i < 10) { //until i is 10
System.out.println(i);
i++; //add one to i
}
The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:
for item in myList:
print item
or
for character in myString:
print character
However, you didn't want to use a for
loop. In that case, you'll need to look at each character using its index. Like this:
print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.
Knowing that you can make a for
loop using only a while
loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a while
loop.
HOWEVER in general you'd use a for
loop in this situation because it's easier to read.
It's between the Z and the C on your keyboard.
You put your image in resources folder and use follow code:
JButton btn = new JButton("");
btn.setIcon(new ImageIcon(Class.class.getResource("/resources/img.png")));
It may be related to Java JRE version.
In my case I need Tomcat 6.0.26 which presented same error with JRE 1.8.0_91. A downgrade to JRE 1.7.49 solved it.
You might find more information in: http://www.howopensource.com/2015/07/unable-to-compile-class-for-jsp-the-type-java-util-mapentry-cannot-be-resolved/
Also it'd work to just specify ifelse()
twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))
File: logdate.aspx
<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%
StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());
tsw.Close();
%>
Done
Remember Running Background, Running continuously are two different tasks.
For long-term background processes, Threads aren't optimal with Android. However, here's the code and do it at your own risk...
Remember Service or Thread will run in the background but our task needs to make trigger (call again and again) to get updates, i.e. once the task is completed we need to recall the function for next update.
Timer (periodic trigger), Alarm (Timebase trigger), Broadcast (Event base Trigger), recursion will awake our functions.
public static boolean isRecursionEnable = true;
void runInBackground() {
if (!isRecursionEnable)
// Handle not to start multiple parallel threads
return;
// isRecursionEnable = false; when u want to stop
// on exception on thread make it true again
new Thread(new Runnable() {
@Override
public void run() {
// DO your work here
// get the data
if (activity_is_not_in_background) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// update UI
runInBackground();
}
});
} else {
runInBackground();
}
}
}).start();
}
Using Service: If you launch a Service it will start, It will execute the task, and it will terminate itself. after the task execution. terminated might also be caused by exception, or user killed it manually from settings. START_STICKY (Sticky Service) is the option given by android that service will restart itself if service terminated.
Remember the question difference between multiprocessing and multithreading? Service is a background process (Just like activity without UI), The same way how you launch thread in the activity to avoid load on the main thread (Activity thread), the same way you need to launch threads(or async tasks) on service to avoid load on service.
In a single statement, if you want a run a background continues task, you need to launch a StickyService and run the thread in the service on event base
Basically it's OK to store your JWT in your localStorage.
And I think this is a good way. If we are talking about XSS, XSS using CDN, it's also a potential risk of getting your client's login/pass as well. Storing data in local storage will prevent CSRF attacks at least.
You need to be aware of both and choose what you want. Both attacks it's not all you are need to be aware of, just remember: YOUR ENTIRE APP IS ONLY AS SECURE AS THE LEAST SECURE POINT OF YOUR APP.
Once again storing is OK, be vulnerable to XSS, CSRF,... isn't
Enabling Relation View in phpMyAdmin / MAMP
If you’re using MAMP for your database driven projects you’ll probably be using phpMyAdmin to administer your MySQL database if you’ve decided to go down that route. If you’re creating a database you might be wondering how to create relationships and foriegn keys for your tables.
Firstly you need to check that you have access to the Relation view. To do this open phpMyAdmin and select a database. You need to make sure your tables’ storage engine is set to use InnoDB. Click on a table within your database and choose the Operations tab. Make sure that the storage engine is set to use InnoDB and save your changes.
Now, go back to your table view and click the Structure tab. Depending on your version of phpMyAdmin you should see a link titled Relation view below the table structure. If you can see it you’re good to go. If you can’t you’ll need to follow the steps below to set phpMyAdmin to enable Relations view.
/Applications/MAMP/bin/phpMyAdmin/scripts/create_tables.sql
/Applications/MAMP/bin/phpMyAdmin/config.inc.php
Find the Server(s) configuration code block and replace/uncomment the following code and fill in the values. If you left everything default in the create_tables.sql file then you should just cut and paste the lines below.
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history';
Save the file and restart MAMP and refresh your phpMyAdmin console.
Go to your database and view one of your tables in Structure mode. You should now see the Relation view link.
Source: http://newvibes.com/blog/enabling-relation-view-in-phpmyadmin-mamp/
I tried everything, but this is the only thing that worked.
useLayoutEffect(() => {
document.getElementById("someID").scrollTo(0, 0);
});
It's an old question, but still active as there is no explicit Android feature. And the guys from facebook found a work around - somehow. Today, I found a way that works for me. Not perfect (see remarks at the end of this answer) but it works!
Main idea is, that I update the icon of my app's shortcut, created by the launcher on my home screen. When I want to change something on the shortcut-icon, I remove it first and recreate it with a new bitmap.
Here is the code. It has a button increment
. When pressed, the shortcut is replaced with one that has a new counting number.
First you need these two permissions in your manifest:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
Then you need this two methods for installing and uninstalling shortcuts. The shortcutAdd
method creates a bitmap with a number in it. This is just to demonstrate that it actually changes. You probably want to change that part with something, you want in your app.
private void shortcutAdd(String name, int number) {
// Intent to be send, when shortcut is pressed by user ("launched")
Intent shortcutIntent = new Intent(getApplicationContext(), Play.class);
shortcutIntent.setAction(Constants.ACTION_PLAY);
// Create bitmap with number in it -> very default. You probably want to give it a more stylish look
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
paint.setColor(0xFF808080); // gray
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(50);
new Canvas(bitmap).drawText(""+number, 50, 50, paint);
((ImageView) findViewById(R.id.icon)).setImageBitmap(bitmap);
// Decorate the shortcut
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
// Inform launcher to create shortcut
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
private void shortcutDel(String name) {
// Intent to be send, when shortcut is pressed by user ("launched")
Intent shortcutIntent = new Intent(getApplicationContext(), Play.class);
shortcutIntent.setAction(Constants.ACTION_PLAY);
// Decorate the shortcut
Intent delIntent = new Intent();
delIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
delIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
// Inform launcher to remove shortcut
delIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(delIntent);
}
And finally, here are two listener to add the first shortcut and update the shortcut with an incrementing counter.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
findViewById(R.id.add).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
shortcutAdd("changeIt!", count);
}
});
findViewById(R.id.increment).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
shortcutDel("changeIt!");
count++;
shortcutAdd("changeIt!", count);
}
});
}
Remarks:
This way works also if your App controls more shortcuts on the home screen, e.g. with different extra's in the Intent
. They just need different names so that the right one is uninstalled and reinstalled.
The programmatical handling of shortcuts in Android is a well known, widely used but not officially supported Android feature. It seems to work on the default launcher and I never tried it anywhere else. So dont blame me, when you get this user-emails "It does not work on my XYZ, double rooted, super blasted phone"
The launcher writes a Toast
when a shortcut was installad and one when a shortcut was uninstalled. So I get two Toast
s every time I change the icon. This is not perfect, but well, as long as the rest of my app is perfect...
Check out the BeamIt open source project. It will connect via bluetooth and WIFI (although it claims it does not do WIFI) and I have verified that it works well in my projects. It will allow peer to peer contact easily.
As for multiple connections, it is possible, but you will have to edit the BeamIt source code to make it possible. I suggest reading the GameKit programming guide
If you plan to build a full functional applications with more than a handful of features, I will suggest to jump right to using Eclipse RCP as the framework.
If your application won't grow too big or your requirements are just too unique to be handled by a normal business framework, you can safely jump with Swing.
At the end of the day, I'd suggest you to try both technologies to find the one suit you better. Like Netbeans vs Eclipse vs IntelliJ, there is no the absolute correct answer here and both frameworks have their own drawbacks.
Pro Swing:
Pro SWT:
I just had the same error with Visual Studio 2013 and EF6. I had to use a NewGet packed Entity Framework and done the job perfectly
Basically you can't access variables from parent directly. You do this by events. Component's output property is responsible for this. I would suggest reading https://angular.io/docs/ts/latest/guide/template-syntax.html#input-and-output-properties
DateFormatSymbols class provides methods for our ease use.
To get short month strings. For example: "Jan", "Feb", etc.
getShortMonths()
To get month strings. For example: "January", "February", etc.
getMonths()
Sample code to return month string in mmm format,
private static String getShortMonthFromNumber(int month){
if(month<0 || month>11){
return "";
}
return new DateFormatSymbols().getShortMonths()[month];
}
I have figured it out lol. for the button do .setBounds(0, 0, 220, 30) The .setBounds layout is like this (int x, int y, int width, int height)
what is the type of the field EventDate
, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort
As PPK points out here, in IE you can also use
e.cancelBubble = true;
The best answer to this could be
Don't use selct for this job use input instead
like this
echo $this->Form->input('field_name', array(
'type' => 'select',
'options' => $options_arr,
'label' => 'label here',
'value' => $id, // default value
'escape' => false, // prevent HTML being automatically escaped
'error' => false,
'class' => 'form-control' // custom class you want to enter
));
Hope it helps.
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
There's lightweight binary editor, check hexedit. http://www.linux.org/apps/AppId_6968.html. I tried using it for editing ELF binaries in Linux at least.
In this answer there is also the best answer I found to your question:
HTML table with fixed headers?
and based on pure CSS.
UIButton* closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 50, 90, 35)];
//Customise this button as you wish then
closeBtn.layer.cornerRadius = 10;
closeBtn.layer.masksToBounds = YES;//Important
The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:
It can be just the usual Single View Application.
Replace the ViewController.swift code with the following:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Data model: These strings will be the data for the table view cells
let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
// cell reuse id (cells that scroll out of view can be reused)
let cellReuseIdentifier = "cell"
// don't forget to hook this up from the storyboard
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Register the table view cell class and its reuse id
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
// (optional) include this line if you want to remove the extra empty cell divider lines
// self.tableView.tableFooterView = UIView()
// This view controller itself will provide the delegate methods and row data for the table view.
tableView.delegate = self
tableView.dataSource = self
}
// number of rows in table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.animals.count
}
// create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// create a new cell if needed or reuse an old one
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
// set the text from the data model
cell.textLabel?.text = self.animals[indexPath.row]
return cell
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You tapped cell number \(indexPath.row).")
}
}
Read the in-code comments to see what is happening. The highlights are
UITableViewDelegate
and UITableViewDataSource
protocols.numberOfRowsInSection
method determines how many rows there will be in the table view.cellForRowAtIndexPath
method sets up each row.didSelectRowAtIndexPath
method is called every time a row is tapped.Drag a UITableView
onto your View Controller. Use auto layout to pin the four sides.
Control drag from the Table View in IB to the tableView
outlet in the code.
That's all. You should be able run your app now.
This answer was tested with Xcode 9 and Swift 4
Row Deletion
You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.
Row Spacing
If you would like to have spacing between your rows, see this supplemental example.
Custom cells
The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.
Dynamic Cell Height
Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
//Your stuff
});
Have you tried using Timestamp.valueOf(String)
? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:
import java.sql.*;
public class Test {
public static void main(String[] args) {
String text = "2011-10-02 18:48:05.123456";
Timestamp ts = Timestamp.valueOf(text);
System.out.println(ts.getNanos());
}
}
Assuming you've already validated the string length, this will convert to the right format:
static String convertSeparators(String input) {
char[] chars = input.toCharArray();
chars[10] = ' ';
chars[13] = ':';
chars[16] = ':';
return new String(chars);
}
Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat
(I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt
. You can then combine the values pretty easily:
Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
Following code shows how to upload a file to a SFTP server using our Rebex SFTP component.
// create client, connect and log in
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server
client.PutFile(@"c:\data\test.zip", "test.zip");
client.Disconnect();
You can write a complete communication log to a file using a LogWriter property as follows. Examples output (from FTP component but the SFTP output is similar) can be found here.
client.LogWriter = new Rebex.FileLogWriter(
@"c:\temp\log.txt", Rebex.LogLevel.Debug);
or intercept the communication using events as follows:
Sftp client = new Sftp();
client.CommandSent += new SftpCommandSentEventHandler(client_CommandSent);
client.ResponseRead += new SftpResponseReadEventHandler(client_ResponseRead);
client.Connect("sftp.example.org");
//...
private void client_CommandSent(object sender, SftpCommandSentEventArgs e)
{
Console.WriteLine("Command: {0}", e.Command);
}
private void client_ResponseRead(object sender, SftpResponseReadEventArgs e)
{
Console.WriteLine("Response: {0}", e.Response);
}
For more info see tutorial or download a trial and check samples.
You'll want to do get a Calendar instance and get it's day of month
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
String dayOfMonthStr = String.valueOf(dayOfMonth);
You can also get DAY_OF_WEEK, DAY_OF_YEAR, DAY_OF_WEEK_IN_MONTH, etc.
Note that callback syntax is deprecated:
Deprecation Notice
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Here a modernized solution using the promise
interface
$.ajax({url: "...", cache: false}).done(function( data ) {
// data contains result
}).fail(function(err){
// error
});
You can get the parameters you are asking for by typing:
dir /?
For the full list, try:
dir /s /b /a:d
It sounds like you want to do a nearest neighbour search with some bound on the distance. SQL does not support anything like this as far as I am aware and you would need to use an alternative data structure such as an R-tree or kd-tree.
The best way to secure phpMyAdmin is the combination of all these 4:
1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)
Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:
# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):
sudo nano /etc/apache2/conf-available/phpmyadmin.conf
/etc/phpmyadmin/apache.conf
Change: phpmyadmin URL by this line:
Alias /newphpmyadminname /usr/share/phpmyadmin
Add: AllowOverride All
<Directory /usr/share/phpmyadmin>
Options FollowSymLinks
DirectoryIndex index.php
AllowOverride Limit
...
sudo systemctl restart apache2
sudo nano /usr/share/phpmyadmin/.htaccess
deny from all
allow from 127.0.0.1
alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
alias myip="echo ${SSH_CONNECTION%% *}"
# Secure Web Access to phpMyAdmin:
Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04
PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add
C:\Windows\System32\drivers\etc
Notepad - Run As Administrator - open: hosts
127.0.0.1 pma.yourdomain.com
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)
# Check to make sure you are on SSH Tunnel
1. Windows - CMD:
ping pma.yourdomain.com
ping www.yourdomain.com
# See PuTTY ports:
netstat -ano |find /i "listening"
2. Test live:
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/
If you are able to do these all successfully,
you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.
Sometimes spacing and Order of parameters in connection string matters (based on personal experience and a long night :S)
So stick to the standard format here
Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;
This works for me on all devices [ iOS, Android and Window Mobile 8.1 ].
Does not look like the best way by any means... but cannot be more simpler :)
<a href="bingmaps:?cp=18.551464~73.951399">
<a href="http://maps.apple.com/maps?q=18.551464, 73.951399">
Open Maps
</a>
</a>
this worked for me!
if some_queryset.objects.all().exists(): print("this table is not empty")
Use optparse
which comes with the standard library. For example:
#!/usr/bin/env python
import optparse
def main():
p = optparse.OptionParser()
p.add_option('--person', '-p', default="world")
options, arguments = p.parse_args()
print 'Hello %s' % options.person
if __name__ == '__main__':
main()
Source: Using Python to create UNIX command line tools
However as of Python 2.7 optparse is deprecated, see: Why use argparse rather than optparse?
You can also use,
output <- as.matrix(as.data.frame(z))
The memory usage is very similar to
output <- matrix(unlist(z), ncol = 10, byrow = TRUE)
Which can be verified, with mem_changed()
from library(pryr)
.
it's also a good thing to make sure you have the right import
I had an issue like that and I found out that the bean was using
javax.faces.view.ViewScoped;
^
instead of
javax.faces.bean.ViewScoped;
^
ES6: Using async/await
you can do below getMeta
function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await
keyword and change variable end
to img
, and change var
to let
keyword). You need to run getMeta
by await
only from async
function (run).
function getMeta(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject();
img.src = url;
});
}
async function run() {
let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
let w = img.width;
let h = img.height;
size.innerText = `width=${w}px, height=${h}px`;
size.appendChild(img);
}
run();
_x000D_
<div id="size" />
_x000D_
You can use monitorEvents function.
Just inspect your element (right mouse click
? Inspect
on visible element or go to Elements
tab in Chrome Developer Tools and select wanted element) then go to Console
tab and write:
monitorEvents($0)
Now when you move mouse over this element, focus or click it, the name of the fired event will be displayed with its data.
To stop getting this data just write this to console:
unmonitorEvents($0)
$0
is just the last DOM element selected by Chrome Developer Tools. You can pass any other DOM object there (for example result of getElementById
or querySelector
).
You can also specify event "type" as second parameter to narrow monitored events to some predefined set. For example:
monitorEvents(document.body, 'mouse')
List of this available types is here.
I made a small gif that illustrates how this feature works:
An updated answer here as of 2017, should anyone need it, is that onhashchange
is well supported in all major browsers. See caniuse for details. To use it with jQuery no plugin is needed:
$( window ).on( 'hashchange', function( e ) {
console.log( 'hash changed' );
} );
Occasionally I come across legacy systems where hashbang URL's are still used and this is helpful. If you're building something new and using hash links I highly suggest you consider using the HTML5 pushState API instead.
This command alone solved my problem:
npm cache clean --force
Also you should make sure you are using the correct version of node.
Using nvm to manage the node version:
nvm list; # check your local versions;
nvm install 10.10.0; # install a new remote version;
nvm alias default 10.10.0; # set the 10.10.0 as the default node version, but you have to restart the terminal to make it take effect;
I may be late to the party, but this is something which bugged me for too long. In my experience, I would rather want to see which changes are pending than update my working copy and deal with those changes.
This goes in the ~/.gitconfig
file:
[alias]
diffpull=!git fetch && git diff HEAD..@{u}
It fetches the current branch, then does a diff between the working copy and this fetched branch. So you should only see the changes that would come with git pull
.
You can Use ----
(@item.rigged) ? "Yes" : "No"
If @item.rigged is true, it will return 'Yes' else it will return 'No'
None of the above worked out for me until I changed the Action as [HttpPost]
.
and made the ajax type as POST
.
[HttpPost]
public JsonResult GetSelectedSignalData(string signal1,...)
{
JsonResult result = new JsonResult();
var signalData = GetTheData();
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
result.Data = serializer.Serialize(signalData);
return Json(result, JsonRequestBehavior.AllowGet);
..
..
...
}
And the ajax call as
$.ajax({
type: "POST",
url: some_url,
data: JSON.stringify({ signal1: signal1,.. }),
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data !== null) {
setValue();
}
},
failure: function (data) {
$('#errMessage').text("Error...");
},
error: function (data) {
$('#errMessage').text("Error...");
}
});
put quotes around your variable. If it happens to have spaces, it will give you "ambiguous redirect" as well. also check your spelling
echo $AAAA" "$DDDD" "$MOL_TAG >> "${OUPUT_RESULTS}"
eg of ambiguous redirect
$ var="file with spaces"
$ echo $AAAA" "$DDDD" "$MOL_TAG >> ${var}
bash: ${var}: ambiguous redirect
$ echo $AAAA" "$DDDD" "$MOL_TAG >> "${var}"
$ cat file\ with\ spaces
aaaa dddd mol_tag
And this works for me:
$(function () {
$('#datetimepicker5').datetimepicker({
format: 'HH:mm'
});
});
As other people have answered, you need to do;
myDropDown.Items.Remove(ListItem li);
but if you want the page to refresh asynchronously, the dropdown needs to be inside an asp:UpdatePanel
after you do the Remove
call, you need to call:
yourPanel.Update();
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The problem is that 2011-01-31 really is 2011-01-31 00:00:00. That is the beginning of the day. Everything during the day is not included.
Using boto3
(currently version 1.4.4) use S3.Object.delete()
.
import boto3
s3 = boto3.resource('s3')
s3.Object('your-bucket', 'your-key').delete()
If you will place your definitions in this order then the code will be compiled
class Ball;
class Player {
public:
void doSomething(Ball& ball);
private:
};
class Ball {
public:
Player& PlayerB;
float ballPosX = 800;
private:
};
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
int main()
{
}
The definition of function doSomething requires the complete definition of class Ball because it access its data member.
In your code example module Player.cpp has no access to the definition of class Ball so the compiler issues an error.
The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.
Having said that it would be possible to trigger an alert from the controller code by doing something like this -
public ActionResult ActionName(PostBackData postbackdata)
{
//your DB code
return new JavascriptResult { Script = "alert('Successfully registered');" };
}
You can find further info in this question - How to display "Message box" using MVC3 controller
I used friedmud's answer. I looked into this for a while, and it seems to be a good way to get started. This solution also has a well defined method of adding compiler flags. I answered again, because I made changes to make it work in my environment, Ubuntu and g++. More working examples are the best teacher, sometimes.
appname := myapp
CXX := g++
CXXFLAGS := -Wall -g
srcfiles := $(shell find . -maxdepth 1 -name "*.cpp")
objects := $(patsubst %.cpp, %.o, $(srcfiles))
all: $(appname)
$(appname): $(objects)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)
depend: .depend
.depend: $(srcfiles)
rm -f ./.depend
$(CXX) $(CXXFLAGS) -MM $^>>./.depend;
clean:
rm -f $(objects)
dist-clean: clean
rm -f *~ .depend
include .depend
Makefiles seem to be very complex. I was using one, but it was generating an error related to not linking in g++ libraries. This configuration solved that problem.
I too got this error. Incidentally, i typed __int__ instead of __init__.
I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.
If you're using Angularjs, you can use the angular-materialize plugin, which provides some handy directives. Then you don't need to initialize in the js, just add material-select
to your select:
<div input-field>
<select class="" ng-model="select.value1" material-select>
<option ng-repeat="value in select.choices">{{value}}</option>
</select>
</div>
While you are installing Git, you can select the option shown below, it'll help you to set the path automatically.
Its worked out for me :)
In case of a large file you can use pandas.read_csv
with the chunksize
argument which allows to read the dataset per chunk:
import pandas as pd
INPUT_CSV = "input.csv"
OUTPUT_CSV = "output.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory
header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
chunk_df["Berry"] = chunk_df["Name"]
# You apply any other transformation to the chunk
# ...
chunk_df.to_csv(OUTPUT_CSV, header=header, mode=mode)
header = False # Do not save the header for the other chunks
mode = "a" # 'a' stands for append mode, all the other chunks will be appended
If you want to update the file inplace, you can use a temporary file and erase it at the end
import pandas as pd
INPUT_CSV = "input.csv"
TMP_CSV = "tmp.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory
header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
chunk_df["Berry"] = chunk_df["Name"]
# You apply any other transformation to the chunk
# ...
chunk_df.to_csv(TMP_CSV, header=header, mode=mode)
header = False # Do not save the header for the other chunks
mode = "a" # 'a' stands for append mode, all the other chunks will be appended
os.replace(TMP_CSV, INPUT_CSV)
You'll want to install the sshpass program. Then:
sshpass -p YOUR_PASSWORD sftp -oBatchMode=no -b YOUR_COMMAND_FILE_PATH USER@HOST
Obviously, it's better to setup public key authentication. Only use this if that's impossible to do, for whatever reason.
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
All this complexity ("late static binding" ... harumph) is, to me, simply a sign of PHP's broken object/class model. If class objects were first-class objects (see Python), then "$_instance" would be a class instance variable -- a member of the class object, as opposed to a member/property of its instances, and also as opposed to shared by its descendants. In the Smalltalk world, this is the difference between a "class variable" and a "class instance variable".
In PHP, it looks to me as though we need to take to heart the guidance that patterns are a guide towards writing code -- we might perhaps think about a Singleton template, but trying to write code that inherits from an actual "Singleton" class looks misguided for PHP (though I supposed some enterprising soul could create a suitable SVN keyword).
I will continue to just code each singleton separately, using a shared template.
Notice that I'm absolutely staying OUT of the singletons-are-evil discussion, life is too short.
Try gzipping some data through the gzip libary like this...
import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()
... then run your code as posted ...
import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content
This method worked for me as for some reason the gzip library fails to read some files.
building on mwigdahls answer. if you also need to do grouping here is how to get it to look like
group, csv
'group1', 'paul, john'
'group2', 'mary'
--drop table #user
create table #user (groupName varchar(25), username varchar(25))
insert into #user (groupname, username) values ('apostles', 'Paul')
insert into #user (groupname, username) values ('apostles', 'John')
insert into #user (groupname, username) values ('family','Mary')
select
g1.groupname
, stuff((
select ', ' + g.username
from #user g
where g.groupName = g1.groupname
order by g.username
for xml path('')
),1,2,'') as name_csv
from #user g1
group by g1.groupname
The SoundPlayer class can do this. It looks like all you have to do is set its Stream property to the stream, then call Play
.
edit
I don't think it can play MP3 files though; it seems limited to .wav. I'm not certain if there's anything in the framework that can play an MP3 file directly. Everything I find about that involves either using a WMP control or interacting with DirectX.
I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.
Just add:
import os
in the beginning, before:
from settings import PROJECT_ROOT
This will import the python's module os, which apparently is used later in the code of your module without being imported.
This situation occurred to me when I uninstalled a method and tried to reinstall it. My very same interpreter, which worked before, suddenly stopped working. And this error occurred.
I tried restarting my PC, reinstalling Pycharm, invalidating caches, nothing worked.
Then I went here to reinstall the interpreter: https://www.python.org/downloads/
When you install it, there's an option to fix the python.exe interpreter. Click that. My IDE went back to normal working conditions.
For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:
// Didn't work
<div>
<TroubledComponent/>
</div>
// Worked
<div key='uniqueKey'>
<TroubledComponent/>
</div>
It is working. Just modify to null check:
if(document.body != null){
document.body.appendChild(element);
}
Pointy's suggestion is good; it may work, but I didn't try.
It's been some time since I've used Matlab, but from memory it does provide (albeit with extra plugins) the ability to generate source to allow you to realise your algorithm on a DSP.
Since python is a general purpose programming language there is no reason why you couldn't do everything in python that you can do in matlab. However, matlab does provide a number of other tools - eg. a very broad array of dsp features, a broad array of S and Z domain features.
All of these could be hand coded in python (since it's a general purpose language), but if all you're after is the results perhaps spending the money on Matlab is the cheaper option?
These features have also been tuned for performance. eg. The documentation for Numpy specifies that their Fourier transform is optimised for power of 2 point data sets. As I understand Matlab has been written to use the most efficient Fourier transform to suit the size of the data set, not just power of 2.
edit: Oh, and in Matlab you can produce some sensational looking plots very easily, which is important when you're presenting your data. Again, certainly not impossible using other tools.
I have installed python 3.7.4. First, I tried python in my command prompt. It was saying that 'Python is not recognized command......'. Then I tried 'py' command and it works.
My sample command is:
py hacker.py
To show months as Jan 2017 Feb 2017 etc:
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
Angle the dates if they take up too much space:
theme(axis.text.x=element_text(angle=60, hjust=1))
You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.
public static final URL ICON16 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug16.png");
public static final URL ICON32 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug32.png");
public static final URL ICON96 = HelperUi.class.getResource("/com/jsql/view/swing/resources/images/software/bug96.png");
List<Image> images = new ArrayList<>();
try {
images.add(ImageIO.read(HelperUi.ICON96));
images.add(ImageIO.read(HelperUi.ICON32));
images.add(ImageIO.read(HelperUi.ICON16));
} catch (IOException e) {
LOGGER.error(e, e);
}
// Define a small and large app icon
this.setIconImages(images);
In Intellij13, you can use Editor configuration like below:
This works good
worksheet.get_Range("A1","A14").Cells.HorizontalAlignment =
Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
I got the same error when issuing a URL without the protocol (like localhost:4200
) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).
Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.
Make sure there are no 'echo off' statements in the scripts and call 'echo on' after calling each script to reset any you have missed.
The reason is that if echo is left on, then the command interpreter will output each command (after parameter processing) before executing it. Makes it look really bad for using in production, but very useful for debugging purposes as you can see where output has gone wrong.
Also, make sure you are checking the ErrorLevels set by the called batch scripts and programs. Remember that there are 2 different methods used in .bat files for this. If you called a program, the Error level is in %ERRORLEVEL%, while from batch files the error level is returned in the ErrorLevel variable and doesn't need %'s around it.
Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.
You could try passing a callback function to perform the replacement:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace
function repeatedly, and using the DOM method proposed by Dmitrij.
Your way seems to be faster...
Why do you need it, though?
Hope this tip will save someone else's life. In my case the problem was that I ran out of memory, but only slightly, was hard to think about it. Wasted 3hrs on that. I recommend running:
sudo htop
or
sudo free -m
...along with running problematic requests on the server to see if your memory doesn't run out. And if it does like in my case, you need to create a swap file (unless you already have one).
I have followed this tutorial to create swap file on Ubuntu Server 14.04 and it worked just fine: http://www.cyberciti.biz/faq/ubuntu-linux-create-add-swap-file/
To get milliseconds for current date.
Swift 4+:
func currentTimeInMilliSeconds()-> Int
{
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
You can only manually delete properties of objects. Thus:
var container = {};
container.instance = new class();
delete container.instance;
However, this won't work on any other pointers. Therefore:
var container = {};
container.instance = new class();
var pointer = container.instance;
delete pointer; // false ( ie attempt to delete failed )
Furthermore:
delete container.instance; // true ( ie attempt to delete succeeded, but... )
pointer; // class { destroy: function(){} }
So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.
A manually specified destroy
method could unbind any event listeners. Something like:
function class(){
this.properties = { /**/ }
function handler(){ /**/ }
something.addEventListener( 'event', handler, false );
this.destroy = function(){
something.removeEventListener( 'event', handler );
}
}
I have got a much simpler answer to your question, run the following two commands
sudo docker run -t -d ubuntu --name mycontainername /bin/bash
sudo docker ps -a
the above ps -a command returns a list of all containers. Take the name of the container which references the image name - 'ubuntu' . docker auto generates names for the containers for example - 'lightlyxuyzx'
, that's if you don't use the --name option.
The -t and -d options are important, the created container is detached and can be reattached as given below with the -t option.
With --name option, you can name your container in my case 'mycontainername'.
sudo docker exec -ti mycontainername bash
and this above command helps you login to the container with bash shell. From this point on any changes you make in the container is automatically saved by docker.
For example - apt-get install curl
inside the container
You can exit the container without any issues, docker auto saves the changes.
On the next usage, All you have to do is, run these two commands every time you want to work with this container.
This Below command will start the stopped container:
sudo docker start mycontainername
sudo docker exec -ti mycontainername bash
Another example with ports and a shared space given below:
docker run -t -d --name mycontainername -p 5000:5000 -v ~/PROJECTS/SPACE:/PROJECTSPACE 7efe2989e877 /bin/bash
In my case: 7efe2989e877 - is the imageid of a previous container running which I obtained using
docker ps -a
This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code
$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";
To enable validation for all elements of form use this one
$("form").data("validator").settings.ignore = "";
Note that use them within $(document).ready(function() { })
That what manual says about setOnClickListener
method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.