The way of dknaack does not work for me, I found this solution as well:
@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList,
"Select chapter", new { @onchange = "location = this.value;" })
where
@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)
In the controller you can add:
DbModel db = new DbModel(); //entity model of Entity Framework
ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
You also can use in this form:
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>
On your model class decorate that property with [Required]
attribute. I.e.:
[Required]
public string ShortName {get; set;}
If you have a List of type string that you want in a drop down list I do the following:
EDIT: Clarified, making it a fuller example.
public class ShipDirectory
{
public string ShipDirectoryName { get; set; }
public List<string> ShipNames { get; set; }
}
ShipDirectory myShipDirectory = new ShipDirectory()
{
ShipDirectoryName = "Incomming Vessels",
ShipNames = new List<string>(){"A", "A B"},
}
myShipDirectory.ShipNames.Add("Aunt Bessy");
@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })
Which gives a drop down list like so:
<select id="ShipNames" name="ShipNames" style="width:500px">
<option value="">Select a Ship...</option>
<option>A</option>
<option>A B</option>
<option>Aunt Bessy</option>
</select>
To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):
public ActionResult MyActionName(MyViewModel model)
Access the ShipNames value like so: model.ShipNames
If you just want to access the drop down list on post then the signature becomes:
public ActionResult MyActionName(string ShipNames)
EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.
Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.
If the purpose of the CSS class on the <form/>
element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/>
element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.
You can use System Color (18.2) values, introduced with CSS 2.0, but deprecated in CSS 3.
a:link, a:hover, a:active { color: WindowText; }
That way your anchor links will have the same color as normal document text on this system.
If you want to go all fancy-pants, here's how you can extend it to be able to do this:
@(Html.ActionLink<ArticlesController>(x => x.Details(), article.Title, new { id = article.ArticleID }))
You will need to put this in the System.Web.Mvc
namespace:
public static class MyProjectExtensions
{
public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var link = new TagBuilder("a");
string actionName = ExpressionHelper.GetExpressionText(expression);
string controllerName = typeof(TController).Name.Replace("Controller", "");
link.MergeAttribute("href", urlHelper.Action(actionName, controllerName));
link.SetInnerText(linkText);
return new MvcHtmlString(link.ToString());
}
public static MvcHtmlString ActionLink<TController, TAction>(this HtmlHelper htmlHelper, Expression<Action<TController, TAction>> expression, string linkText, object routeValues)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var link = new TagBuilder("a");
string actionName = ExpressionHelper.GetExpressionText(expression);
string controllerName = typeof(TController).Name.Replace("Controller", "");
link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
link.SetInnerText(linkText);
return new MvcHtmlString(link.ToString());
}
public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> expression, string linkText, object routeValues, object htmlAttributes) where TController : Controller
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);
var attributes = AnonymousObjectToKeyValue(htmlAttributes);
var link = new TagBuilder("a");
string actionName = ExpressionHelper.GetExpressionText(expression);
string controllerName = typeof(TController).Name.Replace("Controller", "");
link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
link.MergeAttributes(attributes, true);
link.SetInnerText(linkText);
return new MvcHtmlString(link.ToString());
}
private static Dictionary<string, object> AnonymousObjectToKeyValue(object anonymousObject)
{
var dictionary = new Dictionary<string, object>();
if (anonymousObject == null) return dictionary;
foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
{
dictionary.Add(propertyDescriptor.Name, propertyDescriptor.GetValue(anonymousObject));
}
return dictionary;
}
}
This includes two overrides for Route Values
and HTML Attributes
, also, all of your views would need to add: @using YourProject.Controllers
or you can add it to your web.config <pages><namespaces>
Yet another solution would be to create a Dictionary<string, object>
before calling TextBoxFor
and pass that dictionary. In the dictionary, add "disabled"
key only if the textbox is to be diabled. Not the neatest solution but simple and straightforward.
Isn't this what default constructors are for?
class MyModel
{
public MyModel()
{
this.ReturnDate = DateTime.Now;
}
public date ReturnDate {get; set;};
}
Improved version of Paulius Zaliaduonis' answer:
In order to make the validation work properly I had to change the Model to:
public class ViewModel
{
public HttpPostedFileBase File { get; set; }
[Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
public string FileName
{
get
{
if (File != null)
return File.FileName;
else
return String.Empty;
}
}
}
and the view to:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.FileName)
}
This is required because what @Serj Sagan wrote about FileExtension attribute working only with strings.
In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197
The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:
Razor code before changes
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
After changes
<!-- New div display-field (after div editor-label) -->
<div class="display-field">
@Html.DisplayFor(model => model.Text)
</div>
<div class="editor-field">
<!-- change to HiddenFor in existing div editor-field -->
@Html.HiddenFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.
This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.
[DisplayName("Name goes here")]
attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.Html.LabelFor
. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"})
Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.
For example, if your data class is MyModel
with a SomekingStatus
property, you could do it like this:
First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:
[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}
All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).
Step 2: add a metatadata class referenced by your new partial class:
public class MyModelMetaData
{
// Apply DisplayNameAttribute (or any other attributes)
[DisplayName("My New Label")]
public string SomekingStatus;
}
[required]
etc) so you may need to duplicate those in the Meta-data class.And to consume the hidden ID input back on your Edit action method:
[HttpPost]
public ActionResult Edit(FormCollection collection)
{
ViewModel.ID = Convert.ToInt32(collection["ID"]);
}
Every method in HtmlHelper class has a twin with For
suffix.
Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this
o=>o.SomeProperty
instead of "SomeProperty" in the case of using Html.Hidden method.
Using @Value
is a hack, because it outputs two attributes, e.g.:
<input type="..." Value="foo" value=""/>
You should do this instead:
@Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")
The @ symbol when specifying HtmlAttributes is used when the "thing" you are trying to set is a keyword c#. So for instance the word class, you cannot specify class, you must use @class.
It is:
<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>
In VB.net you set an anonymous type using
new with {.class = "tab" }
and, as other point out, your third parameter should be an object (could be an anonymous type, also).
JQuery version:
$('yourInputSelectorHere').val("<script>alert('test');<\/script>")
SELECT column_name, data_type, character_maximum_length, table_name,ordinal_position, is_nullable
FROM information_schema.COLUMNS WHERE table_name LIKE 'YOUR_TABLE_NAME'
ORDER BY ordinal_position
With numpy:
In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]
Out[130]: array([1, 4])
or see Alex Szatmary's answer if list_a can be a numpy array but not filter
Numpy usually gives you a big speed boost as well
In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)
In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop
In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop
Subclassing tuple where some of these subclass instances may need to be one-string instances throws up something interesting.
class Sequence( tuple ):
def __init__( self, *args ):
# initialisation...
self.instances = []
def __new__( cls, *args ):
for arg in args:
assert isinstance( arg, unicode ), '# arg %s not unicode' % ( arg, )
if len( args ) == 1:
seq = super( Sequence, cls ).__new__( cls, ( args[ 0 ], ) )
else:
seq = super( Sequence, cls ).__new__( cls, args )
print( '# END new Sequence len %d' % ( len( seq ), ))
return seq
NB as I learnt from this thread, you have to put the comma after args[ 0 ]
.
The print line shows that a single string does not get split up.
NB the comma in the constructor of the subclass now becomes optional :
Sequence( u'silly' )
or
Sequence( u'silly', )
The SET
clause should come after the table specification.
UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
For me it was because I changed the Output Type
of my startup project from Console Application
to Class Library
.
Reverting to Console Application
did the trick.
It's one of the common mistake everybody make while working with jQuery, Basically $ is an alias of jQuery() so when you try to call/access it before declaring the function will endup throwing this error.
Reasons might be
1) Path to jQuery library you included is not correct.
2) Added library after the script were you see that error
To solve this
Load the jquery library beginning of all your javascript files/scripts.
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
Using Linq to xml
Add a reference to System.Xml.Linq
and use
XDocument.Parse(string xmlString)
Edit: Sample follows, xml data (TestConfig.xml)..
<?xml version="1.0"?>
<Tests>
<Test TestId="0001" TestType="CMD">
<Name>Convert number to string</Name>
<CommandLine>Examp1.EXE</CommandLine>
<Input>1</Input>
<Output>One</Output>
</Test>
<Test TestId="0002" TestType="CMD">
<Name>Find succeeding characters</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>abc</Input>
<Output>def</Output>
</Test>
<Test TestId="0003" TestType="GUI">
<Name>Convert multiple numbers to strings</Name>
<CommandLine>Examp2.EXE /Verbose</CommandLine>
<Input>123</Input>
<Output>One Two Three</Output>
</Test>
<Test TestId="0004" TestType="GUI">
<Name>Find correlated key</Name>
<CommandLine>Examp3.EXE</CommandLine>
<Input>a1</Input>
<Output>b1</Output>
</Test>
<Test TestId="0005" TestType="GUI">
<Name>Count characters</Name>
<CommandLine>FinalExamp.EXE</CommandLine>
<Input>This is a test</Input>
<Output>14</Output>
</Test>
<Test TestId="0006" TestType="GUI">
<Name>Another Test</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>Test Input</Input>
<Output>10</Output>
</Test>
</Tests>
C# usage...
XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
from el in root.Elements("Test")
where (string)el.Element("CommandLine") == "Examp2.EXE"
select el;
foreach (XElement el in tests)
Console.WriteLine((string)el.Attribute("TestId"));
This code produces the following output: 0002 0006
I did some mock testing to record the difference between save()
and persist()
.
Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.
For the below example, take EmployeeVehicle as an Entity with PK as vehicleId
which is a generated value and vehicleName
as one of its properties.
Example 1 : Dealing with Transient Object
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = new EmployeeVehicle();
entity.setVehicleName("Honda");
session.save(entity);
// session.persist(entity);
session.getTransaction().commit();
session.close();
Result:
select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)
Note the result is same when you get an already persisted object and save it
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
entity.setVehicleName("Toyota");
session.save(entity); -------> **instead of session.update(entity);**
// session.persist(entity);
Repeat the same using persist(entity)
and will result the same with new Id ( say 37 , honda ) ;
Example 2 : Dealing with Detached Object
// Session 1
// Get the previously saved Vehicle Entity
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached object
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.save(entity);
session2.getTransaction().commit();
session2.close();
Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"
select nextval ('hibernate_sequence')
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)
Using persist to persist detached entity
// (ii) Using Persist() to persist a detached
// Session 1
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.persist(entity);
session2.getTransaction().commit();
session2.close();
Result:
Exception being thrown : detached entity passed to persist
So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with Transient object .
Important Note : In the above example , the pk of vehicle entity is a generated value , so when using save() to persist a detached entity , hibernate generates a new id to persist . However if this pk is not a generated value than it is result in a exception stating key violated.
This is an Oracle doc explaining how to trace SQL queries, including a couple of tools (SQL Trace and tkprof)
$("button").click(function() {
alert(this.id);
});
I was facing the same problem, following code worked for me:
$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);
If it is for binding, then you can reference indexers from XAML
Text="{Binding [FullName]}"
Here it is referencing the class indexer with the key "FullName"
After reading the documentation of VideoCapture
. I figured out that you can tell VideoCapture
, which frame to process next time we call VideoCapture.read()
(or VideoCapture.grab()
).
The problem is that when you want to read()
a frame which is not ready, the VideoCapture
object stuck on that frame and never proceed. So you have to force it to start again from the previous frame.
Here is the code
import cv2
cap = cv2.VideoCapture("./out.mp4")
while not cap.isOpened():
cap = cv2.VideoCapture("./out.mp4")
cv2.waitKey(1000)
print "Wait for the header"
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
while True:
flag, frame = cap.read()
if flag:
# The frame is ready and already captured
cv2.imshow('video', frame)
pos_frame = cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES)
print str(pos_frame)+" frames"
else:
# The next frame is not ready, so we try to read it again
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, pos_frame-1)
print "frame is not ready"
# It is better to wait for a while for the next frame to be ready
cv2.waitKey(1000)
if cv2.waitKey(10) == 27:
break
if cap.get(cv2.cv.CV_CAP_PROP_POS_FRAMES) == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
# If the number of captured frames is equal to the total number of frames,
# we stop
break
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
Here is an answer that works with data.table and is simpler. This assumes your data.table is named yourDF
:
j1 <- max.col(yourDF[, .(V1, V2, V3, V4)], "first")
yourDF$newCol <- c("V1", "V2", "V3", "V4")[j1]
Replace ("V1", "V2", "V3", "V4")
and (V1, V2, V3, V4)
with your column names
select * from [tbl] where [link] is not null and len([link]) > 1
For MySQL user:
LENGTH([link]) > 1
Deleting the Genymotion cached .ova file, deleting the corrupted deployed image, redownloading the image, and reinstalling it addressed the issue for me.
Note that the deployed images are under: ~/.Genymobile/Genymotion/deployed
the cached ova files are under: ~/.Genymobile/Genymotion/ova
You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.
Add on info to get query parameters.
const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');
For more info about URLSearchParams check this link URLSearchParams
Because getTitle
is not a string
, it returns a reference or delegate
to a method (if you like), if you don't explicitly call the method.
Call your method this way:
string t= obj.getTitle() ; //obj.getTitle() says return the title string object
However, this would work:
Func<string> method = obj.getTitle; // this compiles to a delegate and points to the method
string s = method();//call the delegate or using this syntax `method.Invoke();`
You can't declare a variable as Decimal
- you have to use Variant
(you can use CDec
to populate it with a Decimal
type though).
This is to help others completely new to react and who area having problems just starting a first app even though they did a fresh install and try using npm install and the other fixes I saw around the forums.
Running it on Windows 10 with all the latest npm create-react-app installed and got failure after failure on a simple npm start in a simple my-app demo folder.
Spent a long time with what looks similar to the OP error at first but is slightly different. This starts with ERRNO 4058 and continues with code 'ENOENT' syscall: 'spawn cmd', path: ''cmd' ...
Eventually worked out from github create-react-app forum that a quick fix for this is registering cmd in the "path" variable. To do this go to System Properties>Environment variables. Click on path variable edit and and add new entry of C:\Windows\System32. Restart CMD prompt and I was good to go.
I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.
protected void Page_Load(object sender, EventArgs e)
Calendar1.SelectedDate = DateTime.Today;
}
the previous code did NOT highlight the selection, although it set the SelectedDate to today.
However, to select and highlight the following code will work properly.
protected void Page_Load(object sender, EventArgs e)
{
DateTime today = DateTime.Today;
Calendar1.TodaysDate = today;
Calendar1.SelectedDate = Calendar1.TodaysDate;
}
check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx
Were you expecting player
to be a dict
rather than a list
?
>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']
1
Try:
<?php
phpinfo();
?>
Run the page and search for mysql
. If not found, run the following in the shell and restart the Apache server:
sudo apt-get install mysql-server mysql-client php5-mysql
Also make sure you have all the following lines uncommented somewhere in your apache2.conf (or in your conf.d/php.ini) file, from
;extension=php_mysql.so
to
extension=php_mysql.so
If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.
// this function just get the public url of zip file.
let url = await getStorageUrl(path)
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
console.log('zip download status ', res.status)
//load contents into jszip and create an object
jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
const zipObj = zip
$.each(zip.files, function (index, zipEntry) {
console.log('filename', zipEntry.name)
})
})
Now using the zipObj you can access the files and create a src url for it.
var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)
For Swift 3 & Swift 4 :
Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3
let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
//Do whatever you want here
})
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
Deprecated :
This is the swift version inspired by the checked response :
Display AlertView :
let alert = UIAlertView(title: "No network connection",
message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
alert.delegate = self
alert.show()
Add the delegate to your view controller :
class AgendaViewController: UIViewController, UIAlertViewDelegate
When user click on button, this code will be executed :
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
}
I can programmatically log user out Facebook by redirecting user to
https://www.facebook.com/logout.php?next=YOUR_REDIRECT_URL&access_token=USER_ACCESS_TOKEN
The URL supplied in the next parameter must be a URL with the same base domain as your application as defined in your app's settings.
More details: https://developers.facebook.com/docs/authentication
Many popular Java webapps, including Jenkins and Nexus, use this mechanism:
Optionally, check a servlet context-param / init-param. This allows configuring multiple webapp instances per servlet container, using context.xml
which can be done by modifying the WAR or by changing server settings (in case of Tomcat).
Check an environment variable (using System.getenv), if it is set, then use that folder as your application data folder. e.g. Jenkins uses JENKINS_HOME
and Nexus uses PLEXUS_NEXUS_WORK
. This allows flexible configuration without any changes to WAR.
Otherwise, use a subfolder inside user's home folder, e.g. $HOME/.yourapp
. In Java code this will be:
final File appFolder = new File(System.getProperty("user.home"), ".yourapp");
Do you mean like this
int index = 2;
string s = "hello";
Console.WriteLine(s[index]);
string also implements IEnumberable<char>
so you can also enumerate it like this
foreach (char c in s)
Console.WriteLine(c);
cat * | grep -c string
I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up. As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.
If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).
from itertools import tee, izip, chain
def pairwise(seq):
a,b = tee(seq)
b.next()
return izip(a,b)
for current_item, next_item in pairwise(y):
if compare(current_item, next_item):
# do what you have to do
If you need to compare the last value to some special value, chain that value to the end
for current, next_item in pairwise(chain(y, [None])):
If you guys are looking for a solution for Android, you can use the following code to get the epoch seconds from the timestamp string.
public static long timestampToEpochSeconds(String srcTimestamp) {
long epoch = 0;
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Instant instant = Instant.parse(srcTimestamp);
epoch = instant.getEpochSecond();
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSSSS'Z'", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse(srcTimestamp);
if (date != null) {
epoch = date.getTime() / 1000;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return epoch;
}
Sample input: 2019-10-15T05:51:31.537979Z
Sample output: 1571128673
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
First run:
find . -type f -name "*.py[c|o]" -exec rm -f {} +
Then add:
export PYTHONDONTWRITEBYTECODE=1
To ~/.profile
For Images use
@Url.Content("~/assets/bg4.jpg")
on a Style use this
style="background-image:url(@Url.Content("~/assets/bg4.jpg"))
Instead of using substring with a fixed index, you'd better use replace
:
$("#date").html(function(t){
return t.replace(/^([^\/]*\/)/, '<span>$1</span><br>')
});
One advantage is that it would still work if the first /
is at a different position.
Another advantage of this construct is that it would be extensible to more than one elements, for example to all those implementing a class, just by changing the selector.
Demonstration (note that I had to select jQuery in the menu in the left part of jsfiddle's window)
devnull is right;
sudo update-alternatives --config x-terminal-emulator
DataTable
's Select
method only supports simple filtering expressions like {field} = {value}
. It does not support complex expressions, let alone SQL/Linq statements.
You can, however, use Linq extension methods to extract a collection of DataRow
s then create a new DataTable
.
dt = dt.AsEnumerable()
.GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
.Select(g => g.OrderBy(r => r["PK"]).First())
.CopyToDataTable();
For me it only worked when I added the following code:
.change();
For me it only worked when I added the following code: As I wanted to "reset" the form, that is, select all the first options of all the selects of the form, I used the following code:
$('form').find('select').each(function(){
$(this).val($("select option:first").val());
$(this).change();
});
Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:
if(check if your conditions are not satisfying)
{
event.preventDefault();
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
Thanks to Hemant and Vikram for putting me on the right track.
I don't think using "points" for font-size on a screen is a good idea. Try using px or em on font-size.
From W3C:
Do not specify the font-size in pt, or other absolute length units. They render inconsistently across platforms and can't be resized by the User Agent (e.g browser).
In Firebug in Firefox, you can right click on an element after inspecting it, and choose Copy XPath. I could not get ChromYQLip to work smoothly.
When using bootstrap 4 or 5, flexbox could be used to achieve desired effect:
<body class="d-flex flex-column min-vh-100">
<header>HEADER</header>
<content>CONTENT</content>
<footer class="mt-auto"></footer>
</body>
Please check the examples: Bootstrap 4 Bootstrap 5
In bootstrap 3 and without use of bootstrap. The simplest and cross browser solution for this problem is to set a minimal height for body
object. And then set absolute
position for the footer with bottom: 0
rule.
body {
min-height: 100vh;
position: relative;
margin: 0;
padding-bottom: 100px; //height of the footer
box-sizing: border-box;
}
footer {
position: absolute;
bottom: 0;
height: 100px;
}
Please check this example: Bootstrap 3
I have a Windows 7 client on a Mac host and this post was VERY helpful. Thanks.
I would add that I didn't use gparted. I did this:
Sweet! I preferred that to using a 3rd party tool with warnings about data loss.
Cheers!
you can also use:
pip install package==0.5.*
which is more consistent and easy to read.
<input type="text" autocomplete="off"/>
Should work. Alternatively, use:
<form autocomplete="off" … >
for the entire form (see this related question).
I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.
Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.
Change the text by altering the text in the element directly. (does not update the tooltip position).
$('.tooltip-inner', $element.next()).html(newHtml);
$('.tooltip-inner', $element.next()).text(newText);
Change the text by destroying the old tooltip, then creating and showing a new one. (Causes the old one to fade out and the new one to fade in)
$element
.tooltip('destroy')
.tooltip({
// Repeat previous options.
title: newText,
})
.tooltip('show');
I'm using the top method to both animate the "Saving." message (using  
so the tooltip does not change in size) and to change the text to "Done." (plus padding) when the request completes.
$element.tooltip({
placement: 'left',
title: 'Saving...',
trigger: 'manual',
}).tooltip('show');
var parent = $element.parent();
var interval_id = setInterval(function(){
var text = $('.tooltip-inner', parent).html();
switch(text) {
case 'Saving. ': text = 'Saving.. '; break;
case 'Saving.. ': text = 'Saving...'; break;
case 'Saving...': text = 'Saving. '; break;
}
$('.tooltip-inner', parent).html(text);
}, 250);
send_request( function(){
// When the request is complete
clearInterval(interval_id);
$('.tooltip-inner', parent).html('Done. ');
setTimeout(function() {
$element.tooltip('hide');
}, 1500 /* Show "Done." for a bit */);
});
data.userID = "10";
DateTime.remove({}, callback)
The empty object will match all of them.
Here's a snippet which I wrote which performs the same functionality.
This code is similar to the one written by Kunal Wadhwa.
char *dynamicCharString()
{
char *str, c;
int i;
str = (char*)malloc(1*sizeof(char));
while(c = getc(stdin),c!='\n')
{
str[i] = c;
i++;
realloc(str,i*sizeof(char));
}
str[i] = '\0';
return str;
}
You can to this in Twig or the FormClass as shown in the examples above. But you might want to decide in the controller which class your form should get. Just keep in mind to not have much logic in the controller in general!
$form = $this->createForm(ContactForm::class, null, [
'attr' => [
'class' => 'my_contact_form'
]
]);
In jquery, u can delcare variable two styles.
One is,
$.name = 'anirudha';
alert($.name);
Second is,
var hText = $("#head1").text();
Second is used when you read data from textbox
, label
, etc.
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
In the VBA editor, go to View
, Toolbars
, Customise...
or right click on the tool bar and select Customise...
Under the Commands
tab, select the Edit
menu on the left.
Then approximately two thirds of the way down there's two icons, Comment Block
and Uncomment Block
.
Drag and drop these onto your toolbar and then you have easy access to highlight a block of code, and comment it out and uncomment with the click of a button!
See GauravSingh's answer if you want to assign keyboard shortcuts.
$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
while($value=mysql_fetch_array($duplicate_query)
{
if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
{
echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
$res=mysql_query($query);
if($query)
{
echo "Success";
}
else
{
echo "Error";
}
else
{
echo "Duplicate Entry";
}
}
}
}
else
{
echo "Records Already Exixts";
}
next((x for x in test_list if x.value == value), None)
This gets the first item from the list that matches the condition, and returns None
if no item matches. It's my preferred single-expression form.
However,
for x in test_list:
if x.value == value:
print("i found it!")
break
The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:
for x in test_list:
if x.value == value:
print("i found it!")
break
else:
x = None
This will assign None
to x
if you don't break
out of the loop.
This answer is for visual studio 2017 and if you want to read from text file which location is relative to your compiled console application.
first put your textfile (test.txt in this case) into your solution folder. After compiling keep text file in same folder with applicationName.exe
C:\Users\"username"\source\repos\"solutionName"\"solutionName"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
// open the file stream
inFile.open(".\\test.txt");
// check if opening a file failed
if (inFile.fail()) {
cerr << "Error opeing a file" << endl;
inFile.close();
exit(1);
}
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
// close the file stream
inFile.close();
}
In order to create a .jar file, you need to use jar
instead of java
:
jar cf myJar.jar myClass.class
Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)
) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class
header (e.g., Main-Class: myClass
).
However, as Mark Peters pointed out, with JDK 6, you can use the e
option to define the entry point:
jar cfe myJar.jar myClass myClass.class
Finally, you can execute it:
java -jar myJar.jar
We have to make sure the type= file with name attribute should be same as the parameter name passed in
upload.single('attr')
var multer = require('multer');
var upload = multer({ dest: 'upload/'});
var fs = require('fs');
/** Permissible loading a single file,
the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('recfile');
app.post('/upload', type, function (req,res) {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
/** The original name of the uploaded file
stored in the variable "originalname". **/
var target_path = 'uploads/' + req.file.originalname;
/** A better way to copy the uploaded file. **/
var src = fs.createReadStream(tmp_path);
var dest = fs.createWriteStream(target_path);
src.pipe(dest);
src.on('end', function() { res.render('complete'); });
src.on('error', function(err) { res.render('error'); });
});
You can use serializeArray
[docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
There's no one answer. The standard defines minimum ranges. An int must be able to hold at least 65535. Most modern compilers however allow ints to be 32-bit values. Additionally, there's nothing preventing multiple types from having the same capacity (e.g. int and long).
That being said, the standard does say in your particular case:
0 ? +18446744073709551615
as the range for unsigned long long int.
Further reading: http://en.wikipedia.org/wiki/C_variable_types_and_declarations#Size
git reset HEAD <file1> <file2> ...
remove the specified files from the next commit
I had this same error. Just had to install IIS and everything worked.
brew reinstall openssl
It automatically updates mysql server compatible with openssl. I tried many things, but only this worked for me.
My solution to this is pretty unbelievable.
<script type="text/javascript" src="/js/dataLayer.js?v=1"></script>
The filename in the src attribute needed to be lowercase:
<script type="text/javascript" src="/js/datalayer.js?v=1"></script>
and that somewhat inexplicably fixed the problem.
In both cases the reference was returning 404 for testing.
It is really easy with Google Maps Android API v2
Just copy the example from Developer documentation
(of course you have to init your map first)
GoogleMap map;
// ... get a map.
// Add a thin red line from London to New York.
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
use Firebase.getAuth()
. It returns the current state of the Firebase client. Otherwise the return value is null
Here are the docs: https://www.firebase.com/docs/web/api/firebase/getauth.html
Just replace "UTC" with "GMT" -- simple and doesn't break correctly formatted dates:
DateTime.Parse("Tue, 1 Jan 2008 00:00:00 UTC".Replace("UTC", "GMT"))
getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:
class ParentClass{
}
public class SubClass extends ParentClass{
public static void main(String []args){
ParentClass parentClassInstance = new ParentClass();
SubClass subClassInstance = new SubClass();
if(subClassInstance instanceof ParentClass){
System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
}
if(subClassInstance.getClass() != parentClassInstance.getClass()){
System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
}
}
}
Outputs:
SubClass extends ParentClass. subClassInstance is instanceof ParentClass.
Different getClass() return results with subClassInstance and parentClassInstance.
The values you provided are UTF-8 values. When set, the array of:
declare -a ARR=(0xA7 0x9B 0x46 0x8D 0x1E 0x52 0xA7 0x9B 0x7B 0x31 0xD2)
Will be parsed to print the plaintext characters of each value.
for ((n=0; n < ${#ARR[*]}; n++)); do echo -e "\u${ARR[$n]//0x/}"; done
And the output will yield a few printable characters and some non-printable characters as shown here:
For converting hex values to plaintext using the echo
command:
echo -e "\x<hex value here>"
And for converting UTF-8 values to plaintext using the echo
command:
echo -e "\u<UTF-8 value here>"
And then for converting octal to plaintext using the echo
command:
echo -e "\0<octal value here>"
When you have encoding values you aren't familiar with, take the time to check out the ranges in the common encoding schemes to determine what encoding a value belongs to. Then conversion from there is a snap.
A workaround (until Google fix this bug) is to use an EditText
with android:inputType="numberDecimal"
and android:digits="0123456789.,"
.
Then add a TextChangedListener to the EditText with the following afterTextChanged:
public void afterTextChanged(Editable s) {
double doubleValue = 0;
if (s != null) {
try {
doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
} catch (NumberFormatException e) {
//Error
}
}
//Do something with doubleValue
}
You can use int
and set the base to 2
(for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int
like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>
Run export DOCKER_CONTENT_TRUST=0
and then try it again.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Make sure that you set position explicitly as absolute or relative for z-index to work for selection. I had a similar issue and this solved it for me.
Another approach could be to assume that your base image gets behind quite quickly (and that's very likely to happen), and force another image build of your application periodically (e.g. every week) and then re-deploy it if it has changed.
As far as I can tell, popular base images like the official Debian or Java update their tags to cater for security fixes, so tags are not immutable (if you want a stronger guarantee of that you need to use the reference [image:@digest], available in more recent Docker versions). Therefore, if you were to build your image with docker build --pull
, then your application should get the latest and greatest of the base image tag you're referencing.
Since mutable tags can be confusing, it's best to increment the version number of your application every time you do this so that at least on your side things are cleaner.
So I'm not sure that the script suggested in one of the previous answers does the job, since it doesn't rebuild you application's image - it just updates the base image tag and then it restarts the container, but the new container still references the old base image hash.
I wouldn't advocate for running cron-type jobs in containers (or any other processes, unless really necessary) as this goes against the mantra of running only one process per container (there are various arguments about why this is better, so I'm not going to go into it here).
You can definetely build your code from Vim, that's what the :make
command does.
However, you need to go through the basics first : type vimtutor
in your terminal and follow the instructions to the end.
After you have completed it a few times, open an existing (non-important) text file and try out all the things you learned from vimtutor
: entering/leaving insert mode, undoing changes, quitting/saving, yanking/putting, moving and so on.
For a while you won't be productive at all with Vim and will probably be tempted to go back to your previous IDE/editor. Do that, but keep up with Vim a little bit every day. You'll probably be stopped by very weird and unexpected things but it will happen less and less.
In a few months you'll find yourself hitting o
, v
and i
all the time in every textfield everywhere.
Have fun!
In one controller, you can do:
$rootScope.$broadcast('eventName', data);
and listen to the event in another:
$scope.$on('eventName', function (event, data) {...});
I don't want to start a "What's the best unix command line under Windows" war, but have you thought of Cygwin? Git is in the Cygwin package repository.
And you get a lot of beneficial side-effects! (:-)
1) When the user logs out (Forms signout in Action) I want to redirect to a login page.
public ActionResult Logout() {
//log out the user
return RedirectToAction("Login");
}
2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)
Why would you want to redirect from a controller init?
the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:
public ActionResult Index() {
return RedirectToAction("whateverAction", "whateverController");
}
if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.
ng new ng-app-name --skip-tests
I little sophisticated way:
$(selector).is(condition)? alert('true') : alert('false');
Ex:
$("#btn-primary").is(":disabled")? alert('button disabled') : alert('button disabled');
In C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.
For example, if you have a string class with constructor String(const char* s)
, that's probably exactly what you want. You can pass a const char*
to a function expecting a String
, and the compiler will automatically construct a temporary String
object for you.
On the other hand, if you have a buffer class whose constructor Buffer(int size)
takes the size of the buffer in bytes, you probably don't want the compiler to quietly turn int
s into Buffer
s. To prevent that, you declare the constructor with the explicit
keyword:
class Buffer { explicit Buffer(int size); ... }
That way,
void useBuffer(Buffer& buf);
useBuffer(4);
becomes a compile-time error. If you want to pass a temporary Buffer
object, you have to do so explicitly:
useBuffer(Buffer(4));
In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the explicit
keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as explicit
to prevent the compiler from surprising you with unexpected conversions.
To execute your program from the command line, you have to call the python interpreter, like this :
C:\Python27>python hello.py 1 1
If you code resides in another directory, you will have to set the python binary path in your PATH environment variable, to be able to run it, too. You can find detailed instructions here.
#i'm also maintaining insertion order here
Map<Integer,ArrayList> d=new LinkedHashMap<>();
for( int i=0; i<2; i++)
{
int id=s.nextInt();
ArrayList al=new ArrayList<>();
al.add(s.next()); //name
al.add(s.next()); //category
al.add(s.nextInt()); //fee
d.put(id, al);
}
This works for me using JsonConvert
var result = JsonConvert.DeserializeObject<Class>(responseString);
import os
def get_mount_point(pathname):
"Get the mount point of the filesystem containing pathname"
pathname= os.path.normcase(os.path.realpath(pathname))
parent_device= path_device= os.stat(pathname).st_dev
while parent_device == path_device:
mount_point= pathname
pathname= os.path.dirname(pathname)
if pathname == mount_point: break
parent_device= os.stat(pathname).st_dev
return mount_point
def get_mounted_device(pathname):
"Get the device mounted at pathname"
# uses "/proc/mounts"
pathname= os.path.normcase(pathname) # might be unnecessary here
try:
with open("/proc/mounts", "r") as ifp:
for line in ifp:
fields= line.rstrip('\n').split()
# note that line above assumes that
# no mount points contain whitespace
if fields[1] == pathname:
return fields[0]
except EnvironmentError:
pass
return None # explicit
def get_fs_freespace(pathname):
"Get the free space of the filesystem containing pathname"
stat= os.statvfs(pathname)
# use f_bfree for superuser, or f_bavail if filesystem
# has reserved space for superuser
return stat.f_bfree*stat.f_bsize
Some sample pathnames on my computer:
path 'trash':
mp /home /dev/sda4
free 6413754368
path 'smov':
mp /mnt/S /dev/sde
free 86761562112
path '/usr/local/lib':
mp / rootfs
free 2184364032
path '/proc/self/cmdline':
mp /proc proc
free 0
if on Python =3.3, there's shutil.disk_usage(path)
which returns a named tuple of (total, used, free)
expressed in bytes.
Active mode: -server initiates the connection.
Passive mode: -client initiates the connection.
You can get the parameters you are asking for by typing:
dir /?
For the full list, try:
dir /s /b /a:d
It has a tricky situation: If you submit a post form, then Chrome will open a new tab to send the request. It's right until now, but if it triggers an event to download file(s), this tab will close immediately so that you cannot capture this request in the Dev Tool.
Solution: Before submitting the post form, you need to cut off your network, which makes the request cannot send successfully so that the tab will not be closed. And then you can capture the request message in the Chrome Devtool(Refreshing the new tab if necessary)
I managed to do it with CSS display: table-*
. I haven't tested with more than 3 blocks though.
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
To obtain the perspective-corrected co-ordinates, just divide by the z
co-ordinate:
xc = x / z
yc = y / z
The above works assuming that the camera is at (0, 0, 0)
and you are projecting onto the plane at z = 1
-- you need to translate the co-ords relative to the camera otherwise.
There are some complications for curves, insofar as projecting the points of a 3D Bezier curve will not in general give you the same points as drawing a 2D Bezier curve through the projected points.
The first line of your subclass' constructor must be a call to super()
to ensure that the constructor of the superclass is called.
In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :
${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}
Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):
${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}
And of course, the much useful expansions that operate on whether the parameter is null:
${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}
They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution)
combined with sed or any other external filter). But, they are so easily found by typing man bash
that I don't feel it merits to further extend this post.
Yes, a constructor can be private. There are different uses of this. One such use is for the singleton design anti-pattern, which I would advise against you using. Another, more legitimate use, is in delegating constructors; you can have one constructor that takes lots of different options that is really an implementation detail, so you make it private, but then your remaining constructors delegate to it.
As an example of delegating constructors, the following class allows you to save a value and a type, but it only lets you do it for a subset of types, so making the general constructor private is needed to ensure that only the permitted types are used. The common private constructor helps code reuse.
public class MyClass {
private final String value;
private final String type;
public MyClass(int x){
this(Integer.toString(x), "int");
}
public MyClass(boolean x){
this(Boolean.toString(x), "boolean");
}
public String toString(){
return value;
}
public String getType(){
return type;
}
private MyClass(String value, String type){
this.value = value;
this.type = type;
}
}
Edit
Looking at this answer from several years later, I would like to note that this answer is both incomplete and also a little bit extreme. Singletons are indeed an anti-pattern and should generally be avoided where possible; however, there are many uses of private constructors besides singletons, and my answer names only one.
To give a couple more cases where private constructors are used:
To create an uninstantiable class that is just a collection of related static functions (this is basically a singleton, but if it is stateless and the static functions operate strictly on the parameters rather than on class state, this is not as unreasonable an approach as my earlier self would seem to suggest, though using an interface that is dependency injected often makes it easier to maintain the API when the implementation requires larger numbers of dependencies or other forms of context).
When there are multiple different ways to create the object, a private constructor may make it easier to understand the different ways of constructing it (e.g., which is more readable to you new ArrayList(5)
or ArrayList.createWithCapacity(5)
, ArrayList.createWithContents(5)
, ArrayList.createWithInitialSize(5)
). In other words, a private constructor allows you to provide factory function's whose names are more understandable, and then making the constructor private ensures that people use only the more self-evident names. This is also commonly used with the builder pattern. For example:
MyClass myVar = MyClass
.newBuilder()
.setOption1(option1)
.setOption2(option2)
.build();
@jim mcnamara: try using parentheses for around NF
, i. e. $(NF-1)
and $(NF)
instead of $NF-1
and $NF
(works on Mac OS X 10.6.8 for FreeBSD awk
and gawk
).
echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'
# output:
# 1 2
# 2 3
# two three
From Ubuntu command line:
//WeatherArray.java
public class WeatherArray {
public static void main(String[] args) {
System.out.println("....Hello World");
}}
ls
WeatherArray.java
javac WeatherArray.java
ls
WeatherArray.java WeatherArray.class
java WeatherArray
....Hello World
Of course if you name your java file with different name than WeatherArray, you need to take out public and it would be:
// Sunny.java
class WeatherArray {
public static void main(String[] args) {
System.out.println("....Hello World"); }}
// javac Sunny.java; java WeatherArray
You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
For me below solution worked.
Jenkins --> Manage Jenkins --> Manage Nodes --> master -> configure --> Node properties --> Restrict Jobs execution at node - is enabled and given access to specific users. I have given access myself and then job started to run.
If Restrict Jobs execution at node is enabled scheduled tasks cannot run.
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
ImageBackground might have limit
Actually, you can use directly and it is not deprecated.
If you want to add Background Image in React Native and also wants to add other elements on that Background Image, follow the step below:
- Create a Container View
- Create an Image element with 100% width and height. Also resizeMode: 'Cover'
- Create another View element under Image element with position: 'absolute'
This is the code I use:
import React, { Component } from 'react';
import {Text, View, Image} from 'react-native';
import Screen from '../library/ScreenSize'
export default class MenuScreen extends Component {
static navigationOptions = {
header: null
}
render() {
return (
<View style={{ flex: 1 }}>
<Image
style={{
resizeMode: "cover",
width: "100%",
height: "100%",
justifyContent: "center",
alignItems: "center",
opacity: 0.4
}}
source={require("../assets/images/menuBackgroundImage.jpg")}
></Image>
<View style={{
width: Screen.width,
height: Screen.height * 0.55,
position: 'absolute',
bottom: 0}}>
<Text style={{
fontSize: 48
}}>Glad to Meet You!</Text>
</View>
</View>
);
}
}
Enjoy Coding....
Output:
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).Use a regex such as [^0-9]
to remove all non-digits.
From there, just use Integer.parseInt(String);
You can also use this node module called js-xlsx
1) Install module
npm install xlsx
2) Import module + code snippet
var XLSX = require('xlsx')
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);
Use this line to make this work while using the modal:true option.
open: function (type, data) {
$('.ui-widget-overlay').appendTo("form"); $(this).parent().appendTo("form");
},
USE master
GO
xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc'
GO
[Identify Port used by Named Instance of SQL Server Database Engine by Reading SQL Server Error Logs]
This work for me
<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>
You should use a ImageButton and specify the image in android:src
, and set android:scaletype
to fitXY
Drawable drawable = getResources().getDrawable(R.drawable.s_vit);
drawable.setBounds(0, 0, (int)(drawable.getIntrinsicWidth()*0.5),
(int)(drawable.getIntrinsicHeight()*0.5));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, scaleWidth, scaleHeight);
Button btn = findViewbyId(R.id.yourbtnID);
btn.setCompoundDrawables(sd.getDrawable(), null, null, null); //set drawableLeft for example
To avoid this - one can use the GUI for entering permissions. Eclipse take care of where to insert the permission tag and more often then not is correct
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.
To delete only cookies:
Another neat option is to use the Directive
as an element and not as an attribute.
@Directive({
selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {
@Input()
public first: string;
@Input()
public second: string;
ngAfterViewInit(): void {
console.log(`Values: ${this.first}, ${this.second}`);
}
}
And this directive can be used like that:
<app-someKindOfComponent>
<app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
<app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
<app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`
Simple, neat and powerful.
Because python's math library is a thin wrapper around the C math library which returns floats.
>>> Array.apply(null, Array(10)).map(function(){return 5})
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
>>> //Or in ES6
>>> [...Array(10)].map((_, i) => 5)
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
getElementById("id").removeAttribute("style");
if you are using jQuery then
$("#id").removeClass("classname");
If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.
$list= (new LeaveApplication())
->whereDate('from','<=', $today)
->whereDate('to','>=', $today)
->get();
That is not an nginx
configuration file. It is part of an nginx
configuration file.
The nginx
configuration file (usually called nginx.conf
) will look like:
events {
...
}
http {
...
server {
...
}
}
The server
block is enclosed within an http
block.
Often the configuration is distributed across multiple files, by using the include
directives to pull in additional fragments (for example from the sites-enabled
directory).
Use sudo nginx -t
to test the complete configuration file, which starts at nginx.conf
and pulls in additional fragments using the include
directive. See this document for more.
use jQuery.noConflict()
var j = jQuery.noConflict();
j(document).ready(function(){
j('#datetimepicker').datepicker();
})
What is the best approach to do this JAVA?
I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:
The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.
I read about SAAJ, looks like that will be more granular level of approach?
To do what?
Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?
Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport
.
Can someone send the links for some good tutorials on these topics?
That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:
What are the options we need to use while generating the code using the WSDL2Java?
No options, use wsimport
:)
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject
, and AssignObject
. When the compiler sees thing = value
, it looks at the context and calls one InitializeObject
if you're making a new thing
. If you're not, it instead calls AssignObject
.
Normally this is fine as InitializeObject
and AssignObject
usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.
AFNetworking provides async image loading into a UIImageView with placeholder support. It also supports async networking for working with APIs in general.
I simple used Eval(string)
and it evaluated as Double.
This thread is misleading. Tried commenting on Lucas Ramadan's answer, but I don't have the right privileges yet, so I'll just put this here.
Batch normalization works best after the activation function, and here or here is why: it was developed to prevent internal covariate shift. Internal covariate shift occurs when the distribution of the activations of a layer shifts significantly throughout training. Batch normalization is used so that the distribution of the inputs (and these inputs are literally the result of an activation function) to a specific layer doesn't change over time due to parameter updates from each batch (or at least, allows it to change in an advantageous way). It uses batch statistics to do the normalizing, and then uses the batch normalization parameters (gamma and beta in the original paper) "to make sure that the transformation inserted in the network can represent the identity transform" (quote from original paper). But the point is that we're trying to normalize the inputs to a layer, so it should always go immediately before the next layer in the network. Whether or not that's after an activation function is dependent on the architecture in question.
jQuery Mobile has a datepicker too. Source
Just include the following files,
<script src="jQuery.ui.datepicker.js"></script>
<script src="jquery.ui.datepicker.mobile.js"></script>
Although Visual Studio does not support this (you can do some tricks and get MSBuild to compile both, but not from within Visual Studio), SharpDevelop does. You can have both in the same solution (as long as you are running Visual Studio Professional and above), so the easiest solution if you want to keep using Visual Studio is to seperate your VB code into a different project and access it that way.
<div class="row">
<div class="col-4 alert alert-primary">
1
</div>
<div class="col-8">
<div class="row">
<div class="col-6 alert alert-primary">
2
</div>
<div class="col-6 alert alert-primary">
3
</div>
<div class="col-6 alert alert-primary">
4
</div>
<div class="col-6 alert alert-primary">
5
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-4 alert alert-primary">
6
</div>
<div class="col-4 alert alert-primary">
7
</div>
<div class="col-4 alert alert-primary">
8
</div>
</div>
After 7 years... the facelets solution still works fine for me as a jsf user
include the namespace as
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
and use the EL as
#{fn:length(myBean.someList)}
for example if using in jsf ui:fragment below example works fine
<ui:fragment rendered="#{fn:length(myBean.someList) gt 0}">
<!-- Do something here-->
</ui:fragment>
If all your values are unique, you can make a reverse dictionary:
PIXO_reverse = {v: k for k, v in PIX0.items()}
Result:
>>> PIXO_reverse
{'320x240': 'QVGA', '640x480': 'VGA', '800x600': 'SVGA'}
Now you can use the same logic as before.
Server version: 8.0.19 Homebrew. macOS Catalina 10.15.5 and installed MySQL via Homebrew. Found this file here:
/usr/local/etc/my.cnf
This solution helped :)
@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):
Option Explicit
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
I use this code (I use Python 3):
import csv
import io
import requests
url = "http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv"
r = requests.get(url)
r.encoding = 'utf-8' # useful if encoding is not sent (or not sent properly) by the server
csvio = io.StringIO(r.text, newline="")
data = []
for row in csv.DictReader(csvio):
data.append(row)
Simply use JSON.stringify(your_variableName) it will convert your JSON object to string and if you want to convert string to object use JSON.parse(your_variableName)
Without any additional packages:
true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)
getROC_AUC = function(probs, true_Y){
probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
val = unlist(probsSort$x)
idx = unlist(probsSort$ix)
roc_y = true_Y[idx];
stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)
auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}
aList = getROC_AUC(probs, true_Y)
stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)
plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")
(typeof SOMETHING) !== 'undefined'
It's too long to write when used. But we can't package the typeof
keyword into a function, because an error will thrown before the function is called, like this:
function isdef($var) {
return (typeof $var) !== 'undefined';
}
isdef(SOMETHING); ///// thrown error: SOMETHING is not defined
So I figured out a way:
function isdef($type) {
return $type !== 'undefined';
}
isdef(typeof SOMETHING);
It can work both with individual variables (variables that does not exist at all), or object properties (non-existent properties). And only 7 more characters than PHP isset
.
I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!
package your.package.name;
/**
* Utility class that removes chars from a String.
*
*/
public class RemoveChars {
public static String remove(String string, String remove) {
return new String(remove(string.toCharArray(), remove.toCharArray()));
}
public static char[] remove(final char[] chars, char[] remove) {
int count = 0;
char[] buffer = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
boolean include = true;
for (int j = 0; j < remove.length; j++) {
if ((chars[i] == remove[j])) {
include = false;
break;
}
}
if (include) {
buffer[count++] = chars[i];
}
}
char[] output = new char[count];
System.arraycopy(buffer, 0, output, 0, count);
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String remove = "AEIOU";
System.out.println();
System.out.println("Remove AEIOU: " + string);
System.out.println("Result: " + RemoveChars.remove(string, remove));
}
}
This is the output:
Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result: TH QCK BRWN FX JMPS VR TH LZY DG
Martin R answer is the best approach, and as he said, because String conforms the SquenceType protocol, you can also enumerate a string, getting each character on each iteration.
let characters = "Hello"
var charactersArray: [Character] = []
for (index, character) in enumerate(characters) {
//do something with the character at index
charactersArray.append(character)
}
println(charactersArray)
It happen the same thing to me. See on Gradle -> Build Gradle -> and make sure that the compatibility matches in both compile "app compat" and "support design" lines, they should have the same version.
Then to be super sure, that it will launch with no problem, go to File -> Project Structure ->app and check on tab propertie the build Tools version, it should be the same as your support compile line, just in case i put the target SDK version as 25 as well on the tab Flavors.
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-
core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
*compile 'com.android.support:appcompat-v7:25.3.1'*
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
*compile 'com.android.support:design:25.3.1'*
}
Thats what I did and worked. Good luck!
If you have no Medium security level, then you should add your application to the Exception Site List (Java Control Panel ? Security tab).
Go to Control Panel ? Java Control Panel ? Security tab and press the Edit Site List... button.
Press the Add button, insert your path and press Enter.
Press Continue on the security warning that appears.
Open the applet again and don't forget to press Run on the pop-up window.
There is a danger with using the <input type="text" pattern="\d*">
to bring up the numeric keyboard. On firefox and chrome, the regular expression contained within the pattern causes the browser to validate the input to that expression. errors will occur if it doesn't match the pattern or is left blank. Be aware of unintended actions in other browsers.
You should rather use the attribute placeholder to give the default value to the text input field.
e.g.
<input type="text" size="32" placeholder="1000" name="fee" />
If someone is searching for a complete solution for changing default charset for all database tables and converting the data, this could be one:
DELIMITER $$
CREATE PROCEDURE `exec_query`(IN sql_text VARCHAR(255))
BEGIN
SET @tquery = `sql_text`;
PREPARE `stmt` FROM @tquery;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;
END$$
CREATE PROCEDURE `change_character_set`(IN `charset` VARCHAR(64), IN `collation` VARCHAR(64))
BEGIN
DECLARE `done` BOOLEAN DEFAULT FALSE;
DECLARE `tab_name` VARCHAR(64);
DECLARE `charset_cursor` CURSOR FOR
SELECT `table_name` FROM `information_schema`.`tables`
WHERE `table_schema` = DATABASE() AND `table_type` = 'BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = TRUE;
SET foreign_key_checks = 0;
OPEN `charset_cursor`;
`change_loop`: LOOP
FETCH `charset_cursor` INTO `tab_name`;
IF `done` THEN
LEAVE `change_loop`;
END IF;
CALL `exec_query`(CONCAT(
'ALTER TABLE `',
tab_name,
'` CONVERT TO CHARACTER SET ',
QUOTE(charset),
' COLLATE ',
QUOTE(collation),
';'
));
CALL `exec_query`(CONCAT('REPAIR TABLE `', tab_name, '`;'));
CALL `exec_query`(CONCAT('OPTIMIZE TABLE `', tab_name, '`;'));
END LOOP `change_loop`;
CLOSE `charset_cursor`;
SET foreign_key_checks = 1;
END$$
DELIMITER ;
You can place this code inside the file e.g. chg_char_set.sql
and execute it e.g. by calling it from MySQL terminal:
SOURCE ~/path-to-the-file/chg_char_set.sql
Then call defined procedure with desired input parameters e.g.
CALL change_character_set('utf8mb4', 'utf8mb4_bin');
Once you've tested the results, you can drop those stored procedures:
DROP PROCEDURE `change_character_set`;
DROP PROCEDURE `exec_query`;
I usually use:
dirname $(which $BASH_SOURCE)
You can now use string interpolation and expression bodied properties in C# 6.
private decimal _amount;
public string FormattedAmount => $"{_amount:C}";
Your array.xml is not right. change it to like this
Here is array.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
Save:
public boolean saveFile(Context context, String mytext){
Log.i("TESTE", "SAVE");
try {
FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fos);
out.write(mytext);
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Load:
public String load(Context context){
Log.i("TESTE", "FILE");
try {
FileInputStream fis = context.openFileInput("file_name"+".txt");
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String line= r.readLine();
r.close();
return line;
} catch (IOException e) {
e.printStackTrace();
Log.i("TESTE", "FILE - false");
return null;
}
}
you can solve it by overriding the Run function of CI_Form_Validation
copy this function in a class which extends CI_Form_Validation .
This function will override the parent class function . Here i added only a extra check which can handle file also
/**
* Run the Validator
*
* This function does all the work.
*
* @access public
* @return bool
*/
function run($group = '') {
// Do we even have any data to process? Mm?
if (count($_POST) == 0) {
return FALSE;
}
// Does the _field_data array containing the validation rules exist?
// If not, we look to see if they were assigned via a config file
if (count($this->_field_data) == 0) {
// No validation rules? We're done...
if (count($this->_config_rules) == 0) {
return FALSE;
}
// Is there a validation rule for the particular URI being accessed?
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
if ($uri != '' AND isset($this->_config_rules[$uri])) {
$this->set_rules($this->_config_rules[$uri]);
} else {
$this->set_rules($this->_config_rules);
}
// We're we able to set the rules correctly?
if (count($this->_field_data) == 0) {
log_message('debug', "Unable to find validation rules");
return FALSE;
}
}
// Load the language file containing error messages
$this->CI->lang->load('form_validation');
// Cycle through the rules for each field, match the
// corresponding $_POST or $_FILES item and test for errors
foreach ($this->_field_data as $field => $row) {
// Fetch the data from the corresponding $_POST or $_FILES array and cache it in the _field_data array.
// Depending on whether the field name is an array or a string will determine where we get it from.
if ($row['is_array'] == TRUE) {
if (isset($_FILES[$field])) {
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_FILES, $row['keys']);
} else {
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
}
} else {
if (isset($_POST[$field]) AND $_POST[$field] != "") {
$this->_field_data[$field]['postdata'] = $_POST[$field];
} else if (isset($_FILES[$field]) AND $_FILES[$field] != "") {
$this->_field_data[$field]['postdata'] = $_FILES[$field];
}
}
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
}
// Did we end up with any errors?
$total_errors = count($this->_error_array);
if ($total_errors > 0) {
$this->_safe_form_data = TRUE;
}
// Now we need to re-set the POST data with the new, processed data
$this->_reset_post_array();
// No errors, validation passes!
if ($total_errors == 0) {
return TRUE;
}
// Validation fails
return FALSE;
}
This might be faster if you have many files. This uses the decorate-sort-undecorate pattern so that the last-modified date of each file is fetched only once rather than every time the sort algorithm compares two files. This potentially reduces the number of I/O calls from O(n log n) to O(n).
It's more code, though, so this should only be used if you're mainly concerned with speed and it is measurably faster in practice (which I haven't checked).
class Pair implements Comparable {
public long t;
public File f;
public Pair(File file) {
f = file;
t = file.lastModified();
}
public int compareTo(Object o) {
long u = ((Pair) o).t;
return t < u ? -1 : t == u ? 0 : 1;
}
};
// Obtain the array of (file, timestamp) pairs.
File[] files = directory.listFiles();
Pair[] pairs = new Pair[files.length];
for (int i = 0; i < files.length; i++)
pairs[i] = new Pair(files[i]);
// Sort them by timestamp.
Arrays.sort(pairs);
// Take the sorted pairs and extract only the file part, discarding the timestamp.
for (int i = 0; i < files.length; i++)
files[i] = pairs[i].f;
There is a .val();
method that you can use.
So in your situation you would want to use $("#txtEmail").val();
. Also, make sure you add the id property into your html code!
The easiest way is to use the create
Manager method, which creates and saves the object in a single step.
for item in items:
MyModel.objects.create(name=item.name)
//Variables
char END_OF_FILE = '#';
char singleCharacter;
//Get a character from the input file
inFile.get(singleCharacter);
//Read the file until it reaches #
//When read pointer reads the # it will exit loop
//This requires that you have a # sign as last character in your text file
while (singleCharacter != END_OF_FILE)
{
cout << singleCharacter;
inFile.get(singleCharacter);
}
//If you need to store each character, declare a variable and store it
//in the while loop.
If you are at the office and behind the company proxy, try to imports all company proxy cacert into jre\lib\security
because gradle uses jre's certificates.
Plus, config your gradle.properties. It should work
More details go to that thread: https://groups.google.com/forum/#!msg/adt-dev/kdP2iNgcQFM/BDY7H0os18oJ
Should also be able to do this:
total += eval(myInt1) + eval(myInt2) + eval(myInt3);
This helped me in a different, but similar, situation.
var hiddenFieldID = "input[id$=" + hiddenField + "]";
var requiredVal= $(hiddenFieldID).val();
I've been working on something similar and after a few tries and fails came up with this:
Example: STRING-TO-TEST-ON = 'ab,cd,ef,gh'
I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".
My query is:
SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`
Now let me try and explain what I did ...
I had to find the position of the last "," from the string and to calculate the wantedString length, using LOCATE(",",REVERSE('ab,cd,ef,gh'))-1
by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".
calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:
LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1
I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.
I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.
If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.
try:
from urllib import quote # Python 2.X
except ImportError:
from urllib.parse import quote # Python 3+
You could also use the python compatibility wrapper six to handle this.
from six.moves.urllib.parse import quote
Right click on you image to get resolution. In my case 1233 x 882
const { width } = Dimensions.get('window');
const ratio = 882 / 1233;
const style = {
width,
height: width * ratio
}
<Image source={image} style={style} resizeMode="contain" />
That all
HttpBasicAuth works for me with smaller changes
I use maven dependency
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<version>2.3.8</version>
</dependency>
Smaller change
String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
Another option would be using flexbox.
While it's not supported by IE8 and IE9, you could consider:
Despite some additional browser-specific style prefixing would be necessary for full cross-browser support, you can see the basic usage either on this fiddle and on the following snippet:
html {_x000D_
height: 100%;_x000D_
}_x000D_
html body {_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
width: 100%;_x000D_
overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
background-color: #4C4;_x000D_
min-height: 50px;_x000D_
width: 100%;_x000D_
}_x000D_
footer {_x000D_
background-color: #4C4;_x000D_
min-height: 30px;_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
After searching for many resources/answers on this topic, I decided to code my own. Based on @TaylorOtwell's answer here, this is how I process incoming $_GET request and modify/manipulate each element.
Assuming the url is: http://domain.com/category/page.php?a=b&x=y And I want only one parameter for sorting: either ?desc=column_name or ?asc=column_name. This way, single url parameter is enough to sort and order simultaneously. So the URL will be http://domain.com/category/page.php?a=b&x=y&desc=column_name on first click of the associated table header row.
Then I have table row headings that I want to sort DESC on my first click, and ASC on the second click of the same heading. (Each first click should "ORDER BY column DESC" first) And if there is no sorting, it will sort by "date then id" by default.
You may improve it further, like you may add cleaning/filtering functions to each $_GET component but the below structure lays the foundation.
foreach ($_GET AS $KEY => $VALUE){
if ($KEY == 'desc'){
$SORT = $VALUE;
$ORDER = "ORDER BY $VALUE DESC";
$URL_ORDER = $URL_ORDER . "&asc=$VALUE";
} elseif ($KEY == 'asc'){
$SORT = $VALUE;
$ORDER = "ORDER BY $VALUE ASC";
$URL_ORDER = $URL_ORDER . "&desc=$VALUE";
} else {
$URL_ORDER .= "&$KEY=$VALUE";
$URL .= "&$KEY=$VALUE";
}
}
if (!$ORDER){$ORDER = 'ORDER BY date DESC, id DESC';}
if ($URL_ORDER){$URL_ORDER = $_SERVER[SCRIPT_URL] . '?' . trim($URL_ORDER, '&');}
if ($URL){$URL = $_SERVER[SCRIPT_URL] . '?' . trim($URL, '&');}
(You may use $_SERVER[SCRIPT_URI] for full URL beginning with http://domain.com)
Then I use resulting $ORDER I get above, in the MySQL query:
"SELECT * FROM table WHERE limiter = 'any' $ORDER";
Now the function to look at the URL if there is a previous sorting and add sorting (and ordering) parameter to URL with "?" or "&" according to the sequence:
function sort_order ($_SORT){
global $SORT, $URL_ORDER, $URL;
if ($SORT == $_SORT){
return $URL_ORDER;
} else {
if (strpos($URL, '?') !== false){
return "$URL&desc=$_SORT";
} else {
return "$URL?desc=$_SORT";
}
}
}
Finally, the table row header to use the function:
echo "<th><a href='".sort_order('id')."'>ID</a></th>";
Summary: this will read the URL, modify each of the $_GET components and make the final URL with parameters of your choice with the correct form of usage of "?" and "&"
Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:
File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
public static string DataTable2String(DataTable dataTable)
{
StringBuilder sb = new StringBuilder();
if (dataTable != null)
{
string seperator = " | ";
#region get min length for columns
Hashtable hash = new Hashtable();
foreach (DataColumn col in dataTable.Columns)
hash[col.ColumnName] = col.ColumnName.Length;
foreach (DataRow row in dataTable.Rows)
for (int i = 0; i < row.ItemArray.Length; i++)
if (row[i] != null)
if (((string)row[i]).Length > (int)hash[dataTable.Columns[i].ColumnName])
hash[dataTable.Columns[i].ColumnName] = ((string)row[i]).Length;
int rowLength = (hash.Values.Count + 1) * seperator.Length;
foreach (object o in hash.Values)
rowLength += (int)o;
#endregion get min length for columns
sb.Append(new string('=', (rowLength - " DataTable ".Length) / 2));
sb.Append(" DataTable ");
sb.AppendLine(new string('=', (rowLength - " DataTable ".Length) / 2));
if (!string.IsNullOrEmpty(dataTable.TableName))
sb.AppendLine(String.Format("{0,-" + rowLength + "}", String.Format("{0," + ((rowLength + dataTable.TableName.Length) / 2).ToString() + "}", dataTable.TableName)));
#region write values
foreach (DataColumn col in dataTable.Columns)
sb.Append(seperator + String.Format("{0,-" + hash[col.ColumnName] + "}", col.ColumnName));
sb.AppendLine(seperator);
sb.AppendLine(new string('-', rowLength));
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < row.ItemArray.Length; i++)
{
sb.Append(seperator + String.Format("{0," + hash[dataTable.Columns[i].ColumnName] + "}", row[i]));
if (i == row.ItemArray.Length - 1)
sb.AppendLine(seperator);
}
}
#endregion write values
sb.AppendLine(new string('=', rowLength));
}
else
sb.AppendLine("================ DataTable is NULL ================");
return sb.ToString();
}
output:
======================= DataTable =======================
MyTable
| COL1 | COL2 | COL3 1000000ng name |
----------------------------------------------------------
| 1 | 2 | 3 |
| abc | Dienstag, 12. März 2013 | xyz |
| Have | a nice | day! |
==========================================================
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
Sheet1.Range("myrange").Rows.Count
This appears to be a variable naming convention in Node.js control-flow code, where a reference to the next function to execute is given to a callback for it to kick-off when it's done.
See, for example, the code samples here:
Let's look at the example you posted:
function loadUser(req, res, next) {
if (req.session.user_id) {
User.findById(req.session.user_id, function(user) {
if (user) {
req.currentUser = user;
return next();
} else {
res.redirect('/sessions/new');
}
});
} else {
res.redirect('/sessions/new');
}
}
app.get('/documents.:format?', loadUser, function(req, res) {
// ...
});
The loadUser
function expects a function in its third argument, which is bound to the name next
. This is a normal function parameter. It holds a reference to the next action to perform and is called once loadUser
is done (unless a user could not be found).
There's nothing special about the name next
in this example; we could have named it anything.
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:
df.info()
UPDATE: Android SDK 11 added a recreate()
method to activities.
I've done that by simply reusing the intent that started the activity. Define an intent starterIntent
in your class and assign it in onCreate()
using starterIntent = getIntent();
. Then when you want to restart the activity, call finish(); startActivity(starterIntent);
It isn't a very elegant solution, but it's a simple way to restart your activity and force it to reload everything.
@(ViewContext.RouteData.Values["parameterName"])
worked with ROUTE PARAM.
Request.Params["paramName"]
did not work with ROUTE PARAM.
A lot of these answers overly complicated and also missing how to use variables. This is how you would do it more simply on standard Linux system (as previously mentioned the date command would have to be adjusted for Mac Users) :
Sample script:
#!/bin/bash
orig="Apr 28 07:50:01"
epoch=$(date -d "${orig}" +"%s")
epoch_to_date=$(date -d @$epoch +%Y%m%d_%H%M%S)
echo "RESULTS:"
echo "original = $orig"
echo "epoch conv = $epoch"
echo "epoch to human readable time stamp = $epoch_to_date"
Results in :
RESULTS:
original = Apr 28 07:50:01
epoch conv = 1524916201
epoch to human readable time stamp = 20180428_075001
Or as a function :
# -- Converts from human to epoch or epoch to human, specifically "Apr 28 07:50:01" human.
# typeset now=$(date +"%s")
# typeset now_human_date=$(convert_cron_time "human" "$now")
function convert_cron_time() {
case "${1,,}" in
epoch)
# human to epoch (eg. "Apr 28 07:50:01" to 1524916201)
echo $(date -d "${2}" +"%s")
;;
human)
# epoch to human (eg. 1524916201 to "Apr 28 07:50:01")
echo $(date -d "@${2}" +"%b %d %H:%M:%S")
;;
esac
}
You should look at the documentation for the Action method; it's explained well. For your case, this should work:
@Html.Action("GetOptions", new { pk="00", rk="00" });
The controllerName
parameter will default to the controller from which Html.Action
is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:
@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
You can just use the global object.
var X = ['a', 'b', 'c'];
global.x = X;
console.log(x);
//['a', 'b', 'c']
All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String)
and class.getClassLoader().getResourceAsStream(String)
. This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).
MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!
Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String)
in the past and haven't had any problems.
PS: I also posted this over here
You can change rounding scheme using:
var value = -0.5;
var value2 = 0.5;
var value3 = 1.4;
Console.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1
Console.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1
Console.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1
Use a MemoryStream
instead of a FileStream
, like this:
MemoryStream ms = new MemoryStream();
bmp.Save (ms, ImageFormat.Jpeg);
byte[] bmpBytes = ms.ToArray();
imprime en linea los datos con un espaciado determinado, así tendrás columnas de datos de la misma variable y será más claro
Print all data in line, so you have rows with the data you need, i just solve the same problem like this, just make sur you had asignad a constant data size and spacement between, I made this
Serial.print("cuenta q2: ");
Serial.print( cuenta_pulsos_encoder_1,3);
Serial.print("\t");
Serial.print(q2_real,4);
Serial.print("\t");
Serial.print("cuenta q3: ");
Serial.print( cuenta_pulsos_encoder_2,3);
Serial.print("\t");
Serial.print(q3_real,4);
Serial.print("\t");
Serial.print("cuenta q4: ");
Serial.print( cuenta_pulsos_encoder_3,3);
Serial.print("\t");
Serial.println(q4_real,4);
You can fix this issue by do as following:
<classpathentry kind="src"
path="src/test/java"/>
. You replace "src/test/java" by your test packageThis issue happened because of junit cannot recognize your source code :D
Just in case somebody land here... since 8.1 you can simply use:
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'
From the docs:
BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.
Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
I did it like this, a variation on Vadims code but to me a bit more readable:
' Returns TRUE if item is already contained in collection, otherwise FALSE
Public Function Contains(col As Collection, item As String) As Boolean
Dim i As Integer
For i = 1 To col.Count
If col.item(i) = item Then
Contains = True
Exit Function
End If
Next i
Contains = False
End Function
Or use the sys.columns
--SQL 2005
SELECT *
FROM sys.columns
WHERE OBJECT_NAME(object_id) = 'spt_values'
-- returns 6 rows = 6 columns
--SQL 2000
SELECT *
FROM syscolumns
WHERE OBJECT_NAME(id) = 'spt_values'
-- returns 6 rows = 6 columns
SELECT *
FROM dbo.spt_values
-- 6 columns indeed
I found this answer above (https://stackoverflow.com/a/41407246/4808079) very useful, but incomplete. If you only ever wanted to color something once, I guess it'd be fine, but I think sharing it in a runnable functional form is much more applicable to real life use cases.
const Color = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
Dim: "\x1b[2m",
Underscore: "\x1b[4m",
Blink: "\x1b[5m",
Reverse: "\x1b[7m",
Hidden: "\x1b[8m",
FgBlack: "\x1b[30m",
FgRed: "\x1b[31m",
FgGreen: "\x1b[32m",
FgYellow: "\x1b[33m",
FgBlue: "\x1b[34m",
FgMagenta: "\x1b[35m",
FgCyan: "\x1b[36m",
FgWhite: "\x1b[37m",
BgBlack: "\x1b[40m",
BgRed: "\x1b[41m",
BgGreen: "\x1b[42m",
BgYellow: "\x1b[43m",
BgBlue: "\x1b[44m",
BgMagenta: "\x1b[45m",
BgCyan: "\x1b[46m",
BgWhite: "\x1b[47m"
}
function colorString(color, string) {
return `${color}${string}${Color.Reset}`;
}
function colorStringLog(color, string) {
console.log(colorString(color, string));
}
Use it like this:
colorStringLog(Color.FgYellow, "Some Yellow text to console log");
console.log([
colorString(Color.FgRed, "red"),
colorString(Color.FgGreen, "green"),
colorString(Color.FgBlue, "blue"),
].join(", "));
Alternative which I did programming Angular:
<div class="form-row">
<div class="form-group col-md-7">
Left
</div>
<div class="form-group col-md-5">
Right
</div>
</div>
You have the word 'document' in a string. Change:
$('document').keypress(function(e){
to
$(document).keypress(function(e){
I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:
Create your sql script file ie:
Please note the echo and serveroutput.
Test_Spool.SQL
Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);
begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
/
Spool off;
set serveroutput off;
set echo off;
Run the script from another worksheet:
@TEST_Spool.SQL
My output from the Test1.txt
set serveroutput on
declare
sqlresult varchar2(60);
begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
anonymous block completed
The date is 2016-04-07 09:21:32
Spool of
You can just sum
and set param axis=1
to sum the rows, this will ignore none numeric columns:
In [91]:
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
a b c d e
0 1 2 dd 5 8
1 2 3 ee 9 14
2 3 4 ff 1 8
If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:
In [98]:
col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:
df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
a b c d e
0 1 2 dd 5 3
1 2 3 ee 9 5
2 3 4 ff 1 7
You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3
(and uses it as default), so switch back to a value of 2
which can be read by Python 2.
Check the protocol
parameter in pickle.dump
. Your resulting code will look like this.
pickle.dump(your_object, your_file, protocol=2)
There is no protocol
parameter in pickle.load
because pickle
can determine the protocol from the file.