The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from
and Deny from
directives that are preventing access. Read the mod_authz_host documentation for more details.
You should be able to solve this in your VirtualHost by adding something like:
<Location />
Allow from all
Order Deny,Allow
</Location>
Or alternatively with a Directory
directive:
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.
Summarize the I/O behaviors
| Mode | r | r+ | w | w+ | a | a+ |
| :--------------------: | :--: | :--: | :--: | :--: | :--: | :--: |
| Read | + | + | | + | | + |
| Write | | + | + | + | + | + |
| Create | | | + | + | + | + |
| Cover | | | + | + | | |
| Point in the beginning | + | + | + | + | | |
| Point in the end | | | | | + | + |
and the decision branch
Numbers from 987-65-4320 to 987-65-4329 are reserved for use in advertisements.
You can easy get that effect without using jQueryUI, for example:
$(document).ready(function(){
$('#slide').click(function(){
var hidden = $('.hidden');
if (hidden.hasClass('visible')){
hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
} else {
hidden.animate({"left":"0px"}, "slow").addClass('visible');
}
});
});
Try this working Fiddle:
My swagger XML file was not deployed into \bin:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "SwaggerDemoApi");
c.IncludeXmlComments(string.Format(@"{0}\bin\SwaggerDemoApi.XML",
System.AppDomain.CurrentDomain.BaseDirectory));
c.DescribeAllEnumsAsStrings();
})
http://wmpratt.com/swagger-and-asp-net-web-api-part-1/
It had to be set in the Release Configuration as well as in the Debug Configuration.
You need to specify which column of the datarow you want to pull data from.
Try the following:
StringBuilder output = new StringBuilder();
foreach (DataRow rows in results.Tables[0].Rows)
{
foreach (DataColumn col in results.Tables[0].Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
1. If you want to remove a marker you can do it as marker.remove();
alternatively you can also hide the marker instead of removing it as
marker.setVisible(false);
and make it visible later whenever needed.
2. However if you want to remove all markers from the map Use map.clear();
Note: map.clear();
will also remove Polylines, Circles
etc.
3. If you not want to remove Polylines, Circles
etc. than use a loop to the length of marker (if you have multiple markers) to remove those Check out the Example here OR set them Visible false And do not use map.clear();
in such case.
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
The API Doc are very clear on this.
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:
increment
generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.
identity
supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence
uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo
uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.
seqhilo
uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid
uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.
guid
uses a database-generated GUID string on MS SQL Server and MySQL.
native
selects identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned
lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select
retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.
foreign
uses the identifier of another associated object. It is usually used in conjunction with a primary key association.
sequence-identity
a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.
If you are building a simple application with not much concurrent users, you can go for increment, identity, hilo etc.. These are simple to configure and did not need much coding inside the db.
You should choose sequence or guid depending on your database. These are safe and better because the id
generation will happen inside the database.
Update: Recently we had an an issue with idendity where primitive type (int) this was fixed by using warapper type (Integer) instead.
Below code worked for me:
<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
you have to assign connection to your command object, like..
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')");
cmd.Connection = conn;
I found the answer is very very simple...
// It is in java, but it should be same in pyspark
Column col = ds.col("colName"); //the column object
String theNameOftheCol = col.toString();
The variable "theNameOftheCol" is "colName"
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).
However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.
Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:
`-mcmodel=small'
Generate code for the small code model: the program and its
symbols must be linked in the lower 2 GB of the address space.
Pointers are 64 bits. Programs can be statically or dynamically
linked. This is the default code model.
`-mcmodel=kernel'
Generate code for the kernel code model. The kernel runs in the
negative 2 GB of the address space. This model has to be used for
Linux kernel code.
`-mcmodel=medium'
Generate code for the medium model: The program is linked in the
lower 2 GB of the address space but symbols can be located
anywhere in the address space. Programs can be statically or
dynamically linked, but building of shared libraries are not
supported with the medium model.
`-mcmodel=large'
Generate code for the large model: This model makes no assumptions
about addresses and sizes of sections.
You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.
Your question was already answered by the other posters, I'd just like to point out that
delete from table where id <> 2
(or variants thereof, not id = 2 etc) will not delete rows where id is NULL.
If you also want to delete rows with id = NULL:
delete from table where id <> 2 or id is NULL
I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .
While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
Why are you using editors to just look at a (large) file?
Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.
There is a Win32 port of GNU less. See the "less" section of the answer above.
Perl is good for quick scripts, and its ..
(range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.
For example:
$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less
This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.
Another example:
$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less
This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...
This is another useful tool you can use. To quote the Wikipedia article:
logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.
Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.
Example usage:
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"
100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.
Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...
Enable Remote Access (Grant) Home / Tutorials / Mysql / Enable Remote Access (Grant) If you try to connect to your mysql server from remote machine, and run into error like below, this article is for you.
ERROR 1130 (HY000): Host ‘1.2.3.4’ is not allowed to connect to this MySQL server
Change mysql config
Start with editing mysql config file
vim /etc/mysql/my.cnf
Comment out following lines.
#bind-address = 127.0.0.1
#skip-networking
If you do not find skip-networking line, add it and comment out it.
Restart mysql server.
~ /etc/init.d/mysql restart
Change GRANT privilege
You may be surprised to see even after above change you are not getting remote access or getting access but not able to all databases.
By default, mysql username and password you are using is allowed to access mysql-server locally. So need to update privilege.
Run a command like below to access from all machines. (Replace USERNAME
and PASSWORD
by your credentials.)
mysql> GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'%' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;
Run a command like below to give access from specific IP. (Replace USERNAME
and PASSWORD
by your credentials.)
mysql> GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'@'1.2.3.4' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;
You can replace 1.2.3.4 with your IP. You can run above command many times to GRANT access from multiple IPs.
You can also specify a separate USERNAME
& PASSWORD
for remote access.
You can check final outcome by:
SELECT * from information_schema.user_privileges where grantee like "'USERNAME'%";
Finally, you may also need to run:
mysql> FLUSH PRIVILEGES;
Test Connection
From terminal/command-line:
mysql -h HOST -u USERNAME -pPASSWORD
If you get a mysql shell, don’t forget to run show databases; to check if you have right privileges from remote machines.
Bonus-Tip: Revoke Access
If you accidentally grant access to a user, then better have revoking option handy.
Following will revoke all options for USERNAME from all machines:
mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'USERNAME'@'%';
Following will revoke all options for USERNAME from particular IP:
mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'USERNAME'@'1.2.3.4';
Its better to check information_schema.user_privileges table after running REVOKE command.
If you see USAGE privilege after running REVOKE command, its fine. It is as good as no privilege at all. I am not sure if it can be revoked.
If you want something a little more elegant/integrated, you can use a decorator to extend the input
directive with support for type=file
. The main caveat to keep in mind is that this method will not work in IE9 since IE9 didn't implement the File API. Using JavaScript to upload binary data regardless of type via XHR is simply not possible natively in IE9 or earlier (use of ActiveXObject
to access the local filesystem doesn't count as using ActiveX is just asking for security troubles).
This exact method also requires AngularJS 1.4.x or later, but you may be able to adapt this to use $provide.decorator
rather than angular.Module.decorator
- I wrote this gist to demonstrate how to do it while conforming to John Papa's AngularJS style guide:
(function() {
'use strict';
/**
* @ngdoc input
* @name input[file]
*
* @description
* Adds very basic support for ngModel to `input[type=file]` fields.
*
* Requires AngularJS 1.4.x or later. Does not support Internet Explorer 9 - the browser's
* implementation of `HTMLInputElement` must have a `files` property for file inputs.
*
* @param {string} ngModel
* Assignable AngularJS expression to data-bind to. The data-bound object will be an instance
* of {@link https://developer.mozilla.org/en-US/docs/Web/API/FileList `FileList`}.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange
* AngularJS expression to be executed when input changes due to user interaction with the
* input element.
*/
angular
.module('yourModuleNameHere')
.decorator('inputDirective', myInputFileDecorator);
myInputFileDecorator.$inject = ['$delegate', '$browser', '$sniffer', '$filter', '$parse'];
function myInputFileDecorator($delegate, $browser, $sniffer, $filter, $parse) {
var inputDirective = $delegate[0],
preLink = inputDirective.link.pre;
inputDirective.link.pre = function (scope, element, attr, ctrl) {
if (ctrl[0]) {
if (angular.lowercase(attr.type) === 'file') {
fileInputType(
scope, element, attr, ctrl[0], $sniffer, $browser, $filter, $parse);
} else {
preLink.apply(this, arguments);
}
}
};
return $delegate;
}
function fileInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
element.on('change', function (ev) {
if (angular.isDefined(element[0].files)) {
ctrl.$setViewValue(element[0].files, ev && ev.type);
}
})
ctrl.$isEmpty = function (value) {
return !value || value.length === 0;
};
}
})();
Why wasn't this done in the first place? AngularJS support is intended to reach only as far back as IE9. If you disagree with this decision and think they should have just put this in anyway, then jump the wagon to Angular 2+ because better modern support is literally why Angular 2 exists.
The issue is (as was mentioned before) that without the file api support doing this properly is unfeasible for the core given our baseline being IE9 and polyfilling this stuff is out of the question for core.
Additionally trying to handle this input in a way that is not cross-browser compatible only makes it harder for 3rd party solutions, which now have to fight/disable/workaround the core solution.
...
I'm going to close this just as we closed #1236. Angular 2 is being build to support modern browsers and with that file support will easily available.
your json file look like this
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
JSONObject jsonObject = (JSONObject)obj;
String name = (String)jsonObject.get("Name");
String course = (String)jsonObject.get("Course");
JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
System.out.println("Name: " + name);
System.out.println("Course: " + course);
System.out.println("Subjects:");
Iterator iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
the output is
Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML
I would do the folowing:
Declare separetly the enum, in it´s own file:
public enum RightEnum {
READ(100), WRITE(200), EDITOR (300);
private int value;
private RightEnum (int value) { this.value = value; }
@Override
public static Etapa valueOf(Integer value){
for( RightEnum r : RightEnum .values() ){
if ( r.getValue().equals(value))
return r;
}
return null;//or throw exception
}
public int getValue() { return value; }
}
Declare a new JPA entity named Right
@Entity
public class Right{
@Id
private Integer id;
//FIElDS
// constructor
public Right(RightEnum rightEnum){
this.id = rightEnum.getValue();
}
public Right getInstance(RightEnum rightEnum){
return new Right(rightEnum);
}
}
You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)
import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
*
*
*/
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{
@Override //this method shoudn´t be used, but I implemented anyway, just in case
public Integer convertToDatabaseColumn(RightEnum attribute) {
return attribute.getValue();
}
@Override
public RightEnum convertToEntityAttribute(Integer dbData) {
return RightEnum.valueOf(dbData);
}
}
The Authority entity:
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
// the **Entity** to map :
private Right right;
// the **Enum** to map (not to be persisted or updated) :
@Column(name="COLUMN1", insertable = false, updatable = false)
@Convert(converter = RightEnumConverter.class)
private RightEnum rightEnum;
}
By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using
autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example
And if you need to compare, you can use:
authority.getRight().equals( RightEnum.READ ); //for example
Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.
However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).
Let´s see.
The RightEnum:
public enum RightEnum {
READ(100), WRITE(200), EDITOR (300);
private int value;
private RightEnum (int value) {
try {
this.value= value;
final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
field.setAccessible(true);
field.set(this, value);
} catch (Exception e) {//or use more multicatch if you use JDK 1.7+
throw new RuntimeException(e);
}
}
@Override
public static Etapa valueOf(Integer value){
for( RightEnum r : RightEnum .values() ){
if ( r.getValue().equals(value))
return r;
}
return null;//or throw exception
}
public int getValue() { return value; }
}
and the Authority entity
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
// the **Enum** to map (to be persisted or updated) :
@Column(name="COLUMN1")
@Enumerated(EnumType.ORDINAL)
private RightEnum rightEnum;
}
In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.
I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.
Generally
In jQuery
I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using
$('#button').on('click',function(){
$('#myModal').modal();
});
myModal
is the id of Bootstrap modal
and you have to give a click event to a button when you call click that button a pop up modal will be displayed.
It is possible that the executable is statically linked and that is why ldd gzip
does not see any links - because it isn't. I don't know much about things that far back so I don't know if there would be incompatibilities if libraries are linked in statically. I might expect there to be.
I know it's the most obvious thing going and I'm sure you've done it, but chmod +x ./gzip
, yes? No such file or directory is a classic symptom of that not being done, that's why I mention it.
d = DateTime.now.utc
Oops!
That seems to work in Rails, but not vanilla Ruby (and of course that is what the question is asking)
d = Time.now.utc
Does work however.
Is there any reason you need to use DateTime
and not Time
? Time
should include everything you need:
irb(main):016:0> Time.now
=> Thu Apr 16 12:40:44 +0100 2009
All versions of make
require that command lines be indented with a TAB (not space) as the first character in the line. If you showed us the entire rule instead of just the two lines in question we could give a clearer answer, but it should be something like:
myTarget: myDependencies
@echo hi
where the first character in the second line must be TAB.
If you want to avoid including the full path to awk, you need to update your PATH variable to include the path to the directory where awk is located, then you can just type
awk
to run your programs.
Go to Control Panel->System->Advanced and set your PATH environment variable to include "C:\Program Files (x86)\GnuWin32\bin" at the end (separated by a semi-colon) from previous entry.
If by ID:
$('#datepicker').datepicker({
format: 'dd/mm/yyyy'
});
If by Class:
$('.datepicker').datepicker({
format: 'dd/mm/yyyy'
});
The correct solution that i get is
<html>
<head>
<script type="text/javascript" language="JavaScript">
function clickedButton()
{
window.location = 'new url'
}
</script>
</head>
<form name="login_form" method="post">
..................
<input type="button" value="Login" onClick="clickedButton()"/>
</form>
</html>
Here the new url is given inside the single quote.
I've used ng-change:
Date.prototype.addDays = function(days) {_x000D_
var dat = new Date(this.valueOf());_x000D_
dat.setDate(dat.getDate() + days);_x000D_
return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
function($rootScope, $scope) {_x000D_
function init() {_x000D_
$scope.startDate = new Date();_x000D_
$scope.endDate = $scope.startDate.addDays(14);_x000D_
}_x000D_
_x000D_
_x000D_
function load() {_x000D_
alert($scope.startDate);_x000D_
alert($scope.endDate);_x000D_
}_x000D_
_x000D_
init();_x000D_
// public methods_x000D_
$scope.load = load;_x000D_
$scope.setStart = function(date) {_x000D_
$scope.startDate = date;_x000D_
};_x000D_
$scope.setEnd = function(date) {_x000D_
$scope.endDate = date;_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
<label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
Run_x000D_
</button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
When you are using foreach loop within view for binded model ... Your model is supposed to be in listed format.
i.e
@model IEnumerable<ViewModels.MyViewModels>
@{
if (Model.Count() > 0)
{
@Html.DisplayFor(modelItem => Model.Theme.FirstOrDefault().name)
@foreach (var theme in Model.Theme)
{
@Html.DisplayFor(modelItem => theme.name)
@foreach(var product in theme.Products)
{
@Html.DisplayFor(modelItem => product.name)
@foreach(var order in product.Orders)
{
@Html.TextBoxFor(modelItem => order.Quantity)
@Html.TextAreaFor(modelItem => order.Note)
@Html.EditorFor(modelItem => order.DateRequestedDeliveryFor)
}
}
}
}else{
<span>No Theam avaiable</span>
}
}
Insert pull-right
into the class attribute and let bootstrap arrange the buttons.
For Bootstrap 2.3, see: http://getbootstrap.com/2.3.2/components.html#misc > Helper classes > .pull-right.
For Bootstrap 3, see: https://getbootstrap.com/docs/3.3/css/#helper-classes > Helper classes.
For Bootstrap 4, see: https://getbootstrap.com/docs/4.0/utilities/float/#responsive
The pull-right
command was removed and replaced with float-right
or in general to float-{sm,md,lg,xl}-{left,right,none}
You can use %%~nf
to get the filename only as described in the reference for for
:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause
The following options are available:
Variable with modifier Description %~I Expands %I which removes any surrounding quotation marks (""). %~fI Expands %I to a fully qualified path name. %~dI Expands %I to a drive letter only. %~pI Expands %I to a path only. %~nI Expands %I to a file name only. %~xI Expands %I to a file extension only. %~sI Expands path to contain short names only. %~aI Expands %I to the file attributes of file. %~tI Expands %I to the date and time of file. %~zI Expands %I to the size of file. %~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
Copying the ".txt" file from one folder to another is very simple and question contains the logic. Only missing part is substituting with right information as below:
import os, shutil, glob
src_fldr = r"Source Folder/Directory path"; ## Edit this
dst_fldr = "Destiantion Folder/Directory path"; ## Edit this
try:
os.makedirs(dst_fldr); ## it creates the destination folder
except:
print "Folder already exist or some error";
below lines of code will copy the file with *.txt extension files from src_fldr to dst_fldr
for txt_file in glob.glob(src_fldr+"\\*.txt"):
shutil.copy2(txt_file, dst_fldr);
In win7, if you want to set the correct timezone as a parameter in JRE, you have to edit the file deployment.properties
stored in path c:\users\%username%\appdata\locallow\sun\java\deployment
adding the string deployment.javaws.jre.1.args=-Duser.timezone\=
my_time_zone
A few years ago it was said that update()
and digest()
were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:
var crypto = require('crypto');
var text = 'I love cupcakes';
var secret = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1'; //consider using sha256
var hash, hmac;
// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);
hmac.write(text); // write in to the stream
hmac.end(); // can't read from the stream until you call end()
hash = hmac.read().toString('hex'); // read out hmac digest
console.log("Method 1: ", hash);
// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);
Tested on node v6.2.2 and v7.7.2
See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.
Html:
<input type="file" name="input-file" id="input-file">
jQuery:
var fileToUpload = $('#input-file').prop('files')[0];
We want to get first element only, because prop('files') returns array.
Complete answer is located in the official PostgreSQL documentation.
You can use new PG9.0 anonymous code block feature (http://www.postgresql.org/docs/9.1/static/sql-do.html )
DO $$
DECLARE v_List TEXT;
BEGIN
v_List := 'foobar' ;
SELECT *
FROM dbo.PubLists
WHERE Name = v_List;
-- ...
END $$;
Also you can get the last insert id:
DO $$
DECLARE lastid bigint;
BEGIN
INSERT INTO test (name) VALUES ('Test Name')
RETURNING id INTO lastid;
SELECT * FROM test WHERE id = lastid;
END $$;
For me, this issue was slightly different than other answers, as I was only receiving 404s on OPTIONS, yet I already had OPTIONS specifically stated in my Integrated Extensionless URL Handler options. Very confusing.
By adding the following security node to the web.config was necessary to knock that out - full system.webserver included for context:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering>
<verbs>
<remove verb="OPTIONS" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
Although it's not the perfect answer for this question, it is the first result for "IIS OPTIONS 404" on Google, so I hope this helps someone out; cost me an hour today.
I know it's an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
resp.read()
is the straight html of the page you want to open, and you can use opener
to view any page using your session cookie.
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
The compiler complains on
var completionHandler: (Float)->Void = {}
because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a "do nothing" closure to the completion handler:
var completionHandler: (Float)->Void = {
(arg: Float) -> Void in
}
and this can be shortened to
var completionHandler: (Float)->Void = { arg in }
due to the automatic type inference.
But what you probably want is that the completion handler is initialized to nil
in the same way that an Objective-C instance variable is inititialized to nil
. In Swift
this can be realized with an optional:
var completionHandler: ((Float)->Void)?
Now the property is automatically initialized to nil
("no value").
In Swift you would use optional binding to check of a the
completion handler has a value
if let handler = completionHandler {
handler(result)
}
or optional chaining:
completionHandler?(result)
If your latest commit is on the master branch, you can simply use
git checkout master
Firefox and other programs allow you to increase and decrease the font size with C-+ and C--. I set up my .emacs so that I have that same ability by adding these lines of code:
(global-set-key [C-kp-add] 'text-scale-increase)
(global-set-key [C-kp-subtract] 'text-scale-decrease)
What you probably need to do is redirect the user after the POST / Form Handler script has been ran.
In PHP this is done like so...
<?php
// ... Handle $_POST data, maybe insert it into a database.
// Ok, $_POST data has been handled, redirect the user
header('Location:success.php');
die();
?>
... this should allow you to refresh the page without getting that "Send Data Again" warning.
You can even redirect to the same page (if that's what you're posting to) as the POST variables will not be sent in the headers (and thus not be there to re-POST on refresh)
Always show errors on a testing server. Never show errors on a production server.
Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:
if( $state == "local" || $state == "testing" )
{
ini_set( "display_errors", "1" );
error_reporting( E_ALL & ~E_NOTICE );
}
else
{
error_reporting( 0 );
}
As of Visual Studio 2012, Microsoft no longer provides the built-in deployment package. If you wish to use this package, you will need to use VS2010.
In 2013 you have several options:
In my projects I create my own installers from scratch, which, since I do not use Windows Installer, have the advantage of being super fast, even on old machines.
The above solutions fix the project or work around the problem in some way. Sometimes you just don't want to fix the project and just hide the warning instead.
To do that, configure the contents of the warning panel and make sure to toggle-off the "build path"->"JRE System Path Problem" category. The UI for this dialog is a bit complex/weird/usability challenged so you might have to fiddle with a few of the options to make it do what you want.
Try out Vertabelo!
It's an online database modeler that supports reverse enginnering.
Just create free of charge Vertabelo account, import an existing database into Vertabelo and voila - your database is in Vertabelo!
It supports following databases:
I guess you want to do the "Iterating over Keys and Values"
As the doc here says, just add "|keys" in the variable you want and it will magically happen.
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
It never hurts to search before asking :)
Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.
Use #define OSsymbol
and #ifdef OSsymbol
where OSsymbol is a #define
'able symbol identifying your target OS.
Typically you would include a central header file defining the selected OS symbol and use OS-specific include and library directories to compile and build.
You did not specify your development environment, but I'm pretty sure your compiler provides global defines for common platforms and OSes.
See also http://en.wikibooks.org/wiki/C_Programming/Preprocessor
I found that if the application within the httpd server has a rule like "if the X-Frame-Options header exists and has a value, leave it alone; otherwise add the header X-Frame-Options: SAMEORIGIN" then an httpd.conf mod_headers rule like "Header always unset X-Frame-Options" would not suffice. The SAMEORIGIN value would always reach the client.
To remedy this, I add two, not one, mod_headers rules (in the outermost httpd.conf file):
Header set X-Frame-Options ALLOW-FROM http://to.be.deleted.com early
Header unset X-Frame-Options
The first rule tells any internal request handler that some other agent has taken responsibility for clickjack prevention and it can skip its attempt to save the world. It runs with "early" processing. The second rule strips off the entirely unwanted X-Frame-Options header. It runs with "late" processing.
I also add the appropriate Content-Security-Policy headers so that the world remains protected yet multi-sourced Javascript from trusted sites still gets to run.
If you use
{{<br />}}
it'll be escaped. If you want raw html, you gotta use
{{{<br />}}}
EDIT (Feb 5 2017): As @hitautodestruct points out, in vue 2 you should use v-html instead of triple curly braces.
Internal error is due to a HIDDEN character at end of shebang line !!
ie line #!/usr/bin/perl
By adding -
or -w
at end moves the character away from "perl" allowing the path to the perl processor to be found and script to execute.
HIDDEN character is created by the editor used to create the script
If you want the output to be
array([1.6e-01, 9.9e-01, 3.6e-04])
the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:
def my_round(value, N):
exponent = np.ceil(np.log10(value))
return 10**exponent*np.round(value*10**(-exponent), N)
For a general solution handling 0
and negative values as well, you can do something like this:
def my_round(value, N):
value = np.asarray(value).copy()
zero_mask = (value == 0)
value[zero_mask] = 1.0
sign_mask = (value < 0)
value[sign_mask] *= -1
exponent = np.ceil(np.log10(value))
result = 10**exponent*np.round(value*10**(-exponent), N)
result[sign_mask] *= -1
result[zero_mask] = 0.0
return result
If you are working in a browser that doesn't support tabindex="-1"
, you may be able to get away with just giving the things that need to be skipped a really high tab index. For example tabindex="500"
basically moves the object's tab order to the end of the page.
I did this for a long data entry form with a button thrown in the middle of it. It's not a button people click very often so I didn't want them to accidentally tab to it and press enter. disabled
wouldn't work because it's a button.
You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.
To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data
to an array before not after you try to slice it:
R = np.array(mean_data)[:,0]
instead of
R = np.array(mean_data[:,0])
But, assuming mean_data has a shape nx3
, instead of
R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]
You can simply do
A = np.array(mean_data).mean(axis=0)
which averages over the 0
th axis and returns a length-n
array
But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:
iOS 10 Swift 3.0
If you don't mind to use swift frameworks then us UINeraida to change navigation background as UIColor
or HexColor
or UIImage
and change navigation back button text programmatically, change complete forground text color.
For UINavigationBar
neraida.navigation.background.color.hexColor("54ad00", isTranslucent: false, viewController: self)
//Change navigation title, backbutton colour
neraida.navigation.foreground.color.uiColor(UIColor.white, viewController: self)
//Change navigation back button title programmatically
neraida.navigation.foreground.backButtonTitle("Custom Title", ViewController: self)
//Apply Background Image to the UINavigationBar
neraida.navigation.background.image("background", edge: (0,0,0,0), barMetrics: .default, isTranslucent: false, viewController: self)
Your Manifest
Must Change like this Activity name must Specified like ".YourActivityname"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.th.mybook"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8" android:targetSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainTabPanel"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyBookActivity" >
</activity>
</application>
For me on Arch Linux, I had to comment this:
<policy domain="delegate" rights="none" pattern="gs" />
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
Looking at the implementation differences, I see that:
[-a-zA-Z0-9._*~'()!]
Java 1.5.0 documentation on URLEncoder
:
[-a-zA-Z0-9._*]
" "
is converted into a plus sign "+"
. So basically, to get the desired result, use URLEncoder.encode(s, "UTF-8")
and then do some post-processing:
"+"
with "%20"
"%xx"
representing any of [~'()!]
back to their literal counter-partsin devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear.
The search or onclick works... but the issue I found was with the older browsers - the search fails. Lots of plugins (jquery ui autocomplete or fancytree filter) have blur and focus handlers. Adding this to an autocomplete input box worked for me(used this.value == "" because it was faster to evaluate). The blur then focus kept the cursor in the box when you hit the little 'x'.
The PropertyChange and input worked for both IE 10 and IE 8 as well as other browsers:
$("#INPUTID").on("propertychange input", function(e) {
if (this.value == "") $(this).blur().focus();
});
For FancyTree filter extension, you can use a reset button and force it's click event as follows:
var TheFancyTree = $("#FancyTreeID").fancytree("getTree");
$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
var n,
leavesOnly = false,
match = $(this).val();
// check for the escape key or empty filter
if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
$("button#btnResetSearch").click();
return;
}
n = SiteNavTree.filterNodes(function (node) {
return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
}, leavesOnly);
$("button#btnResetSearch").attr("disabled", false);
$("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();
// handle the reset and check for empty filter field...
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
if ($("input[name=FT_FilterINPUT]").val() != "")
$("input[name=FT_FilterINPUT]").val("");
$("span#SiteNavMatches").text("");
SiteNavTree.clearFilter();
}).attr("disabled", true);
Should be able to adapt this for most uses.
Let's just say you have 3 buttons:
<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">
To style the disabled button you can use the following css:
input[type="button"]:disabled{
color:#000;
}
This will only affect the button which is disabled.
To stop the color changing when hovering you can use this too:
input[type="button"]:disabled:hover{
color:#000;
}
You can also avoid this by using a css-reset.
In my case i stopped Tomcat server . then immediately the DB went offline .
I resolved my trouble in correcting the "Additional Library Directory", this one was wrong in indicating "$(SolutionDir)\Release", I changed it in "$(SolutionDir)\$(IntDir)"
To correct it, open your project properties -> Configuration Properties -> Linker -> General -> Additional Library Directory
I hope this will help some poeples with the same trouble ;)
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
In SQLAlchemy v0.8 and newer, use the inspection system.
from sqlalchemy import inspect
def object_as_dict(obj):
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs}
user = session.query(User).first()
d = object_as_dict(user)
Note that .key
is the attribute name, which can be different from the column name, e.g. in the following case:
class_ = Column('class', Text)
This method also works for column_property
.
leDbConnection connection =
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();
OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*, tbl_Besitzer.*
FROM tbl_Computer
INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID
WHERE (((tbl_Besitzer.Vorname)='ma'));",
connection);
Just export the environment variables you want above the check for a non-interactive shell in ~/.bashrc.
Open Git Bash.
Set a Git username:
$ git config --global user.name "name family" Confirm that you have set the Git username correctly:
$ git config --global user.name
name family
Set a Git email:
$ git config --global user.email [email protected] Confirm that you have set the Git email correctly:
$ git config --global user.email
If you wish to clear your entire database.
Because of the foreign-key constraints it matters which sequence the tables are truncated. This is a way to bruteforce this sequence.
public static void ClearDatabase<T>() where T : DbContext, new()
{
using (var context = new T())
{
var tableNames = context.Database.SqlQuery<string>("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME NOT LIKE '%Migration%'").ToList();
foreach (var tableName in tableNames)
{
foreach (var t in tableNames)
{
try
{
if (context.Database.ExecuteSqlCommand(string.Format("TRUNCATE TABLE [{0}]", tableName)) == 1)
break;
}
catch (Exception ex)
{
}
}
}
context.SaveChanges();
}
}
usage:
ClearDatabase<ApplicationDbContext>();
remember to reinstantiate your DbContext after this.
first find your binaries file where it is saved. get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
all done!
autovaccum launcher started! cheers!
There's a tagName
property, and a attributes
property as well:
var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
var attrib = element.attributes[i];
openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);
See also How to iterate through all attributes in an HTML element? (I did!)
To get the contents between the open and close tags you could probably use innerHTML
if you don't want to iterate over all the child elements...
alert(element.innerHTML);
... and then get the close tag again with tagName
.
var closeTag = "</"+element.tagName+">";
alert(closeTag);
Before your write to Excel need to change the format:
xlApp = New Excel.Application
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
Dim cells As Excel.Range = xlWorkSheet.Cells
'set each cell's format to Text
cells.NumberFormat = "@"
'reset horizontal alignment to the right
cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight
React Native provides a .measure(...)
method which takes a callback and calls it with the offsets and width/height of a component:
myComponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
})
The following calculates the layout of a custom component after it is rendered:
class MyComponent extends React.Component {
render() {
return <View ref={view => { this.myComponent = view; }} />
}
componentDidMount() {
// Print component dimensions to console
this.myComponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
})
}
}
Note that sometimes the component does not finish rendering before componentDidMount()
is called. If you are getting zeros as a result from measure(...)
, then wrapping it in a setTimeout
should solve the problem, i.e.:
setTimeout( myComponent.measure(...), 0 )
if you're connecting to a postgres database, the following works:
result = cursor.execute(query)
if result.returns_rows:
# we got rows!
return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
return None
You can do so starting with Postgres 9.1:
with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows
In the meanwhile, if you're only interested in the id, you can do so with a trigger:
create function t1_ins_into_t2()
returns trigger
as $$
begin
insert into table2 (val) values (new.id);
return new;
end;
$$ language plpgsql;
create trigger t1_ins_into_t2
after insert on table1
for each row
execute procedure t1_ins_into_t2();
If you don't want to recompile (as Visual Leak Detector requires) I would recommend WinDbg, which is both powerful and fast (though it's not as easy to use as one could desire).
On the other hand, if you don't want to mess with WinDbg, you can take a look at UMDH, which is also developed by Microsoft and it's easier to learn.
Take a look at these links in order to learn more about WinDbg, memory leaks and memory management in general:
This is what I finally came up with, which works great!
{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}
Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.
(start -> run -> services.msc) and look for the postgresql-[version] service then right click and enable it
There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse
for more details. In this case, you probably want:
git diff HEAD@{1}
The @{1}
means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD
on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.
I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do
git diff HEAD@{1} filename
This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.
CharlesB's answer and helmbert's answer are both helpful, but it took me a while to understand them. Here's another way of putting it:
git show <tag>
to see a tag's details contains no reference to any branches, only the ID of the commit that the tag points to.
6f6b5997506d48fc6267b0b60c3f0261b6afe7a2
)git tag v0.1.0 # tags HEAD of *current* branch
git tag v0.1.0 develop # tags HEAD of 'develop' branch
git describe
to describe the current branch:
git describe [--tags]
describes the current branch in terms of the commits since the most recent [possibly lightweight] tag in this branch's history.git describe
may NOT reflect the most recently created tag overall.Sprint as defined in pure Scrum has the duration 30 calendar days. However Iteration length could be anything as defined by the team.
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
I implemented maxlength
behaviour on textarea
recently, and run into problem described in this question: Chrome counts characters wrong in textarea with maxlength attribute.
So all implementations listed here will work little buggy. To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11")
before .length
. And kept it in mind when cuting string.
I ended with something like this:
var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
el.val(val.slice(0, maxlength - (realLength - length)));
}
Don't sure if it solves problem completely, but it works for me for now.
This is my gradle.properties, please note those HTTPS portion
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=8118
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=8118
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.
First, some definitions:
Bar
is a TypeName in Public Class Bar
, or in Dim Foo as Bar
. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.System.Type
objects which contain a value. This value indicates a type; just like a String
would take some text or an Int
would take a number, except we are storing types instead of text or numbers. Type
objects contain the type definitions, as well as its corresponding TypeName.Second, the theory:
Foo.GetType()
returns a Type
object which contains the type for the variable Foo
. In other words, it tells you what Foo
is an instance of.GetType(Bar)
returns a Type
object which contains the type for the TypeName Bar
.In some instances, the type an object has been Cast
to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer
cast into an Object
:
Dim MyVal As Integer = 42
Dim MyObj As Object = CType(MyVal, Object)
So, is MyObj
of type Object
or of type Integer
? MyObj.GetType()
will tell you it is an Integer
.
Type Of Foo Is Bar
feature, which allows you to ascertain a variable Foo
is compatible with a TypeName Bar
. Type Of MyObj Is Integer
and Type Of MyObj Is Object
will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it.
More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarksThe test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.
Public Sub TestMethod1()
Dim MyValInt As Integer = 42
Dim MyValDble As Double = CType(MyValInt, Double)
Dim MyObj As Object = CType(MyValDble, Object)
Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
Debug.Print(MyObj.GetType.ToString) 'Returns System.Double
Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType
Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False
Debug.Print(TypeOf MyObj Is Integer) 'Returns False
Debug.Print(TypeOf MyObj Is Double) '# Returns True
Debug.Print(TypeOf MyObj Is Object) '# Returns True
End Sub
EDIT
You can also use Information.TypeName(Object)
to get the TypeName of a given object. For example,
Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"
You could use the Redis Keyspace Notifications by using psubscribe
and "__keyevent@<DB-INDEX>__:expired"
.
With that, each time that a key will expire, you will get a message published on your redis connection.
Regarding your question basically you create a temporary "normal" key using set
with an expiration time in s/ms. It should match the name of the key that you wish to delete in your set.
As your temporary key will be published to your redis connection holding the "__keyevent@0__:expired"
when it expired, you can easily delete your key from your original set as the message will have the name of the key.
A simple example in practice on that page : https://medium.com/@micah1powell/using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3
doc : https://redis.io/topics/notifications ( look for the flag xE)
I assume you're talking about a UIButton with UIButtonTypeRoundedRect
?
You can't change the background color of that. When you try changing it's background color you're rather changing the color of the rect the button is drawn on (which is usually clear).
So there are two ways to go. Either you subclass UIButton and overwrite its -drawRect:
method or you create images for the different button states (which is perfectly fine to do).
If you set the background images in Interface Builder you should notice that IB doesn't support setting images for all the states the button can have, so I recommend setting the images in code like this:
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setBackgroundImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:@"disabled.png"] forState:UIControlStateDisabled];
[myButton setBackgroundImage:[UIImage imageNamed:@"selected.png"] forState:UIControlStateSelected];
[myButton setBackgroundImage:[UIImage imageNamed:@"higligted.png"] forState:UIControlStateHighlighted];
[myButton setBackgroundImage:[UIImage imageNamed:@"highlighted+selected.png"] forState:(UIControlStateHighlighted | UIControlStateSelected)];
The last line shows how to set an image for the selected & highlighted state (that's the one IB can't set). You don't need the selected images (line 4 & 6) if you're button dosn't need a selected state.
echo
adds spaces between the arguments passed to it. $text
is subject to variable expansion and word splitting, so your echo
command is equivalent to:
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n" ...
You can see that a space will be added before "this". You can either remove the newline characters, and quote $text
to preserve the newlines:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
Or you could use printf
, which is more robust and portable than echo
:
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
In bash
, which supports brace expansion, you could even do:
printf "%s\n" "this is line "{one,two,three} > filename
The native system packages installed with python installation in Debian based systems can be found at :
/usr/lib/python2.7/dist-packages/
In OSX - /Library/Python/2.7/site-packages
by using this small code :
from distutils.sysconfig import get_python_lib
print get_python_lib()
However, the list of packages installed via pip
can be found at :
/usr/local/bin/
Or one can simply write the following command to list all paths where python packages are.
>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
Note: the location might vary based on your OS, like in OSX
>>> import site; site.getsitepackages()
['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']
Best answer of that question I've seen is:
list(, $caller) = debug_backtrace(false);
Short and clean
I faced this error several times and, it was due to transferring large resources(larger than 3MB) from server to client.
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
robocopy seems to be the most versatile. See it's other options in the help
robocopy /?
robocopy SRC DST /E /MOV
Try this.
Dim Workbk as workbook
Set Workbk = thisworkbook
Now everything you program will apply just for your containing macro workbook.
Integer i = 5; //example
Long l = Long.valueOf(i.longValue());
This avoids the performance hit of converting to a String. The longValue()
method in Integer is just a cast of the int value. The Long.valueOf()
method gives the vm a chance to use a cached value.
Suppose you need to pass an arraylist of following class from current activity to next activity // class of the objects those in the arraylist // remember to implement the class from Serializable interface // Serializable means it converts the object into stream of bytes and helps to transfer that object
public class Question implements Serializable {
...
...
...
}
in your current activity you probably have an ArrayList as follows
ArrayList<Question> qsList = new ArrayList<>();
qsList.add(new Question(1));
qsList.add(new Question(2));
qsList.add(new Question(3));
// intialize Bundle instance
Bundle b = new Bundle();
// putting questions list into the bundle .. as key value pair.
// so you can retrieve the arrayList with this key
b.putSerializable("questions", (Serializable) qsList);
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
i.putExtras(b);
startActivity(i);
in order to get the arraylist within the next activity
//get the bundle
Bundle b = getIntent().getExtras();
//getting the arraylist from the key
ArrayList<Question> q = (ArrayList<Question>) b.getSerializable("questions");
Atomic size is 4096 bytes, max size is 65536 bytes. Sendfile uses 16 pipes each of 4096 bytes size. cmd : ioctl(fd, FIONREAD, &buff_size).
AForge.net is a free (open-source) library with Fast Fourier Transform support. (See Sources/Imaging/ComplexImage.cs for usage, Sources/Math/FourierTransform.cs for implemenation)
To make it easier add a custom function and call it when ever you want that changing the value also trigger change
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTirgger("NewValue");
Or you can override the val function to always call the change when the val is called
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
@derchambers I found one more solution:
import pandas as pd
# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'
def eval_join(df, columns):
sum_elements = [f"df['{col}']" for col in list('1234')]
to_eval = "+ '_' + ".join(sum_elements)
return eval(to_eval)
#profile
%timeit df3 = eval_join(df, list('1234')) # 504 ms
If your strings are compile time constants (as in your case) you can use the following trick:
#define USER_JACK strcmp(USER, "jack")
#define USER_QUEEN strcmp(USER, "queen")
#if $USER_JACK == 0
#define USER_VS USER_QUEEN
#elif USER_QUEEN == 0
#define USER_VS USER_JACK
#endif
The compiler can tell the result of the strcmp in advance and will replace the strcmp with its result, thus giving you a #define that can be compared with preprocessor directives. I don't know if there's any variance between compilers/dependance on compiler options, but it worked for me on GCC 4.7.2.
EDIT: upon further investigation, it look like this is a toolchain extension, not GCC extension, so take that into consideration...
Console Application is an application (.exe), not a Library (.dll). To make a library, create a new project, select "Class Library" in type of project, then copy the logic of your first code into this new project.
Or you can edit the Project Properties and select Class Library instead of Console Application in Output type.
As some code can be "console" dependant, I think first solution is better if you check your logic when you copy it.
I wrote a tutorial about this a while ago.
The most important point is the "Site URL":
Site URL: http://localhost/app_name/
Where the folder structure is something like:
app_name
¦ index.php
¦
+---canvas
¦ ¦ index.php
¦ ¦
¦ +---css
¦ main.css
¦ reset.css
¦
+---src
facebook.php
fb_ca_chain_bundle.crt
EDIT:
Kavya: how does the FB server recognize my localhost even without an IP or port??
I don't think this has anything to do with Facebook, I guess since the iframe src
parameter is loaded from client-side it'll treat your local URL as if you put it directly on your browser.
For example have a file on your online server with content (e.g. online.php
):
<iframe src="http://localhost/test.php" width="100%" height="100%">
<p>Not supported!</p>
</iframe>
And on your localhost root directory, have the file test.php
:
<?php echo "Hello from Localhost!"; ?>
Now visit http://your_domain.com/online.php
you will see your localhost file's content!
This is why realtime subscriptions and deauthorize callbacks (just to mention) won't work with localhost URLs! because Facebook will ping (send http requests) to these URLs but obviously Facebook server won't translate those URLs to yours!
Android Studio 0.8.10+ has introduced an incredibly useful tool called Memory Monitor.
What it's good for:
- Showing available and used memory in a graph, and garbage collection events over time.
- Quickly testing whether app slowness might be related to excessive garbage collection events.
- Quickly testing whether app crashes may be related to running out of memory.
Figure 1. Forcing a GC (Garbage Collection) event on Android Memory Monitor
You can have plenty good information on your app's RAM real-time consumption by using it.
Sorting a tuple is quite simple:
tuple(sorted(t))
A degree of control is possible over how information travels from a third-party website to Facebook when a page is shared (or liked, etc.). In order to make this possible, information is sent via Open Graph meta tags in the <head>
part of the website’s code.
You can use .rstrip('\n')
to only remove newlines from the end of the string:
for i in contents:
alist.append(i.rstrip('\n'))
This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip()
.
However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines()
method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read()
result and don't use file.readlines()
at all:
alist = t.read().splitlines()
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve
saves the file to a temporary file and returns a tuple (filename, headers)
urlopen
returns a Request
object whose read
method returns a bytestring containing the file contentsIn the recent Git, you can add -r
/--rebase
on pull
command to rebase your current branch on top of the upstream branch after fetching. The warning should disappear, but there is a risk that you'll get some conflicts which you'll need to solve.
Alternatively you can checkout different branch with force, then go back to master
again, e.g.:
git checkout origin/master -f
git checkout master -f
Then pull it again as usual:
git pull origin master
Using this method can save you time from stashing (git stash
) and potential permission issues, reseting files (git reset HEAD --hard
), removing files (git clean -fd
), etc. Also the above it's easier to remember.
express-fileupload
looks like the only middleware that still works these days.
With the same example, multer
and connect-multiparty
gives an undefined value of req.file or req.files, but express-fileupload
works.
And there are a lot of questions and issues raised about the empty value of req.file/req.files.
We had some code here (in VS2005 and C#2.0) where the previous engineers went out of their way to use list.ForEach( delegate(item) { foo;});
instead of foreach(item in list) {foo; };
for all the code that they wrote. e.g. a block of code for reading rows from a dataReader.
I still don't know exactly why they did this.
The drawbacks of list.ForEach()
are:
It is more verbose in C# 2.0. However, in C# 3 onwards, you can use the "=>
" syntax to make some nicely terse expressions.
It is less familiar. People who have to maintain this code will wonder why you did it that way. It took me awhile to decide that there wasn't any reason, except maybe to make the writer seem clever (the quality of the rest of the code undermined that). It was also less readable, with the "})
" at the end of the delegate code block.
See also Bill Wagner's book "Effective C#: 50 Specific Ways to Improve Your C#" where he talks about why foreach is preferred to other loops like for or while loops - the main point is that you are letting the compiler decide the best way to construct the loop. If a future version of the compiler manages to use a faster technique, then you will get this for free by using foreach and rebuilding, rather than changing your code.
a foreach(item in list)
construct allows you to use break
or continue
if you need to exit the iteration or the loop. But you cannot alter the list inside a foreach loop.
I'm surprised to see that list.ForEach
is slightly faster. But that's probably not a valid reason to use it throughout , that would be premature optimisation. If your application uses a database or web service that, not loop control, is almost always going to be be where the time goes. And have you benchmarked it against a for
loop too? The list.ForEach
could be faster due to using that internally and a for
loop without the wrapper would be even faster.
I disagree that the list.ForEach(delegate)
version is "more functional" in any significant way. It does pass a function to a function, but there's no big difference in the outcome or program organisation.
I don't think that foreach(item in list)
"says exactly how you want it done" - a for(int 1 = 0; i < count; i++)
loop does that, a foreach
loop leaves the choice of control up to the compiler.
My feeling is, on a new project, to use foreach(item in list)
for most loops in order to adhere to the common usage and for readability, and use list.Foreach()
only for short blocks, when you can do something more elegantly or compactly with the C# 3 "=>
" operator. In cases like that, there may already be a LINQ extension method that is more specific than ForEach()
. See if Where()
, Select()
, Any()
, All()
, Max()
or one of the many other LINQ methods doesn't already do what you want from the loop.
It is indeed possible to change a div
elements' width in jQuery:
$("#div").css("width", "300px");
However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:
#div {
width: 75%;
/* You can also specify min/max widths */
min-width: 300px;
max-width: 960px;
}
This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.
I was hit by an unresponsive build and absolutely nothing would allow me to either kill or cancel the build. Even trying to end the task would trigger a user input window, saying that it could not be ended while the build is still going on (quite ironic because that was precisely the intention, to leave that broken state).
The build was taken care of by MSBuild, so the one way I found is to end its task. When forcing MSBuild.exe to end, VS will wake up and finally see the build as cancelled, allowing you to work again.
Hope this helps someone in the same situation.
Using old C++ version, you can use this snippet :
template<typename T>
string toBinary(const T& t)
{
string s = "";
int n = sizeof(T)*8;
for(int i=n-1; i>=0; i--)
{
s += (t & (1 << i))?"1":"0";
}
return s;
}
int main()
{
char a, b;
short c;
a = -58;
c = -315;
b = a >> 3;
cout << "a = " << a << " => " << toBinary(a) << endl;
cout << "b = " << b << " => " << toBinary(b) << endl;
cout << "c = " << c << " => " << toBinary(c) << endl;
}
a = => 11000110
b = => 11111000
c = -315 => 1111111011000101
You can use re.escape():
re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_
).
This is possible, but you need to use JSONP, not JSON. Stefan's link pointed you in the right direction. The jQuery AJAX page has more information on JSONP.
Remy Sharp has a detailed example using PHP.
function DoPrevent(e) {
e.preventDefault();
e.stopPropagation();
}
// Bind:
$(element).on('click', DoPrevent);
// UnBind:
$(element).off('click', DoPrevent);
I would like to run an automation test in different environments.
So I add this to command maven command:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"
Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095
The package.json file is used by npm to learn about your node.js project.
Use npm init
to generate package.json files for you!
It comes bundled with npm. Read its documentation here: https://docs.npmjs.com/cli/init
Also, there's an official tool you can use to generate this file programmatically: https://github.com/npm/init-package-json
if (foo = bar)
by accident.Therefore I prefer
if (foo == NULL)
{
// null case
}
else
{
// non null case
}
or
if (foo != NULL)
{
// non null case
}
else
{
// null case
}
However, if I were writing a set of style guidelines I would not be putting things like this in it, I would be putting things like:
Make sure you do a null check on the pointer.
You can modify .htaccess like others said, but the fastest solution is to rename the file extension to .php
Check if db name do not have "_" or "-" that helps in my case
Using the DateTime class available in PHP version 5.2 it would be done like this:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
As of PHP 5.4 you can do this as a one-liner:
echo (new DateTime('17 Oct 2008'))->format('c');
You can use y.count()
.
It will return the integer value of the number of times a sub string appears in a string.
For example:
string.count("bah") >> 0
string.count("Hello") >> 1
For portability, try this:
#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif
Then simply call clrscr()
. On Windows, it will use conio.h
's clrscr()
, and on Linux, it will use ANSI escape codes.
If you really want to do it "properly", you can eliminate the middlemen (conio
, printf
, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
#else // !_WIN32
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
#endif
You can use split function.
SELECT
(select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
(select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
(select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
FROM MyTbl
StringUtils.isBlank() returns true for blanks(just whitespaces)and for null String as well. Actually it trims the Char sequences and then performs check.
StringUtils.isEmpty() returns true when there is no charsequence in the String parameter or when String parameter is null. Difference is that isEmpty() returns false if String parameter contains just whiltespaces. It considers whitespaces as a state of being non empty.
this.WindowState = FormWindowState.Maximized;
Very simple:
import json
data = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print data['two']
If you do import foo
(inside bar.py
) and import bar
(inside foo.py
), it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.
The problem is when instead you do from foo import abc
(inside bar.py
) and from bar import xyz
(inside foo.py
). Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.
you can pass multiple params in url like
http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc
and in order to get this query fields , you can use map like
@RequestMapping(method = RequestMethod.GET, value = "/custom")
public String controllerMethod(@RequestParam Map<String, String> customQuery) {
System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
System.out.println("customQuery = price " + customQuery.containsKey("price"));
System.out.println("customQuery = other " + customQuery.containsKey("other"));
System.out.println("customQuery = sort " + customQuery.containsKey("sort"));
return customQuery.toString();
}
When using hashcodes with any jce provider you first try to get an instance of the algorithm, then update it with the data you want to be hashed and when you are finished you call digest to get the hash value.
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(in.getBytes());
byte[] digest = sha.digest();
you can use the digest to get a base64 or hex encoded version according to your needs
Angular
var payload = $.param({ jobId: 2 });
this.$http({
method: 'POST',
url: 'web/api/ResourceAction/processfile',
data: payload,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
WebAPI 2
public class AcceptJobParams
{
public int jobId { get; set; }
}
public IHttpActionResult ProcessFile([FromBody]AcceptJobParams thing)
{
// do something with fileName parameter
return Ok();
}
jQuery('#main').css('opacity') = '0.6';
should be
jQuery('#main').css('opacity', '0.6');
Update:
http://jsfiddle.net/GegMk/ if you type in the text box. Click away, the opacity changes.
Most easiest way in a single line of code
var base64Image = new Buffer( blob, 'binary' ).toString('base64');
Install the wheel
package first:
pip install wheel
The documentation isn't overly clear on this, but "the wheel project provides a bdist_wheel command for setuptools" actually means "the wheel package...".
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
First, add a data conversion block into your data flow diagram.
Open the data conversion block and tick the column for which the error is showing. Below change its data type to unicode string(DT_WSTR) or whatever datatype is expected and save.
Go to the destination block. Go to mapping in it and map the newly created element to its corresponding address and save.
Right click your project in the solution explorer.select properties. Select configuration properties and select debugging in it. In this, set the Run64BitRunTime option to false (as excel does not handle the 64 bit application very well).
Select Case parameter
' does something here.
' does something here.
Case "userID", "packageID", "mvrType"
If otherFactor Then
' does something here.
Else
goto case default
End If
Case Else
' does some processing...
Exit Select
End Select
use
select convert(varchar(10),GETDATE(), 103) +
' '+
right(convert(varchar(32),GETDATE(),108),8) AS Date_Time
It will Produce:
Date_Time 30/03/2015 11:51:40
Try using combination of map and lambda functions:
aList = map( lambda x: x, set ([1, 2, 6, 9, 0]) )
It is very convenient approach if you have a set of numbers in string and you want to convert it to list of integers:
aList = map( lambda x: int(x), set (['1', '2', '3', '7', '12']) )
I wrote a simple function:
function push(&$arr,$new) {
$arr = array_merge($arr,$new);
}
so that I can "upsert" new element easily:
push($my_array, ['a'=>1,'b'=>2])
At the time this question was asked nobody thought about Bitcoin price. In the case of BTC, it is probably insufficient to use DECIMAL(15,2)
. If the Bitcoin will rise to $100,000 or more, we will need at least DECIMAL(18,9)
to support cryptocurrencies in our apps.
DECIMAL(18,9)
takes 12 bytes of space in MySQL (4 bytes per 9 digits).
let me share my experience:
my html page designer use:
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
when I create a simple AJAX request, getting an error it says, TypeError: $.ajax(…) is not a function
So, i add:
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
then, it perfectly works for me at least.
C# 9 records and with expressions can make it a little easier, especially if your type has many properties.
You can use something like:
var books2 = books1.Select(b => b with { }).ToList();
I did this as an example:
record Book
{
public string Name { get; set; }
}
static void Main()
{
List<Book> books1 = new List<Book>()
{
new Book { Name = "Book1.1" },
new Book { Name = "Book1.2" },
new Book { Name = "Book1.3" }
};
var books2 = books1.Select(b => b with { }).ToList();
books2[0].Name = "Changed";
books2[1].Name = "Changed";
Console.WriteLine("Book1");
foreach (var item in books1)
{
Console.WriteLine(item);
}
Console.WriteLine("Book2");
foreach (var item in books2)
{
Console.WriteLine(item);
}
}
And the result was:
Book1
Book { Name = Book1.1 }
Book { Name = Book1.2 }
Book { Name = Book1.3 }
Book2
Book { Name = Changed }
Book { Name = Changed }
Book { Name = Book1.3 }
A case when process get SIGABRT from itself: Hrvoje mentioned about a buried pure virtual being called from ctor generating an abort, i recreated an example for this. Here when d is to be constructed, it first calls its base class A ctor, and passes inside pointer to itself. the A ctor calls pure virtual method before table was filled with valid pointer, because d is not constructed yet.
#include<iostream>
using namespace std;
class A {
public:
A(A *pa){pa->f();}
virtual void f()=0;
};
class D : public A {
public:
D():A(this){}
virtual void f() {cout<<"D::f\n";}
};
int main(){
D d;
A *pa = &d;
pa->f();
return 0;
}
compile: g++ -o aa aa.cpp
ulimit -c unlimited
run: ./aa
pure virtual method called
terminate called without an active exception
Aborted (core dumped)
now lets quickly see the core file, and validate that SIGABRT was indeed called:
gdb aa core
see regs:
i r
rdx 0x6 6
rsi 0x69a 1690
rdi 0x69a 1690
rip 0x7feae3170c37
check code:
disas 0x7feae3170c37
mov $0xea,%eax = 234 <- this is the kill syscall, sends signal to process
syscall <-----
http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/
234 sys_tgkill pid_t tgid pid_t pid int sig = 6 = SIGABRT
:)
Maybe you want to search for some text in all columns of the Pandas dataframe, and not just in the subset of them. In this case, the following code will help.
df[df.apply(lambda row: row.astype(str).str.contains('String To Find').any(), axis=1)]
Warning. This method is relatively slow, albeit convenient.
mayavi
.So I also had the common error: Microsoft Visual C++ 14.0 is required
when pip installing a library.
After looking across many web pages and the solutions to this thread, with none of them working. I figured these steps (most taken from previous solutions) allowed this to work.
Build Tools for Visual Studio 2017
. Which is under All downloads
(scroll down) >> Tools for Visual Studio 2017
C++ Components
you require (I didn't know which I required so installed many of them).
Build Tools for Visual Studio 2017
then open the application Visual Studio Installer
then go to Visual Studio Build Tools 2017
>> Modify
>> Individual Components
and selected the required components. C++/CLI support
, VC++ 2017 version <...> latest
, Visual C++ 2017 Redistributable Update
, Visual C++ tools for CMake
, Windows 10 SDK <...> for Desktop C++
, Visual C++ Build Tools core features
, Visual Studio C++ core features
.Install/Modify these components for Visual Studio Build Tools 2017
.
This is the important step. Open the application Visual Studio Installer
then go to Visual Studio Build Tools
>> Launch
. Which will open a CMD window at the correct location for Microsoft Visual Studio\YYYY\BuildTools
.
python -m pip install --upgrade setuptools
within this CMD window.pip install -U <library>
.click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export
using Sql Developer 3.0
See SQL Developer downloads for latest versions
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
I don't know why but you have to add a setTimeout with at least for me 200ms:
setTimeout( function() {$("#DIV_ID").scrollTop(0)}, 200 );
Tested with Firefox / Chrome / Edge.
You need to create a delegate type. The keyword 'delegate' in the anonymous method creation is a bit misleading. You are not creating an anonymous delegate but an anonymous method. The method you created can be used in a delegate. Like this:
myControl.Invoke(new MethodInvoker(delegate() { (MyMethod(this, new MyEventArgs(someParameter)); }));
Have you tried the Generate Scripts
(Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
Simple answer: give these two tds a style field.
<tr>
<td>One</td>
<td style="padding-right: 10px">Two</td>
<td>Three</td>
<td>Four</td>
</tr>
Tidy one: use class name
<tr>
<td>One</td>
<td class="more-padding-on-right">Two</td>
<td>Three</td>
<td>Four</td>
</tr>
.more-padding-on-right {
padding-right: 10px;
}
Complex one: using nth-child selector in CSS and specify special padding values for these two, which works in modern browsers.
tr td:nth-child(2) {
padding-right: 10px;
}?
Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.
Client to call REST webservice:
package in.india.client.downloadfiledemo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;
public class DownloadFileClient {
private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";
public DownloadFileClient() {
try {
Client client = Client.create();
WebResource objWebResource = client.resource(BASE_URI);
ClientResponse response = objWebResource.path("/")
.type(MediaType.TEXT_HTML).get(ClientResponse.class);
System.out.println("response : " + response);
if (response.getStatus() == Status.OK.getStatusCode()
&& response.hasEntity()) {
MultiPart objMultiPart = response.getEntity(MultiPart.class);
java.util.List<BodyPart> listBodyPart = objMultiPart
.getBodyParts();
BodyPart filenameBodyPart = listBodyPart.get(0);
BodyPart fileLengthBodyPart = listBodyPart.get(1);
BodyPart fileBodyPart = listBodyPart.get(2);
String filename = filenameBodyPart.getEntityAs(String.class);
String fileLength = fileLengthBodyPart
.getEntityAs(String.class);
File streamedFile = fileBodyPart.getEntityAs(File.class);
BufferedInputStream objBufferedInputStream = new BufferedInputStream(
new FileInputStream(streamedFile));
byte[] bytes = new byte[objBufferedInputStream.available()];
objBufferedInputStream.read(bytes);
String outFileName = "D:/"
+ filename;
System.out.println("File name is : " + filename
+ " and length is : " + fileLength);
FileOutputStream objFileOutputStream = new FileOutputStream(
outFileName);
objFileOutputStream.write(bytes);
objFileOutputStream.close();
objBufferedInputStream.close();
File receivedFile = new File(outFileName);
System.out.print("Is the file size is same? :\t");
System.out.println(Long.parseLong(fileLength) == receivedFile
.length());
}
} catch (UniformInterfaceException e) {
e.printStackTrace();
} catch (ClientHandlerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
new DownloadFileClient();
}
}
Service to response client:
package in.india.service.downloadfiledemo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.multipart.MultiPart;
@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {
@GET
public Response getFile() {
java.io.File objFile = new java.io.File(
"D:/DanGilbert_2004-480p-en.mp4");
MultiPart objMultiPart = new MultiPart();
objMultiPart.type(new MediaType("multipart", "mixed"));
objMultiPart
.bodyPart(objFile.getName(), new MediaType("text", "plain"));
objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
"plain"));
objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));
return Response.ok(objMultiPart).build();
}
}
JAR needed:
jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar
WEB.XML:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>DownloadFileDemo</display-name>
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>in.india.service.downloadfiledemo</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
After reviewing all the other answers, I ended up with this:
function oldSchoolMakeBuild(cb) {
var makeProcess = exec('make -C ./oldSchoolMakeBuild',
function (error, stdout, stderr) {
stderr && console.error(stderr);
cb(error);
});
makeProcess.stdout.on('data', function(data) {
process.stdout.write('oldSchoolMakeBuild: '+ data);
});
}
Sometimes data
will be multiple lines, so the oldSchoolMakeBuild
header will appear once for multiple lines. But this didn't bother me enough to change it.
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
Thank you guys for the help,
When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:
The easy method that will work even in corrupted setup environment is :
To download ez_setup.py and run it using command line
python ez_setup.py
output
Extracting in c:\uu\uu\appdata\local\temp\tmpjxvil3
Now working in c:\u\u\appdata\local\temp\tmpjxvil3\setuptools-5.6
Installing Setuptools
run
pip install beautifulsoup4
output
Downloading/unpacking beautifulsoup4
Running setup.py ... egg_info for package
Installing collected packages: beautifulsoup4
Running setup.py install for beautifulsoup4
Successfully installed beautifulsoup4
Cleaning up...
Bam ! |Done¬
csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.
Any two GUIDs are very likely unique (not equal).
See this SO entry, and from Wikipedia
While each generated GUID is not guaranteed to be unique, the total number of unique keys (2^128 or 3.4×10^38) is so large that the probability of the same number being generated twice is very small. For example, consider the observable universe, which contains about 5×10^22 stars; every star could then have 6.8×10^15 universally unique GUIDs.
So probably you have to wait for many more billion of years, and hope that you hit one before the universe as we know it comes to an end.
If you don't want duplicates in a list, use a HashSet
. That way it will be clear to anyone else reading your code what your intention was and you'll have less code to write since HashSet
already handles what you are trying to do.
You can undo your Git commits in two ways:
First is you can use git revert
, if you want to keep your commit history:
git revert HEAD~3
git revert <hashcode of commit>
Second is you can use git reset
, which would delete all your commit history and bring your head to commit where you want it.
git reset <hashcode of commit>
git reset HEAD~3
You can also use the --hard
keyword if any of it starts behaving otherwise. But, I would only recommend it until it's extremely necessary.
In windows batch scripts, %~s1
expands path parameters to short names. Create this batch file:
@ECHO OFF
echo %~s1
I called mine shortNamePath.cmd
and call it like this:
c:\>shortNamePath "c:\Program Files (x86)\Android\android-sdk"
c:\PROGRA~2\Android\ANDROI~1
Edit: here's a version that uses the current directory if no parameter was supplied:
@ECHO OFF
if '%1'=='' (%0 .) else echo %~s1
Called without parameters:
C:\Program Files (x86)\Android\android-sdk>shortNamePath
C:\PROGRA~2\Android\ANDROI~1
If you want absolute urls, you have the third parameter.
$product_url = $this->generateUrl('product_detail',
array(
'slug' => 'slug'
),
UrlGeneratorInterface::ABSOLUTE_URL
);
Remember to include UrlGeneratorInterface.
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
This is my pure HTML & Javascript solution:
var setHeight = function (element, height) {
if (!element) {;
return false;
}
else {
var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10),
toggleButton = document.createElement('a'),
text = document.createTextNode('...Show more'),
parent = element.parentNode;
toggleButton.src = '#';
toggleButton.className = 'show-more';
toggleButton.style.float = 'right';
toggleButton.style.paddingRight = '15px';
toggleButton.appendChild(text);
parent.insertBefore(toggleButton, element.nextSibling);
element.setAttribute('data-fullheight', elementHeight);
element.style.height = height;
return toggleButton;
}
}
var toggleHeight = function (element, height) {
if (!element) {
return false;
}
else {
var full = element.getAttribute('data-fullheight'),
currentElementHeight = parseInt(element.style.height, 10);
element.style.height = full == currentElementHeight ? height : full + 'px';
}
}
var toggleText = function (element) {
if (!element) {
return false;
}
else {
var text = element.firstChild.nodeValue;
element.firstChild.nodeValue = text == '...Show more' ? '...Show less' : '...Show more';
}
}
var applyToggle = function(elementHeight){
'use strict';
return function(){
toggleHeight(this.previousElementSibling, elementHeight);
toggleText(this);
}
}
var modifyDomElements = function(className, elementHeight){
var elements = document.getElementsByClassName(className);
var toggleButtonsArray = [];
for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) {
var currentElement = elements[index];
var toggleButton = setHeight(currentElement, elementHeight);
toggleButtonsArray.push(toggleButton);
}
for (var index=0, arrayLength=toggleButtonsArray.length; index<arrayLength; index++){
toggleButtonsArray[index].onclick = applyToggle(elementHeight);
}
}
You can then call modifyDomElements function to apply text shortening on all the elements that have shorten-text class name. For that you would need to specify the class name and the height that you would want your elements to be shortened to:
modifyDomElements('shorten-text','50px');
Lastly, in your your html, just set the class name on the element you would want your text to get shorten:
<div class="shorten-text">Your long text goes here...</div>
This is a FAQ:
//somexpression[$N]
means "Find every node selected by //somexpression
that is the $N
th child of its parent".
What you want is:
(//input[@id="search_query"])[2]
Remember: The []
operator has higher precedence (priority) than the //
abbreviation.
USE [DATABASE]
DECLARE @USERNAME VARCHAR(500)
DECLARE @STRSQL NVARCHAR(MAX)
SET @USERNAME='[USERNAME] '
SET @STRSQL=''
select @STRSQL+=CHAR(13)+'GRANT EXECUTE ON ['+ s.name+'].['+obj.name+'] TO'+@USERNAME+';'
from
sys.all_objects as obj
inner join
sys.schemas s ON obj.schema_id = s.schema_id
where obj.type in ('P','V','FK')
AND s.NAME NOT IN ('SYS','INFORMATION_SCHEMA')
EXEC SP_EXECUTESQL @STRSQL
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Refer this post: Replacing a fragment with another fragment inside activity group
Actually, your question is how to write a Higher Order Component (HOC). The main goal of using HOC is preventing copy-pasting. You can write your HOC as a purely functional component or as a class here is an example:
class Child extends Component {
render() {
return (
<div>
Child
</div>
);
}
}
If you want to write your parent component as a class-based component:
class Parent extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
If you want to write your parent as a functional component:
const Parent=props=>{
return(
<div>
{props.children}
</div>
)
}
The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.
The question asked is just a type conversion question and here its conversion from int
data type to float
data type and for that you can do it by the function :
float()
And for more details you can visit this page.
A shorter answer from here, adapted to this question:
var arr = $('.requiredText');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Just for completeness.
You should NOT use jQuery('selector').attr("tagName").toLowerCase()
, because it only works in older versions of Jquery.
You could use $('selector').prop("tagName").toLowerCase()
if you're certain that you're using a version of jQuery thats >= version 1.6.
You may think that EVERYONE is using jQuery 1.10+ or something by now (January 2016), but unfortunately that isn't really the case. For example, many people today are still using Drupal 7, and every official release of Drupal 7 to this day includes jQuery 1.4.4 by default.
So if do not know for certain if your project will be using jQuery 1.6+, consider using one of the options that work for ALL versions of jQuery :
Option 1 :
jQuery('selector')[0].tagName.toLowerCase()
Option 2
jQuery('selector')[0].nodeName.toLowerCase()
This does what you want and overcomes some of the problems in other answers:
import matplotlib.pyplot as plt
labels = ["HHZ 1", "HHN", "HHE"]
colors = ["r","g","b"]
f,axs = plt.subplots(3, sharex=True, sharey=True)
# ---- loop over axes ----
for i,ax in enumerate(axs):
axs[i].plot([0,1],[1,0],color=colors[i],label=labels[i])
axs[i].legend(loc="upper right")
plt.show()
It may make things more elegant to wrap it in a property.
string MySessionVar
{
get{
return Session["MySessionVar"] ?? String.Empty;
}
set{
Session["MySessionVar"] = value;
}
}
then you can treat it as a string.
if( String.IsNullOrEmpty( MySessionVar ) )
{
// do something
}
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
For case1:
INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
FROM TAB_TEACHER
WHERE name_teacher = 'Professor Jack'
LIMIT 1
For case2 you just have to do 2 separate insert statements
My solution:
Edit > Past Special > Paste XML As Classes
to get the class in your codeList<class1
>), then use the XmlSerializer
to serialize that list to a xml
file.deserialize
it.Code:
StreamReader sr = new StreamReader(@"C:\Users\duongngh\Desktop\Newfolder\abc.txt");
XmlSerializer xml = new XmlSerializer(typeof(Class1[]));
var a = xml.Deserialize(sr);
sr.Close();
NOTE: you must pay attention to the root name, don't change it. Mine is "ArrayOfClass1"
This should work:
$("label[for='comedyclubs']")
See also: Selectors/attributeEquals - jQuery JavaScript Library
I have been working on Swagger equivalent documentation library called Springfox
nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer
has been implemented by class WebMvcConfigurationSupport
class which we can directly extend.
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
public class WebConfig extends WebMvcConfigurationSupport { }
And this is how I have used it for setting my resource handling mechanism as follows -
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
For a minimal change:
for(int i=0; i<str.Length; i++ )
if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
errorCount++;
You could use regular expressions, at least if speed is not an issue and you do not really need the actual exact count.
echo realpath(dirname(__FILE__));
If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__
with $_SERVER['PHP_SELF']
. But be aware that PHP_SELF is a security risk!