This is written in Kotlin, it will open the maps app if it's found and place the point and let you start the trip:
val gmmIntentUri = Uri.parse("http://maps.google.com/maps?daddr=" + adapter.getItemAt(position).latitud + "," + adapter.getItemAt(position).longitud)
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(mapIntent)
}
Replace requireActivity()
with your Context
.
Is this what you are looking for.
$("input.address_field").on('click', function(){
$(this).css('border', '2px solid red');
});
I like to use the syntax '1 MonthName 2015' for dates ex:
WHERE aa.AuditDate>='1 September 2015'
AND aa.AuditDate<='30 September 2015'
for dates
I got this problem once when I had a single quote as part of the header. When I removed it (i.e. renamed the respective column header from Jimmy's data
to Jimmys data
), the function returned no warnings.
First rule of threading - "Threading is fun"...
I'm not able to understand the flow of execution of the program, And when ob1 is created then the constructor is called where
t.start()
is written but stillrun()
method is not executed rathermain()
method continues execution. So why is this happening?
This is exactly what should happen. When you call Thread#start
, the thread is created and schedule for execution, it might happen immediately (or close enough to it), it might not. It comes down to the thread scheduler.
This comes down to how the thread execution is scheduled and what else is going on in the system. Typically, each thread will be given a small amount of time to execute before it is put back to "sleep" and another thread is allowed to execute (obviously in multiple processor environments, more than one thread can be running at time, but let's try and keep it simple ;))
Threads may also yield
execution, allow other threads in the system to have chance to execute.
You could try
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
// Yield here
Thread.yield();
}
And it might make a difference to the way the threads run...equally, you could sleep
for a small period of time, but this could cause your thread to be overlooked for execution for a period of cycles (sometimes you want this, sometimes you don't)...
join()
method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??
The way you've stated the question is wrong...join
will wait for the Thread
it is called on to die before returning. For example, if you depending on the result of a Thread
, you could use join
to know when the Thread
has ended before trying to retrieve it's result.
Equally, you could poll the thread, but this will eat CPU cycles that could be better used by the Thread
instead...
my way...
const myForm = document.forms['form-name']
myForm.onsubmit=e=>
{
e.preventDefault() // for testing...
let data = Array.from(new FormData(myForm))
.reduce((r,[k,v])=>{r[k]=v;return r},{})
/*_______________________________________ same code: for beginners
let data = {}
Array.from(new FormData(myForm), (entry) => { data[ entry[0] ] = entry[1]} )
________________________________________________________________*/
console.log(data)
//...
}
Couple of other differences:
Abstract classes can have static methods, properties, fields etc. and operators, interfaces can't. Cast operator allows casting to/from abstract class but don't allow casting to/from interface.
So pretty much you can use abstract class on its own even if it is never implemented (through its static members) and you can't use interface on its own in any way.
Git clone is the command you're looking for:
git clone [email protected]:username/repo.git
Update: And this is the official guide: https://help.github.com/articles/fork-a-repo
Take a look at: https://help.github.com/
It has really useful content
The setOnPageChangeListener() method is deprecated. Use addOnPageChangeListener(OnPageChangeListener) instead.
You can use OnPageChangeListener and getting the position inside onPageSelected()
method, this is an example:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.d(TAG, "my position is : " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
Or just use getCurrentItem() to get the real position:
viewPager.getCurrentItem();
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
String u = request.getParameter("username");
String p = request.getParameter("password");
try {
st = con.createStatement();
String sql;
sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
+ p + "'";
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/home.jsp");
requestDispatcher.forward(request, response);
} else {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/invalidLogin.jsp");
requestDispatcher.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
rs.close();
ps.close();
con.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
java.sql.Timestamp
is a subclass of java.util.Date
. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat
and creating Joda DateTime
should be straightforward from this point on.
Here to show equivalent implementation of a flatMap using subscribes.
Without flatMap:
this.searchField.valueChanges.debounceTime(400)
.subscribe(
term => this.searchService.search(term)
.subscribe( results => {
console.log(results);
this.result = results;
}
);
);
With flatMap:
this.searchField.valueChanges.debounceTime(400)
.flatMap(term => this.searchService.search(term))
.subscribe(results => {
console.log(results);
this.result = results;
});
http://plnkr.co/edit/BHGmEcdS5eQGX703eRRE?p=preview
Hope it could help.
Olivier.
Add a property to the form method="post"
.
Like this:
<form name="loginform" method="post">
Assuming you have the following database tables:
First, you need to create the @Embeddable
holding the composite identifier:
@Embeddable
public class EmployeeId implements Serializable {
@Column(name = "company_id")
private Long companyId;
@Column(name = "employee_number")
private Long employeeNumber;
public EmployeeId() {
}
public EmployeeId(Long companyId, Long employeeId) {
this.companyId = companyId;
this.employeeNumber = employeeId;
}
public Long getCompanyId() {
return companyId;
}
public Long getEmployeeNumber() {
return employeeNumber;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EmployeeId)) return false;
EmployeeId that = (EmployeeId) o;
return Objects.equals(getCompanyId(), that.getCompanyId()) &&
Objects.equals(getEmployeeNumber(), that.getEmployeeNumber());
}
@Override
public int hashCode() {
return Objects.hash(getCompanyId(), getEmployeeNumber());
}
}
With this in place, we can map the Employee
entity which uses the composite identifier by annotating it with @EmbeddedId
:
@Entity(name = "Employee")
@Table(name = "employee")
public class Employee {
@EmbeddedId
private EmployeeId id;
private String name;
public EmployeeId getId() {
return id;
}
public void setId(EmployeeId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The Phone
entity which has a @ManyToOne
association to Employee
, needs to reference the composite identifier from the parent class via two @JoinColumn
mappings:
@Entity(name = "Phone")
@Table(name = "phone")
public class Phone {
@Id
@Column(name = "`number`")
private String number;
@ManyToOne
@JoinColumns({
@JoinColumn(
name = "company_id",
referencedColumnName = "company_id"),
@JoinColumn(
name = "employee_number",
referencedColumnName = "employee_number")
})
private Employee employee;
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
You can use something like this :
SELECT
Books.BookTitle,
Books.Edition,
Books.Year,
Books.Pages,
Books.Rating,
Categories.Category,
Publishers.Publisher,
Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.
You can only do this in Javascript/JQuery, you can do it with the following JQuery (assuming you've gave your select an id of multiselect):
$(function () {
$("#multiSelect").css("height", parseInt($("#multiSelect option").length) * 20);
});
A more up to date answer:
allprojects {
repositories {
google() // add this
}
}
And don't forget to update gradle to 4.1+ (in gradle-wrapper.properties):
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
source: https://developer.android.com/studio/build/dependencies.html#google-maven
All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
I believe:
String.Format("{0:0.00}",Sale);
Should do it.
See Link String Format Examples C#
Simon Zeinstra has found the solution!
But, I used Visual Studio community 2015 and I didn't even have to use schema compare.
Using SQL Server Object Explorer, I found my user-defined table type in the DB. I right-mouse clicked on the table-type and selected . This opened a code tab in the IDE with the TSQL code visible and editable. I simply changed the definition (in my case just increased the size of an nvarchar field) and clicked the Update Database button in the top-left of the tab.
Hey Presto! - a quick check in SSMS and the udtt definition has been modified.
Brilliant - thanks Simon.
Here is your simple and easy answer
Go to your class where you want to give a negative margin then copy and paste this inside the class.
Example for negative margin top
mt-n3
Example for negative margin bottom
mb-n2
Short answer no :)
But you could just use the same CSS for the hover like so:
a:hover, .hoverclass {
background:red;
}
Maybe if you explain why you need the class added, there may be a better solution?
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
Name your Interface
what it is. Truck
. Not ITruck
because it isn't an ITruck
it is a Truck
.
An Interface
in Java is a Type. Then you have DumpTruck
, TransferTruck
, WreckerTruck
, CementTruck
, etc that implement Truck
.
When you are using the Interface
in place of a sub-class you just cast it to Truck
. As in List<Truck>
. Putting I
in front is just Hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass
that is tautology just as bad as the IInterface
tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions, could be something like AbstractTruck
. Since only the sub-classes will ever see this and you should never cast to an Abstract
class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck
and use BaseTruck
or DefaultTruck
instead since the abstract
is in the definition. But since Abstract
classes should never be part of any public facing interface I believe it is an acceptable exception to the rule. Making the constructors protected
goes a long way to crossing this divide.
And the Impl
suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl
suffix on every name of every Class?
The Interface
is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck
is a Type of Truck
.
Look to the Java standard library itself. Do you see IList
, ArrayListImpl
, LinkedListImpl
? No, you see List
and ArrayList
, and LinkedList
. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principle as well.
Also, if you find yourself adding DTO
, JDO
, BEAN
or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even internally adhere to in a consistent manner.
If all you can come up with to make your Class
name unique is suffixing it with Impl
, then you need to rethink having an Interface
at all. So when you have a situation where you have an Interface
and a single Implementation
that is not uniquely specialized from the Interface
you probably don't need the Interface
.
Take a look at this:
(reprinted from the expired blog page http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/ based on the archived version at http://web.archive.org/web/20130120010146/http://jamiethompson.co.uk/web/2008/06/17/publish-subscribe-with-jquery/)
June 17th, 2008
With a view to writing a jQuery UI integrated with the offline functionality of Google Gears i’ve been toying with some code to poll for network connection status using jQuery.
The basic premise is very simple. We create an instance of a network detection object which will poll a URL at regular intervals. Should these HTTP requests fail we can assume that network connectivity has been lost, or the server is simply unreachable at the current time.
$.networkDetection = function(url,interval){
var url = url;
var interval = interval;
online = false;
this.StartPolling = function(){
this.StopPolling();
this.timer = setInterval(poll, interval);
};
this.StopPolling = function(){
clearInterval(this.timer);
};
this.setPollInterval= function(i) {
interval = i;
};
this.getOnlineStatus = function(){
return online;
};
function poll() {
$.ajax({
type: "POST",
url: url,
dataType: "text",
error: function(){
online = false;
$(document).trigger('status.networkDetection',[false]);
},
success: function(){
online = true;
$(document).trigger('status.networkDetection',[true]);
}
});
};
};
You can view the demo here. Set your browser to work offline and see what happens…. no, it’s not very exciting.
What is exciting though (or at least what is exciting me) is the method by which the status gets relayed through the application. I’ve stumbled upon a largely un-discussed method of implementing a pub/sub system using jQuery’s trigger and bind methods.
The demo code is more obtuse than it need to be. The network detection object publishes ’status ‘events to the document which actively listens for them and in turn publishes ‘notify’ events to all subscribers (more on those later). The reasoning behind this is that in a real world application there would probably be some more logic controlling when and how the ‘notify’ events are published.
$(document).bind("status.networkDetection", function(e, status){
// subscribers can be namespaced with multiple classes
subscribers = $('.subscriber.networkDetection');
// publish notify.networkDetection even to subscribers
subscribers.trigger("notify.networkDetection", [status])
/*
other logic based on network connectivity could go here
use google gears offline storage etc
maybe trigger some other events
*/
});
Because of jQuery’s DOM centric approach events are published to (triggered on) DOM elements. This can be the window or document object for general events or you can generate a jQuery object using a selector. The approach i’ve taken with the demo is to create an almost namespaced approach to defining subscribers.
DOM elements which are to be subscribers are classed simply with “subscriber” and “networkDetection”. We can then publish events only to these elements (of which there is only one in the demo) by triggering a notify event on $(“.subscriber.networkDetection”)
The #notifier
div which is part of the .subscriber.networkDetection
group of subscribers then has an anonymous function bound to it, effectively acting as a listener.
$('#notifier').bind("notify.networkDetection",function(e, online){
// the following simply demonstrates
notifier = $(this);
if(online){
if (!notifier.hasClass("online")){
$(this)
.addClass("online")
.removeClass("offline")
.text("ONLINE");
}
}else{
if (!notifier.hasClass("offline")){
$(this)
.addClass("offline")
.removeClass("online")
.text("OFFLINE");
}
};
});
So, there you go. It’s all pretty verbose and my example isn’t at all exciting. It also doesn’t showcase anything interesting you could do with these methods, but if anyone’s at all interested to dig through the source feel free. All the code is inline in the head of the demo page
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
open
also has an -a flag, that you can use to open up an app from within the Applications folder by it's name (or by bundle identifier with -b flag). You can combine this with the --args option to achieve the result you want:
open -a APP_NAME --args ARGS
To open up a video in VLC player that should scale with a factor 2x and loop you would for example exectute:
open -a VLC --args -L --fullscreen
Note that I could not get the output of the commands to the terminal. (although I didn't try anything to resolve that)
Using lodash unionWith function, you can accomplish a simple upsert to an object. The documentation states that if there is a match, it will use the first array. Wrap your updated object in [ ] (array) and put it as the first array of the union function. Simply specify your matching logic and if found it will replace it and if not it will add it
Example:
let contacts = [
{type: 'email', desc: 'work', primary: true, value: 'email prim'},
{type: 'phone', desc: 'cell', primary: true, value:'phone prim'},
{type: 'phone', desc: 'cell', primary: false,value:'phone secondary'},
{type: 'email', desc: 'cell', primary: false,value:'email secondary'}
]
// Update contacts because found a match
_.unionWith([{type: 'email', desc: 'work', primary: true, value: 'email updated'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)
// Add to contacts - no match found
_.unionWith([{type: 'fax', desc: 'work', primary: true, value: 'fax added'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)
static const size_t npos = -1;
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type size_t.
This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".
As a return value, it is usually used to indicate no matches.
This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.
$ git remote remove <name>
ie.
$ git remote remove upstream
that should do the trick
Similar to getting the length of a dataframe, len(df)
, the following worked for pandas and blaze:
Total = sum(df['MyColumn'])
or alternatively
Total = sum(df.MyColumn)
print Total
Yes, is possible to dynamically add properties to a PHP object.
This is useful when a partial object is received from javascript.
JAVASCRIPT side:
var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
data: myObject, dataType: "json",
contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});
PHP side:
$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object
OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.
You can add image to asp.net button. you dont need to use only image button or link button. When displaying button on browser, it is converting to html button as default. So you can use its "Style" properties for adding image. My example is below. I hope it works for you.
Style="background-image:url('Image/1.png');"
You can change image location with using
background-repeat
properties. So you can write a button like below:
<asp:Button ID="btnLogin" runat="server" Text="Login" Style="background-image:url('Image/1.png'); background-repeat:no-repeat"/>
Take a look at the library I wrote: https://github.com/tachyons-css/react-native-style-tachyons
It allows you to specify a root-fontSize (rem
) upon start, which you can make dependent of your PixelRatio
or other device-characteristics.
Then you get styles relative to your rem
, not only fontSize, but paddings etc. as well:
<Text style={[s.f5, s.pa2, s.tc]}>
Something
</Text>
Expanation:
f5
is always your base-fontsizepa2
gives you padding relative to your base-fontsize.125 Khz (low-frequency) tags are write-once/read-many, and usually only contain a small (permanent) unique identification number.
13.56 Mhz (high-frequency) tags are usually read/write, they can typically store about 1 to 2 kilbytes of data in addition to their preset (permanent) unique ID number.
860-960 Mhz (ultra-high-frequency) tags are typically read/write and can have much larger information storage capacity (I think that 64 KB is the highest currently available for passive tags) in addition to their preset (permanent) unique ID number.
Most read/write tags can be locked to prevent further writing to specific data-blocks in the tag's internal memory, while leaving other blocks unlocked. Different tag manufacturers make their tags differently, though.
Depending on your intended application, you might have to program your own microcontroller to interface with an embedded RFID read/write module using a manufacturer-specific protocol. That's certainly a lot cheaper than buying a complete RFID read/write unit, as they can cost several thousand dollars. With a custom solution, you can build you own unit that does specifically what you want for as little as $200.
SkyTek - RFID reader manufacturing company (you can buy their products through third-party retailers & wholesalers like Mouser)
Trossen Robotics - You can buy RFID tags and readers (125 Khz & 13.56 Mhz) from here, among other things
I think it will help you
Use git checkout
instead of git stash apply
:
$ git checkout stash -- .
$ git commit
This will restore all the files in the current directory to their stashed version.
If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:
$ git merge --squash --strategy-option=theirs stash
If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using
$ git checkout stash -- <paths...>
or interactively with
$ git checkout -p stash
Push annotated tags, keep lightweight local
man git-tag
says:
Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.
And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:
annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.
Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.
git describe
without command line options only sees annotated tagsInternals differences
both lightweight and annotated tags are a file under .git/refs/tags
that contains a SHA-1
for lightweight tags, the SHA-1 points directly to a commit:
git tag light
cat .git/refs/tags/light
prints the same as the HEAD's SHA-1.
So no wonder they cannot contain any other metadata.
annotated tags point to a tag object in the object database.
git tag -as -m msg annot
cat .git/refs/tags/annot
contains the SHA of the annotated tag object:
c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
and then we can get its content with:
git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
sample output:
object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
type commit
tag annot
tagger Ciro Santilli <[email protected]> 1411478848 +0200
msg
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
<YOUR PGP SIGNATURE>
-----END PGP SIGNAT
And this is how it contains extra metadata. As we can see from the output, the metadata fields are:
A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?
Bonuses
Determine if a tag is annotated:
git cat-file -t tag
Outputs
commit
for lightweight, since there is no tag object, it points directly to the committag
for annotated, since there is a tag object in that caseList only lightweight tags: How can I list all lightweight tags?
The cloud services provides a range of options from fully managed to less managed services. Less managed services gives more control to the developers. The same is the difference in Compute and App engine also. The below image elaborate more on this point
try this,
mongoimport --db dbName --collection collectionName <fileName.json
Example,
mongoimport --db foo --collection myCollections < /Users/file.json
connected to: *.*.*.*
Sat Mar 2 15:01:08 imported 11 objects
Issue is because of you date format.
I used same JSON with modified date as below and it worked
{jobID:"2597401",
account:"XXXXX",
user:"YYYYY",
pkgT:{"pgi/7.2-5":{libA:["libpgc.so"],flavor:["default"]}},
startEpoch:"1338497979",
runTime:"1022",
execType:"user:binary",
exec:"/share/home/01482/XXXXX/appker/ranger/NPB3.3.1/NPB3.3-MPI/bin/ft.D.64",
numNodes:"4",
sha1:"5a79879235aa31b6a46e73b43879428e2a175db5",
execEpoch:1336766742,
execModify:{"$date" : 1343779200000},
startTime:{"$date" : 1343779200000},
numCores:"64",
sizeT:{bss:"1881400168",text:"239574",data:"22504"}}
hope this helps
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
We run similar standards, when scripting we demand [ ] around names, and where appropriate schema qualifiers - primarily it hedges your bets against future name grabs by the SQL syntax.
SELECT [Name] FROM [dbo].[Customer] WHERE [Location] = 'WA'
This has saved our souls in the past - some of our database systems have run 10+ years from SQL 6.0 through SQL 2005 - way past their intended lifespans.
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
Radiff2 is a tool designed to compare binary files, similar to how regular diff compares text files.
Try radiff2
which is a part of radare2
disassembler. For instance, with this command:
radiff2 -x file1.bin file2.bin
You get pretty formatted two columns output where differences are highlighted.
I posted my solution at Python implementation of "median of medians" algorithm , which is a little bit faster than using sort(). My solution uses 15 numbers per column, for a speed ~5N which is faster than the speed ~10N of using 5 numbers per column. The optimal speed is ~4N, but I could be wrong about it.
Per Tom's request in his comment, I added my code here, for reference. I believe the critical part for speed is using 15 numbers per column, instead of 5.
#!/bin/pypy
#
# TH @stackoverflow, 2016-01-20, linear time "median of medians" algorithm
#
import sys, random
items_per_column = 15
def find_i_th_smallest( A, i ):
t = len(A)
if(t <= items_per_column):
# if A is a small list with less than items_per_column items, then:
#
# 1. do sort on A
# 2. find i-th smallest item of A
#
return sorted(A)[i]
else:
# 1. partition A into columns of k items each. k is odd, say 5.
# 2. find the median of every column
# 3. put all medians in a new list, say, B
#
B = [ find_i_th_smallest(k, (len(k) - 1)/2) for k in [A[j:(j + items_per_column)] for j in range(0,len(A),items_per_column)]]
# 4. find M, the median of B
#
M = find_i_th_smallest(B, (len(B) - 1)/2)
# 5. split A into 3 parts by M, { < M }, { == M }, and { > M }
# 6. find which above set has A's i-th smallest, recursively.
#
P1 = [ j for j in A if j < M ]
if(i < len(P1)):
return find_i_th_smallest( P1, i)
P3 = [ j for j in A if j > M ]
L3 = len(P3)
if(i < (t - L3)):
return M
return find_i_th_smallest( P3, i - (t - L3))
# How many numbers should be randomly generated for testing?
#
number_of_numbers = int(sys.argv[1])
# create a list of random positive integers
#
L = [ random.randint(0, number_of_numbers) for i in range(0, number_of_numbers) ]
# Show the original list
#
# print L
# This is for validation
#
# print sorted(L)[int((len(L) - 1)/2)]
# This is the result of the "median of medians" function.
# Its result should be the same as the above.
#
print find_i_th_smallest( L, (len(L) - 1) / 2)
Use Not IsNull(Fields!W_O_Count.Value)
Many of the answers here are out of date for 2015 (although the initially accepted one from Daniel Roseman is not). Here's the current state of things:
.whl
files)—not just on PyPI, but in third-party repositories like Christoph Gohlke's Extension Packages for Windows. pip
can handle wheels; easy_install
cannot.virtualenv
) have become a very important and prominent tool (and recommended in the official docs); they include pip
out of the box, but don't even work properly with easy_install
.distribute
package that included easy_install
is no longer maintained. Its improvements over setuptools
got merged back into setuptools
. Trying to install distribute
will just install setuptools
instead.easy_install
itself is only quasi-maintained.pip
used to be inferior to easy_install
—installing from an unpacked source tree, from a DVCS repo, etc.—are long-gone; you can pip install .
, pip install git+https://
.pip
comes with the official Python 2.7 and 3.4+ packages from python.org, and a pip
bootstrap is included by default if you build from source.pip
as "the preferred installer program".pip
over the years that will never be in easy_install
. For example, pip
makes it easy to clone your site-packages by building a requirements file and then installing it with a single command on each side. Or to convert your requirements file to a local repo to use for in-house development. And so on.The only good reason that I know of to use easy_install
in 2015 is the special case of using Apple's pre-installed Python versions with OS X 10.5-10.8. Since 10.5, Apple has included easy_install
, but as of 10.10 they still don't include pip
. With 10.9+, you should still just use get-pip.py
, but for 10.5-10.8, this has some problems, so it's easier to sudo easy_install pip
. (In general, easy_install pip
is a bad idea; it's only for OS X 10.5-10.8 that you want to do this.) Also, 10.5-10.8 include readline
in a way that easy_install
knows how to kludge around but pip
doesn't, so you also want to sudo easy_install readline
if you want to upgrade that.
Try This code:
public class GenericCompare<T> : IEqualityComparer<T> where T : class
{
private Func<T, object> _expr { get; set; }
public GenericCompare(Func<T, object> expr)
{
this._expr = expr;
}
public bool Equals(T x, T y)
{
var first = _expr.Invoke(x);
var sec = _expr.Invoke(y);
if (first != null && first.Equals(sec))
return true;
else
return false;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
Example of its use would be
collection = collection
.Except(ExistedDataEles, new GenericCompare<DataEle>(x=>x.Id))
.ToList();
Google is my friend and it showed me this page:
I found this useful to read from a specific column and row:
FileStream stream = File.Open(@"C:\Users\Desktop\ExcelDataReader.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.IsFirstRowAsColumnNames = true;
DataTable dt = result.Tables[0];
string text = dt.Rows[1][0].ToString();
Please give a try:
\Q and \E as anchors
Put an Or condition to match either a full word or regex.
Ref Link : How to match a whole word that includes special characters in regex
This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
//ADD THESE, BECAUSE ASP.NET is Expecting them for validation
//Even if they are empty you will be able to post the file
[request setPostValue:@"" forKey:@"__VIEWSTATE"];
[request setPostValue:@"" forKey:@"__EVENTVALIDATION"];
///
[request setFile:FIleName forKey:@"fileupload_control_Name"];
[request startSynchronous];
In newer versions of Git for Windows, Bash is started with --login
which causes Bash to not read .bashrc
directly. Instead it reads .bash_profile
.
If this file does not exist, create it with the following content:
if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
This will cause Bash to read the .bashrc
file. From my understanding of this issue, Git for Windows should do this automatically. However, I just installed version 2.5.1, and it did not.
You can also put the files or links into the root of the solution explorer and then set the files properties:
Build action = Content
and
Copy to Output Directory = Copy if newer
(for example)
For a link drag the file from the windows explorer into the solution explorer holding down the shift and control keys.
Also can use without parent
say router definition like:
{path:'/about', name: 'About', component: AboutComponent}
then can navigate by name
instead of path
goToAboutPage() {
this.router.navigate(['About']); // here "About" is name not path
}
Updated for V2.3.0
In Routing from v2.0 name property no more exist. route define without name property. so you should use path instead of name. this.router.navigate(['/path'])
and no leading slash for path so use path: 'about'
instead of path: '/about'
router definition like:
{path:'about', component: AboutComponent}
then can navigate by path
goToAboutPage() {
this.router.navigate(['/about']); // here "About" is path
}
You can do this:
//first get all the <a> elements
List<WebElement> linkList=driver.findElements(By.tagName("a"));
//now traverse over the list and check
for(int i=0 ; i<linkList.size() ; i++)
{
if(linkList.get(i).getAttribute("href").contains("long"))
{
linkList.get(i).click();
break;
}
}
in this what we r doing is first we are finding all the <a>
tags and storing them in a list.After
that we are iterating the list one by one to find <a>
tag whose href attribute contains long string. And then we click on that particular <a>
tag and comes out of the loop.
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
If you do not want to use jQuery, make the button type a normal button and add a click listener pointing to the function you would like to execute, and send the form in as a parameter. The button would be as follows:
<button (click)="yourSubmitFunction(yourForm)" [disabled]="!yourForm.valid" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
Remember to remove: (ngSubmit)="yourSubmitFunction(yourForm)"
from the form div if you use this method.
If the directory ../.foo/bar/
doesn't exist, you can't create a file there, so make sure you create the directory first.
Try something like this:
File f = new File("somedirname1/somedirname2/somefilename");
if (!f.getParentFile().exists())
f.getParentFile().mkdirs();
if (!f.exists())
f.createNewFile();
From jQuery.ajax()
async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
So in your request, you must do async: false
instead of async: "false"
.
Update:
The return value of ajaxSubmit
is not the return value of the success: function(){...}
. ajaxSubmit
returns no value at all, which is equivalent to undefined
, which in turn evaluates to true.
And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.
If you want to submit the form only, when the response is "Successful"
, you must return false
from ajaxSubmit
and then submit the form in the success
function, as @halilb already suggested.
Something along these lines should work
function ajaxSubmit() {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
url: "checkpass.php",
data: "password="+password,
success: function(response) {
if(response == "Successful")
{
$('form').removeAttr('onsubmit'); // prevent endless loop
$('form').submit();
}
}
});
return false;
}
One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object
to collect values, and make use of Object#tap
to get rid of temporary variable that is otherwise needed for nil
check on result of process_x
method.
items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}
Complete example for illustration:
items = [1,2,3,4,5]
def process x
rand(10) > 5 ? nil : x
end
items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}
Alternate approach:
By looking at the method you are calling process_x url
, it is not clear what is the purpose of input x
in that method. If I assume that you are going to process the value of x
by passing it some url
and determine which of the x
s really get processed into valid non-nil results - then, may be Enumerabble.group_by
is a better option than Enumerable#map
.
h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
#=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}
h["Good"]
#=> [3,4,5]
If you have your github setup in some sort of online syncing service, such as google drive or dropbox, try disabling the syncing as the syncing service tries to read/write to the file as github tries to do the same, leading to github not working correctly.
I had the exact same problem, and it was fixed by doing a chmod 777 /dev/ttyUSB0
. I never had this error again, even though previously the only way to get it to work was to reboot the VM or unplug and replug the USB-to-serial adapter. I am running Ubuntu 10.04 (Lucid Lynx) VM on OS X.
The web site likely uses cookies to store your session information. When you run
curl --user user:pass https://xyz.com/a #works ok
curl https://xyz.com/b #doesn't work
curl
is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a
in one browser session, and tried to access page b
in a different one.
What you need to do is save the cookies created by the first command:
curl --user user:pass --cookie-jar ./somefile https://xyz.com/a
and then read them back in when running the second:
curl --cookie ./somefile https://xyz.com/b
Alternatively you can try downloading both files in the same command, which I think will use the same cookies.
You should set android:button="@null"
instead of "null"
.
You were soo close!
I had the same problem
I fixed that by using two options
contentType: false
processData: false
Actually I Added these two command to my $.ajax({}) function
I found the answer. IE stores passwords in two different locations based on the password type:
%APPDATA%\Microsoft\Credentials
, in encrypted filesHKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
, encrypted with the urlFrom a very good page on NirSoft.com:
Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:
AutoComplete Passwords: These passwords are saved in the following location in the Registry:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).HTTP Authentication Passwords: These passwords are stored in the Credentials file under
Documents and Settings\Application Data\Microsoft\Credentials
, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.
In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead
/CredWrite
, where the user can manage their passwords from within an established UI system in Windows.
pch=20 returns a symbol sized between "." and 19.
It's a filled symbol (which is probably what you want).
Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,
dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)
with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
ann=F, bg="steelblue2", fg=NULL))
Put each line in cmd or all of theme in the batch file:
@echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
"Put your command here"
it works fine for me.
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
Perhaps the best two browser techs for this are Canvas, with Flash as a back up.
We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.
With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.
It does not work in uniform way in all browsers. I went to to: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_pulpitimage and added style for zoom and -moz-transform. I ran the same code on firefox, IE and chrome and got 3 different results.
<html>
<style>
body{zoom:3;-moz-transform: scale(3);}
</style>
<body>
<h2>Norwegian Mountain Trip</h2>
<img border="0" src="/images/pulpit.jpg" alt="Pulpit rock" />
</body>
</html>
When you want to pass new information to your application, you need to use POST form. In Razor you can use the following
View Code:
@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
@Html.Hidden("id", Model.Id)
@Html.Hidden("productid", Model.ProductId)
@Html.TextBox("qty", Model.Quantity)
@Html.TextBox("unitrate", Model.UnitRate)
<input type="submit" value="Update" />
}
Controller's actions
[HttpGet]
public ActionResult Update(){
//[...] retrive your record object
return View(objRecord);
}
[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
if (ModelState.IsValid){
int _records = UpdatePrice(id,productid,qty,unitrate);
if (_records > 0){ {
return RedirectToAction("Index1", "Shopping");
}else{
ModelState.AddModelError("","Can Not Update");
}
}
return View("Index1");
}
Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity)
you can either have an input with the name (respectecting case) "Quantity"
or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:
Model
public class Record {
public string Id { get; set; }
public string ProductId { get; set; }
public string Quantity { get; set; }
public decimal UnitRate { get; set; }
}
View
@using(Html.BeginForm("Update")){
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.ProductId)
@Html.TextBoxFor(model=> model.Quantity)
@Html.TextBoxFor(model => model.UnitRate)
<input type="submit" value="Update" />
}
Post Action
[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well
if(TryValidateModel(rec)){
//update code
}
return View("Index1");
}
A relatively newer (de)compression tool you might want to consider is zstandard. It does an excellent job of utilizing spare cores, and it has made some great trade-offs when it comes to compression ratio vs. (de)compression time. It is also highly tweak-able depending on your compression ratio needs.
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
After Laravel 5.5 you can use now() function to get the current date and time.
In blade file, you can write like this to print date.
{{ now()->toDateTimeString('Y-m-d') }}
I was facing the same situation.
I begin by declaring the structures I need:
Set<String> myKeysInSet = null;
String[] myArrayOfString = null;
In my case, I have a JSON object and I need all the keys in this JSON to be stored in an array of strings. Using the GSON library, I use JSON.keySet() to get the keys and move to my Set :
myKeysInSet = json_any.keySet();
With this, I have a Set structure with all the keys, as I needed it. So I just need to the values to my Array of Strings. See the code below:
myArrayOfString = myKeysInSet.toArray(new String[myKeysInSet.size()]);
This was my first answer in StackOverflow. Sorry for any error :D
ssh-keygen -t rsa
When asked for a passphrase ,leave it blank i.e, just press enter. as simple as that!!
The Html Agility Pack has been mentioned before - if you are going for speed, you might also want to check out the Majestic-12 HTML parser. Its handling is rather clunky, but it delivers a really fast parsing experience.
Maybe just a bit of trivia, but UPnP will use HTTP formatted messages over UDP for device discovery.
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
Only second approach will work. You can modify collection during iteration using iterator.remove()
only. All other attempts will cause ConcurrentModificationException
.
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:
http://www.backtrack-linux.org/wiki/index.php/Java_Install
root@bt:~# killall -9 /opt/firefox/firefox-bin
root@bt:~# mkdir /opt/java
root@bt:~# mv -f jre1.7.0_05/ /opt/java/
root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1
root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java
root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"
For Java 7 (32 bit)
root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/
For Java 8 (64 bit)
root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/
root@bt:~# firefox http://java.com/en/download/testjava.jsp
Yes, you can do this in one line (though for robust IOException
handling you wouldn't want to).
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);
This uses a java.util.Scanner
, telling it to delimit the input with \Z
, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next()
.
There is a constructor that takes a File
and a String charSetName
(among many other overloads). These two constructor may throw FileNotFoundException
, but like all Scanner
methods, no IOException
can be thrown beyond these constructors.
You can query the Scanner
itself through the ioException()
method if an IOException
occurred or not. You may also want to explicitly close()
the Scanner
after you read the content, so perhaps storing the Scanner
reference in a local variable is best.
For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:
com.google.common.io.Files
contains many useful methods. The pertinent ones here are:
String toString(File, Charset)
String
List<String> readLines(File, Charset)
List<String>
, one entry per lineorg.apache.commons.io.IOUtils
also offer similar functionality:
String toString(InputStream, String encoding)
InputStream
as a String
List readLines(InputStream, String encoding)
List
of String
, one entry per lineimport urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)
In Python v3 the "urllib.request" is a module by itself, therefore "urllib" cannot be used here.
Javascript doesn't have "associative arrays" the way you're thinking of them. Instead, you simply have the ability to set object properties using array-like syntax (as in your example), plus the ability to iterate over an object's properties.
The upshot of this is that there is no guarantee as to the order in which you iterate over the properties, so there is nothing like a sort for them. Instead, you'll need to convert your object properties into a "true" array (which does guarantee order). Here's a code snippet for converting an object into an array of two-tuples (two-element arrays), sorting it as you describe, then iterating over it:
var tuples = [];
for (var key in obj) tuples.push([key, obj[key]]);
tuples.sort(function(a, b) {
a = a[1];
b = b[1];
return a < b ? -1 : (a > b ? 1 : 0);
});
for (var i = 0; i < tuples.length; i++) {
var key = tuples[i][0];
var value = tuples[i][1];
// do something with key and value
}
You may find it more natural to wrap this in a function which takes a callback:
function bySortedValue(obj, callback, context) {_x000D_
var tuples = [];_x000D_
_x000D_
for (var key in obj) tuples.push([key, obj[key]]);_x000D_
_x000D_
tuples.sort(function(a, b) {_x000D_
return a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0_x000D_
});_x000D_
_x000D_
var length = tuples.length;_x000D_
while (length--) callback.call(context, tuples[length][0], tuples[length][1]);_x000D_
}_x000D_
_x000D_
bySortedValue({_x000D_
foo: 1,_x000D_
bar: 7,_x000D_
baz: 3_x000D_
}, function(key, value) {_x000D_
document.getElementById('res').innerHTML += `${key}: ${value}<br>`_x000D_
});
_x000D_
<p id='res'>Result:<br/><br/><p>
_x000D_
list = ["my", "name", "is", "kourosh"]
" ".join(list)
If this is an input, using the JOIN method, we can add the distance between the words and also convert the list to the string.
This is Python output
'my name is kourosh'
To send json to the server, you first have to create json
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
name:"Bob",
...
}),
dataType: 'json'
});
}
This is how you would structure the ajax request to send the json as a post var.
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
data: { json: JSON.stringify({
name:"Bob",
...
})},
dataType: 'json'
});
}
The json will now be in the json
post var.
This simple method solved the problem for me: Copy the content of your dataset, open an empty Excel sheet, choose "Paste Special" -> "Values", and save. Import the new file instead.
(I tried all the existing solutions, and none worked for me. My old dataset appeared to have no missing values, space, special characters, or embedded formulas.)
I had this problem even after setting the config properly. git config
My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).
You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().
http://www.php.net/manual/en/reflectionclass.getdoccomment.php
My problem in Android 9 was navigating on a webview over domains with http The solution from this answer
<application
android:networkSecurityConfig="@xml/network_security_config"
...>
and:
res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
I had the same problem. the other answers are correct but there is another solution. you can set response header to allow cross-origin access. according to this post you have to add the following codes before any app.get call:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
this worked for me :)
I'm not up on my PowerShell syntax, but I think you could just call System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion(). This will return the version as a string (something like v2.0.50727
, I think).
Use the /i with xcopy and if the directory doesn't exist it will create the directory for you.
Basically this is what you need to do:
in the first activity:
Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);
and in the second activtiy:
Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);
one of the get-functions will give return you the value, depending on the datatype you are passing through.
There are many ways to tackle a problem like this. There are many ways to do this. I'm going to give you the most simple solution to this question I know. When changing the text of a label or any kind of wiget really. I would do it like this.
Name_Of_Label["text"] = "Your New Text"
So when I apply this knowledge to your code. It would look something like this.
from tkinter import*
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
#self.fram1 = Frame(self.__mainWindow)
self.labelText = 'Enter amount to deposit'
self.depositLabel = Label(self.__mainWindow, text = self.labelText)
self.depositEntry = Entry(self.__mainWindow, width = 10)
self.depositEntry.bind('<Return>', self.depositCallBack)
self.depositLabel.pack()
self.depositEntry.pack()
mainloop()
def depositCallBack(self,event):
self.labelText["text"] = 'change the value'
print(self.labelText)
myGUI = MyGUI()
If this helps please let me know!
Why was the problem: As someone already specified: If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.
I was observing this problem when I was trying to create byte[] from a pdf file and then converting it to String and then taking the String as input and converting back to file.
So make sure your encoding and decoding logic is same as I did. I explicitly encoded the byte[] to Base64 and decoded it to create the file again.
Use-case:
Due to some limitation I was trying to sent byte[]
in request(POST)
and the process was as follows:
PDF File >> Base64.encodeBase64(byte[]) >> String >> Send in request(POST) >> receive String >> Base64.decodeBase64(byte[]) >> create binary
Try this and this worked for me..
File file = new File("filePath");
byte[] byteArray = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(byteArray);
String byteArrayStr= new String(Base64.encodeBase64(byteArray));
FileOutputStream fos = new FileOutputStream("newFilePath");
fos.write(Base64.decodeBase64(byteArrayStr.getBytes()));
fos.close();
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
}
catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:
.clear { height: 50px; width: 25px; }
Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both;
attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:
.clear { clear: both; }
Here's a variation, using the version of fs
that uses promises:
const fs = require('fs');
await fs.promises.writeFile('../data/phraseFreqs.json', JSON.stringify(output)); // UTF-8 is default
The following should do what you want:
x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
$(document).ready(function () {_x000D_
var url = window.location;_x000D_
$('ul.nav a[href="' + url + '"]').parent().addClass('active');_x000D_
$('ul.nav a').filter(function () {_x000D_
return this.href == url;_x000D_
}).parent().addClass('active').parent().parent().addClass('active');_x000D_
});_x000D_
_x000D_
This works perfectly
_x000D_
You can use Janel. This last works as an application launcher or service launcher (available from 4.x).
One possible reason here might be your script have wrong shebang (so it is not using python from your virtualenv). I just did this change and it works:
-#!/bin/python
+#!/usr/bin/env python
Or ignore shebang and just run the script with python in your venv:
$ python your_script.py
If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that
@Component
public class SuggestionService {
declares a bean of type SuggestionService
, and of name suggestionService
. It's equivalent to
@Component("suggestionService")
public class SuggestionService {
or to
<bean id="suggestionService" .../>
You're redefining another bean of the same type, but with a different name, in the XML:
<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
...
</bean>
So, either specify the name of the bean in the annotation to be SuggestionService
, or use the ID suggestionService
in the XML (don't forget to also modify the <ref>
element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.
I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...)
but it would not work in my case.
I actually had a String
in a JSON format, but I feel like it is literally transforming the toString()
method of every field into JSON. In my case, a date LocalDate
field would end up as:
"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}
which is not the best date format to send in a request ...
In the end, the simplest solution in my case is to use the Spring ObjectMapper
. Its behaviour is better since it uses Jackson to build your JSON with complex types.
@Autowired
private ObjectMapper objectMapper;
and I simply used it in mytest:
mockMvc.perform(post("/api/")
.content(objectMapper.writeValueAsString(...))
.contentType(MediaType.APPLICATION_JSON)
);
Use a ListIterator to iterate through the Collection. If the Collection is not a List to start with use Arrays.asList(Collection.toArray())
to turn it into a List first.
\d{1,2}[\,\.]{1}\d{1,2}
EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan
^[0-9]{1,2}([,.][0-9]{1,2})?$
Try This:
Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
When 0 Then LTrim (race_description)
Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation
from tbl_races
Updated answer for 2019 - the cocoa pods team moved to using their own CDN which solves this issue, which was due to GitHub rate limiting, as described here: https://blog.cocoapods.org/CocoaPods-1.7.2/
TL;DR
You need to change the source line in your Podfile
to this:
source 'https://cdn.cocoapods.org/'
if you press x, x amount of times you will get the division of the checkbox by y which results into a jquery boxcheck which would be an invalid way to do this kind of thing. I hope you will have a look at this before using the .on() functions
Based on multiple comments from stackoverflow, scikit-learn documentation and some other, I made a python package to plot ROC curve (and other metric) in a really simple way.
To install package : pip install plot-metric
(more info at the end of post)
To plot a ROC Curve (example come from the documentation) :
Let's load a simple dataset and make a train & test set :
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, n_classes=2, weights=[1,1], random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=2)
Train a classifier and predict test set :
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=50, random_state=23)
model = clf.fit(X_train, y_train)
# Use predict_proba to predict probability of the class
y_pred = clf.predict_proba(X_test)[:,1]
You can now use plot_metric to plot ROC Curve :
from plot_metric.functions import BinaryClassification
# Visualisation with plot_metric
bc = BinaryClassification(y_test, y_pred, labels=["Class 1", "Class 2"])
# Figures
plt.figure(figsize=(5,5))
bc.plot_roc_curve()
plt.show()
You can find more example of on the github and documentation of the package:
You could have done a:
git add -u -n
To check which files you modified and are going to be added (dry run: -n option), and then
git add -u
To add just modified files
i'm using arrayadpter ,using this follwed code i'm able to get items
String value = (String)adapter.getItemAtPosition(position);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String string=adapter.getItem(position);
Log.d("**********", string);
}
});
This probably should be a comment under the cmdow.exe
answer, but here is a simple batch file I wrote to allow for fairly sophisticated and simple control over all windows that you can see in the taskbar.
First step is to run cmdow /t
to display a list of those windows. Look at what the image name is in the column Image
, then command line:
mycmdowscript.cmd imagename
Here are the contents of the batch file:
:: mycmdowscript.cmd
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET IMAGE=%1
SET ACTION=/%2
SET REST=1
SET PARAMS=
:: GET ANY ADDITIONAL PARAMS AND STORE THEM IN A VARIABLE
FOR %%I in (%*) DO (
IF !REST! geq 3 (
SET PARAMS=!PARAMS! %%I
)
SET /A REST+=1
)
FOR /F "USEBACKQ tokens=1,8" %%I IN (`CMDOW /t`) DO (
IF %IMAGE%==%%J (
:: you now have access to the handle in %%I
cmdow %%I %ACTION% !PARAMS!
)
)
ENDLOCAL
@echo on
EXIT /b
example usage
:: will set notepad to 500 500
mycmdowscript.cmd notepad siz 500 500
You could probably rewrite this to allow for multiple actions on a single command, but I haven't tried yet.
For this to work, cmdow.exe must be located in your path. Beware that when you download this, your AV program might yell at you. This tool has (I guess) in the past been used by malware authors to manipulate windows. It is not harmful by itself.
Use PaulGuo's jSQL, a SQL like database using javascript. For example:
var db = new jSQL();
db.create('dbname', testListData).use('dbname');
var data = db.select('*').where(function(o) {
return o.name == 'Jacking';
}).listAll();
Spring MVC and Spring Boot are exist for the different purpose. So, it is not wise to compare each other as the contenders.
What is Spring Boot?
Spring Boot is a framework for packaging the spring application with sensible defaults. What does this mean?. You are developing a web application using Spring MVC, Spring Data, Hibernate and Tomcat. How do you package and deploy this application to your web server. As of now, we have to manually write the configurations, XML files, etc. for deploying to web server.
Spring Boot does that for you with Zero XML configuration in your project. Believe me, you don't need deployment descriptor, web server, etc. Spring Boot is magical framework that bundles all the dependencies for you. Finally your web application will be a standalone JAR file with embeded servers.
If you are still confused how this works, please read about microservice framework development using spring boot.
What is Spring MVC?
It is a traditional web application framework that helps you to build web applications. It is similar to Struts framework.
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control, Dependency Injection.
A Spring MVC provides an elegant solution to use MVC in spring framework by the help of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request and maps it to the right resource such as controllers, models, and views.
I hope this helps you to understand the difference.
You can use the following to generate a number between 1 and an upper limit.
Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1
Here is a specific example:
Example - Generate pseudo random numbers in the range 1 to 600:
Math.abs(new Random().nextInt() % 600) + 1
This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.
If you want to use a lower bound that is not equal to 1 then you can use the following formula.
Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]
Here is a specific example:
Example - Generate pseudo random numbers in the range of 40 to 99:
Math.abs( new Random().nextInt() % (99 - 40) ) + 40
This will generate a random number within a range of 40 and 99.
In some cases, it's easily to deal with a null
than an exception. In particular, the coalescing operator is handy:
SomeClass someObject = (obj as SomeClass) ?? new SomeClass();
It also simplifies code where you are (not using polymorphism, and) branching based on the type of an object:
ClassA a;
ClassB b;
if ((a = obj as ClassA) != null)
{
// use a
}
else if ((b = obj as ClassB) != null)
{
// use b
}
As specified on the MSDN page, the as
operator is equivalent to:
expression is type ? (type)expression : (type)null
which avoids the exception completely in favour of a faster type test, but also limits its use to types that support null
(reference types and Nullable<T>
).
You do not need to install or update any software for the JUnit. it is the part of Java Development tools and comes with almost most of the latest versions in Eclipse.
Go to your project. Right click onto that->Select buildpath->add library->select JUnit from the list ->select the version you want to work with-> done
build you project again to see the errors gone:)
You passed an argument to a function which didn't take any. For example:
def takes_no_arguments
end
takes_no_arguments 1
# ArgumentError: wrong number of arguments (1 for 0)
Your first formulation, image_url('logo.png')
, is correct. If the image is found, it will generate the path /assets/logo.png
(plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png
.
The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png
.
If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets
from your project directory and restart the server (webrick, etc.).
If that fails, you can also try just using background-image: url(logo.png);
That will cause your CSS to look for files with the same relative path (which in this case is /assets).
Based on @Ross's answer answer for Chart.js 2.0 and up, I had to include a little tweak to guard against the case when the bar's heights comes too chose to the scale boundary.
The animation
attribute of the bar chart's option:
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
ctx.fillStyle = '#444';
var y_pos = model.y - 5;
// Make sure data value does not get overflown and hidden
// when the bar's value is too close to max value of scale
// Note: The y value is reverse, it counts from top down
if ((scale_max - model.y) / scale_max >= 0.93)
y_pos = model.y + 20;
ctx.fillText(dataset.data[i], model.x, y_pos);
}
});
}
}
You can enable annotation processors in IntelliJ via the following:
in javascript return statement only used inside function block. if you try to use return statement inside independent if else block it trigger syntax error : Illegal return statement in JavaScript
Here is my example code to avoid such error :
<script type = 'text/javascript'>
(function(){
var ss= 'no';
if(getStatus(ss)){
alert('Status return true');
}else{
alert('Status return false');
}
function getStatus(ask){
if(ask=='yes')
{
return true;
}
else
{
return false;
}
}
})();
</script>
Please check Jsfiddle example
This question is old, but is missing some benchmarks. I benchmarked JOIN against its 2 competitors:
WHERE IN(...)
or equivalentThe result is clear: on MySQL, JOIN
is much faster. N+1 queries can drop the performance of an application drastically:
That is, unless you select a lot of records that point to a very small number of distinct, foreign records. Here is a benchmark for the extreme case:
This is very unlikely to happen in a typical application, unless you're joining a -to-many relationship, in which case the foreign key is on the other table, and you're duplicating the main table data many times.
Takeaway:
JOIN
See my article on Medium for more information.
echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"
-n suppress printing
s substitute
^.* anything at the beginning
- up until the dash
\s* any space characters (any whitespace character)
\( start capture group
\S* any non-space characters
\) end capture group
.*$ anything at the end
\1 substitute 1st capture group for everything on line
p print it
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
I wrote an article on topis how to [manually install curl on debian linu][1]x.
[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:
And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.
source='your token _here0@df and maybe _here1@df or maybe _here2@df'
start_sep='_'
end_sep='@df'
result=[]
tmp=source.split(start_sep)
for par in tmp:
if end_sep in par:
result.append(par.split(end_sep)[0])
print result
must show: here0, here1, here2
the regex is better but it will require additional lib an you may want to go for python only
JavaScript Promises actually use callback functions to determine what to do after a Promise has been resolved or rejected, therefore both are not fundamentally different. The main idea behind Promises is to take callbacks - especially nested callbacks where you want to perform a sort of actions, but it would be more readable.
Alternatively you could update brew
by installing it again. (Think I did this as El Capitan changed something)
Note: this is a heavy handed approach that will remove all applications installed via brew!
Try to install brew a fresh and it will tell how to uninstall.
At original time of writing to uninstall:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Edit: As of 2020 to uninstall:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"
In js you can change zoom by
document.body.style.zoom="90%"
But it doesn't work in FF http://caniuse.com/#search=zoom
For ff you can try
-moz-transform: scale(0.9);
And check next topic How can I zoom an HTML element in Firefox and Opera?
public static String fmt(double d) {
String val = Double.toString(d);
String[] valArray = val.split("\\.");
long valLong = 0;
if(valArray.length == 2) {
valLong = Long.parseLong(valArray[1]);
}
if (valLong == 0)
return String.format("%d", (long) d);
else
return String.format("%s", d);
}
I had to use this because d == (long)d
was giving me violation in a SonarQube report.
@Alex Martelli
's answer is great!
But it work only for one element at time (WHERE name = 'Joan'
)
If you take out the WHERE
clause, the query will return all the root rows together...
I changed a little bit for my situation, so it can show the entire tree for a table.
table definition:
CREATE TABLE [dbo].[mar_categories] (
[category] int IDENTITY(1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[level] int NOT NULL,
[action] int NOT NULL,
[parent] int NULL,
CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category])
)
(level
is literally the level of a category 0: root, 1: first level after root, ...)
and the query:
WITH n(category, name, level, parent, concatenador) AS
(
SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador
FROM mar_categories
WHERE parent is null
UNION ALL
SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador
FROM mar_categories as m, n
WHERE n.category = m.parent
)
SELECT distinct * FROM n ORDER BY concatenador asc
(You don't need to concatenate the level
field, I did just to make more readable)
the answer for this query should be something like:
I hope it helps someone!
now, I'm wondering how to do this on MySQL... ^^
<string.h>
is the old C header. C++ provides <string>
, and then it should be referred to as std::string
.
To display the Alt text of missing images, we have to add a style like this. I think, there is no need to add extra javascript for this.
.Your_Image_Class_Name {
font-size: 14px;
}
It's work for me. Enjoy!!!!
Inheritance brings out IS-A relation. Composition brings out HAS-A relation.
Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
Classic example being of a duck class which implements a flying behaviour.
public interface Flyable{
public void fly();
}
public class Duck {
Flyable fly;
public Duck(){
fly = new BackwardFlying();
}
}
Thus we can have multiple classes which implement flying eg:
public class BackwardFlying implements Flyable{
public void fly(){
Systemout.println("Flies backward ");
}
}
public class FastFlying implements Flyable{
public void fly(){
Systemout.println("Flies 100 miles/sec");
}
}
Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.
If none of this did not help, then try to swap ^ in "^version" to ~ "~version".
Just enter this in your git shell on windows - > alias python='winpty python.exe'
, that is all and you are going to have alias to the python executable. Enjoy
P.S. For permanent alias addition see below,
cd ~
touch .bashrc
then open .bashrc, add your command from above and save the file. You need to create the file through the console or you cannot save it with the proper name. You also need to restart the shell to apply the change.
If you have background on that element, then, adding padding would be useless.
So, in this case, you can use background-clip: content-box; or outline-offset
Explanation: If you use wrapper, then it would be simple to separate the background from border. But if you want to style the same element, which has a background, no matter how much padding you would add, there would be no space between background and border, unless you use background-clip or outline-offset
Instead of trying to modify the $scope
within the service, you can implement a $watch
within your controller to watch a property on your service for changes and then update a property on the $scope
. Here is an example you might try in a controller:
angular.module('cfd')
.controller('MyController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.students = null;
(function () {
$scope.$watch(function () {
return StudentService.students;
}, function (newVal, oldVal) {
if ( newValue !== oldValue ) {
$scope.students = newVal;
}
});
}());
}]);
One thing to note is that within your service, in order for the students
property to be visible, it needs to be on the Service object or this
like so:
this.students = $http.get(path).then(function (resp) {
return resp.data;
});
$result2 is resource link not a string to echo
it or to replace some of its parts with str_replace()
.
This is due to a bug in Webkit.
You can work around the Webkit bug using createEvent('Event')
rather than createEvent('KeyboardEvent')
, and then assigning the keyCode
property. See this answer and this example.
cv::Mat m;
m.create(10, 10, CV_32FC3);
float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
for ( unsigned j = 0; j < 3; j++ ) {
*(array + i ) = (*it)[j];
i++;
}
}
Now you have a float array. In case of 8 bit, simply change float
to uchar
, Vec3f
to Vec3b
and CV_32FC3
to CV_8UC3
.
i think this might work for you
//<?php
//checks file extension for images only
$allowed = array('gif','png' ,'jpg');
$file = $_FILES['file']['name'];
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) )
{
//?>
<script>
alert('file extension not allowed');
window.location.href='some_link.php?file_type_not_allowed_error';
</script>
//<?php
exit(0);
}
//?>
I used a WebView and loaded the image from the memory via
webview.loadUrl("file://...")
The WebView handles all the panning zooming and scrolling. If you use wrap_content the webview won't be bigger then the image and no white areas are shown. The WebView is the better ImageView ;)
As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN()
although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:
Only meaningful if std::numeric_limits::has_quiet_NaN == true.
and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN
it says:
This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.
which as explained here if true
means your platform supports IEEE 754
standard. This previous thread explains this should be true for most situations.
I am trying to avoid using VBA. But if has to be, then it has to be:)
There is quite simple UDF for you:
Function myCountIf(rng As Range, criteria) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
Next ws
End Function
and call it like this: =myCountIf(I:I,A13)
P.S. if you'd like to exclude some sheets, you can add If
statement:
Function myCountIf(rng As Range, criteria) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name <> "Sheet1" And ws.name <> "Sheet2" Then
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
End If
Next ws
End Function
UPD:
I have four "reference" sheets that I need to exclude from being scanned/searched. They are currently the last four in the workbook
Function myCountIf(rng As Range, criteria) As Long
Dim i As Integer
For i = 1 To ThisWorkbook.Worksheets.Count - 4
myCountIf = myCountIf + WorksheetFunction.CountIf(ThisWorkbook.Worksheets(i).Range(rng.Address), criteria)
Next i
End Function
local_settings.py, for django projects.
*~ for all projects.
For center triangle
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int b=(n-1)*2;
for(int i=1;i<=n;i++){
int t= i;
for(int k=1;k<=b;k++){
System.out.print(" ");
}
if(i!=1){
t=i*2-1;
}
for(int j=1;j<=t;j++){
System.out.print("*");
if(j!=t){
System.out.print(" ");
}
}
System.out.println();
b=b-2;
}
output:
*
* * *
possible duplicate , best way to achieve same as stated below:
function getKey(key) {
return `${key}`;
}
var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
Firstly, your example is looking quite correct and works well on my machine. You may go another way.
curl $CURLARGS $RVMHTTP > ./install.sh
All output now storing in ./install.sh
file, which you can edit and execute.
Sorry Late to party but Firestore solved it way back in aug 2018 so If you still looking for that here it is all issues solved with regards to arrays.
https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.htmlOfficial blog post
array-contains, arrayRemove, arrayUnion for checking, removing and updating arrays. Hope it helps.
You can do it with a pivot
query, like this:
select * from (
select LOAN_NUMBER, DOCUMENT_TYPE, DOCUMENT_ID
from my_table t
)
pivot
(
MIN(DOCUMENT_ID)
for DOCUMENT_TYPE in ('Voters ID','Pan card','Drivers licence')
)
Here is a demo on sqlfiddle.com.
My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.
This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen
from the copied link was in a different encoding and hence the curl_exec()
was always returning false
because it was unable to communicate with the server.
It took me a couple hours to finally understand the diference in the characters bellow:
https://www.e-example.com/api
https://www.e-example.com/api
Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api
.
It may seem to you that they are equal but if you check the encoding of the hyphens
here you'll see that the first hyphen
is a unicode characters U+2010 and the other is a U+002D.
Hope this helps someone.
Right now, it has not been exposed at API level yet. However you can achieve it using something similar to this
<ng-container cdkColumnDef="userId" >
<md-header-cell *cdkHeaderCellDef [ngClass]="'customWidthClass'"> ID </md-header-cell>
<md-cell *cdkCellDef="let row" [ngClass]="'customWidthClass'"> {{row.id}} </md-cell>
</ng-container>
In css, you need to add this custom class -
.customWidthClass{
flex: 0 0 75px;
}
Feel free to enter the logic to append class or custom width in here. It will apply custom width for the column.
Since md-table uses flex
, we need to give fixed width in flex manner. This simply explains -
0 = don't grow (shorthand for flex-grow)
0 = don't shrink (shorthand for flex-shrink)
75px = start at 75px (shorthand for flex-basis)
Plunkr here - https://plnkr.co/edit/v7ww6DhJ6zCaPyQhPRE8?p=preview
This syntax has changed with the newer Apache HTTPd server, please see upgrade to apache 2.4 doc for full details.
2.2 configuration syntax was
Order deny,allow
Deny from all
2.4 configuration now is
Require all denied
Thus, this 2.2 syntax
order deny,allow
deny from all
allow from 127.0.0.1
Would ne now written
Require local
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.I found the approach given by cimmanon and Kurt Mueller almost worked, but that I needed a parent reference (i.e., I need to add the '&' prefix to each vendor prefix); like this:
@mixin placeholder {
&::-webkit-input-placeholder {@content}
&:-moz-placeholder {@content}
&::-moz-placeholder {@content}
&:-ms-input-placeholder {@content}
}
I use the mixin like this:
input {
@include placeholder {
font-family: $base-font-family;
color: red;
}
}
With the parent reference in place, then correct css gets generated, e.g.:
input::-webkit-input-placeholder {
font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
color: red;
}
Without the parent reference (&), then a space is inserted before the vendor prefix and the CSS processor ignores the declaration; that looks like this:
input::-webkit-input-placeholder {
font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
color: red;
}
Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux
instead of Other.
After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.
Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.
Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.
Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.
In VirtualBox screen, go to Devices>USB devices. Select your dongle.
Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.
Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.
Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .
You don't need to wait. Protractor automatically waits for angular to be ready and then it executes the next step in the control flow.
Try this It is working for me..
The syntax is GetFiles(string path, string searchPattern);
var filePath = Server.MapPath("~/App_Data/");
string[] filePaths = Directory.GetFiles(@filePath, "*.*");
This code will return all the files inside App_Data
folder.
The second parameter . indicates the searchPattern with File Extension where the first * is for file name and second is for format of the file or File Extension like (*.png - any file name with .png format.
Try this one using Grid Layout:
.grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: auto auto auto;_x000D_
padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
background-color: rgba(255, 255, 255, 0.8);_x000D_
border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
padding: 20px;_x000D_
font-size: 30px;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
<div class="grid-item">1</div>_x000D_
<div class="grid-item">2</div>_x000D_
<div class="grid-item">3</div> _x000D_
<div class="grid-item">4</div>_x000D_
<div class="grid-item">5</div>_x000D_
<div class="grid-item">6</div> _x000D_
<div class="grid-item">7</div>_x000D_
<div class="grid-item">8</div>_x000D_
<div class="grid-item">9</div> _x000D_
</div>
_x000D_
A simple solution that could work in some cases is to create and $compile a wrapper and then append your original element to it.
Something like...
link: function(scope, elem, attr){
var wrapper = angular.element('<div tooltip></div>');
elem.before(wrapper);
$compile(wrapper)(scope);
wrapper.append(elem);
}
This solution has the advantage that it keeps things simple by not recompiling the original element.
This wouldn't work if any of the added directive's require
any of the original element's directives or if the original element has absolute positioning.
Use the rawurlencode
function instead.
Try FieldUtils
from apache commons-lang3:
FieldUtils.readField(object, fieldName, true);
On SQL 2017 - Database A has synonyms to Database B. User can connect to database A and has exec rights to an sp (on A) that refers to the synonyms that point to B. User was set up with connect access B. Only when granting CONNECT to the public group to database B did the sp on A work. I don't recall this working this way on 2012 as granting connect to the user only seemed to work.
In simplejson
(or the library json
in Python 2.6 and later), loads
takes a JSON string and returns a Python data structure, dumps
takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array. To get a JSON string such as
{"apple":"cat", "banana":"dog"}
the Python object you pass to json.dumps
could be:
dict(apple="cat", banana="dog")
though the JSON string is also valid Python syntax for the same dict
. I believe the specific string you say you expect is simply invalid JSON syntax, however.
Yes, the new limit is approximately 1 million rows.
Your syntax error is caused by a missing "table" in the query
ALTER TABLE mytable MODIFY mycolumn varchar(255) null;
Your code in the last update should not compile, much less run. You're passing &x to LoadData. &x has the type of **words, but LoadData expects words* . Of course it crashes when you call realloc on a pointer that's pointing into stack.
The way to fix it is to change LoadData to accept words** . Thi sway, you can actually modify the pointer in main(). For example, realloc call would look like
*x = (words*) realloc(*x, sizeof(words)*2);
It's the same principlae as in "num" being int* rather than int.
Besides this, you need to really figure out how the strings in words ere stored. Assigning a const string to char * (as in str2 = "marley\0") is permitted, but it's rarely the right solution, even in C.
Another point: non need to have "marley\0" unless you really need two 0s at the end of string. Compiler adds 0 tho the end of every string literal.
Serialize list into text file with comma sepparated value
mylist = dir()
with open('filename.txt','w') as f:
f.write( ','.join( mylist ) )
If you have forked a repository fro Delete your forked copy and fork it again from master.
I would like to update the answers above to 2018 and say to use both VisualVM and Eclipse MAT.
VisualVM is used for live monitoring and dump heap. You can also analyze the heap dumps there with great power, however MAT have more capabilities (such as automatic analysis to find leaks) and therefore, I read the VisualVM dump output (.hprof file) into MAT.
Download VisualVM here: https://visualvm.github.io/
You also need to download the plugin for Intellij:
Then you'll see in intellij another 2 new orange icons:
Once you run your app with an orange one, in VisualVM you'll see your process on the left, and data on the right. Sit some time and learn this tool, it is very powerful:
Download here: https://www.eclipse.org/mat/downloads.php
Hope it helps!
The only thing you need to do is:
<?php
if(!isset($_SESSION))
{
session_start();
}
?>
Use ThenBy
:
var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection
.
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);
package.Save();
}
You could modify .adm
and add
.adm{
clear:both;
}
That should make it move to a new line
Firstly a quick recap on RSA key generation.
The public key consists of the modulus and the public exponent.
A minimal private key would consist of the modulus and the private exponent. There is no computationally feasible surefire way to go from a known modulus and private exponent to the corresponding public exponent.
However:
So in most practical RSA implementations you can get the public key from the private key. It would be possible to build a RSA based cryptosystem where this was not possible, but it is not the done thing.
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
I think this will happen if you'll use 'async defer' for (the file that contains the filter) while working with angularjs:
<script src="js/filter.js" type="text/javascript" async defer></script>
if you do, just remove 'async defer'.
Both capture output and run on background with threading
As mentioned on this answer, if you capture the output with stdout=
and then try to read()
, then the process blocks.
However, there are cases where you need this. For example, I wanted to launch two processes that talk over a port between them, and save their stdout to a log file and stdout.
The threading
module allows us to do that.
First, have a look at how to do the output redirection part alone in this question: Python Popen: Write to stdout AND log file simultaneously
Then:
main.py
#!/usr/bin/env python3
import os
import subprocess
import sys
import threading
def output_reader(proc, file):
while True:
byte = proc.stdout.read(1)
if byte:
sys.stdout.buffer.write(byte)
sys.stdout.flush()
file.buffer.write(byte)
else:
break
with subprocess.Popen(['./sleep.py', '0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc1, \
subprocess.Popen(['./sleep.py', '10'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2, \
open('log1.log', 'w') as file1, \
open('log2.log', 'w') as file2:
t1 = threading.Thread(target=output_reader, args=(proc1, file1))
t2 = threading.Thread(target=output_reader, args=(proc2, file2))
t1.start()
t2.start()
t1.join()
t2.join()
sleep.py
#!/usr/bin/env python3
import sys
import time
for i in range(4):
print(i + int(sys.argv[1]))
sys.stdout.flush()
time.sleep(0.5)
After running:
./main.py
stdout get updated every 0.5 seconds for every two lines to contain:
0
10
1
11
2
12
3
13
and each log file contains the respective log for a given process.
Inspired by: https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/
Tested on Ubuntu 18.04, Python 3.6.7.
Use this code:
public static void main(String[] args) {
String test = "A|B|C||D";
String[] result = test.split("\\|");
for (String s : result) {
System.out.println(">" + s + "<");
}
}
If you are using a navigation controller and just want to know if you are in the active and topmost controller, then use:
if navigationController?.topViewController == self {
// Do something
}
This answer is based on @mattdipasquale's comment.
If you have a more complicated scenario, see the other answers above.
I wanted a similar method for my project but in my case the input paths were either from local disk volumes or clustered storage volumes (CSVs). So DriveInfo class did not work for me. CSVs have a mount point under another drive, typically C:\ClusterStorage\Volume*. Note that C: will be a different Volume than C:\ClusterStorage\Volume1
This is what I finally came up with:
public static ulong GetFreeSpaceOfPathInBytes(string path)
{
if ((new Uri(path)).IsUnc)
{
throw new NotImplementedException("Cannot find free space for UNC path " + path);
}
ulong freeSpace = 0;
int prevVolumeNameLength = 0;
foreach (ManagementObject volume in
new ManagementObjectSearcher("Select * from Win32_Volume").Get())
{
if (UInt32.Parse(volume["DriveType"].ToString()) > 1 && // Is Volume monuted on host
volume["Name"] != null && // Volume has a root directory
path.StartsWith(volume["Name"].ToString(), StringComparison.OrdinalIgnoreCase) // Required Path is under Volume's root directory
)
{
// If multiple volumes have their root directory matching the required path,
// one with most nested (longest) Volume Name is given preference.
// Case: CSV volumes monuted under other drive volumes.
int currVolumeNameLength = volume["Name"].ToString().Length;
if ((prevVolumeNameLength == 0 || currVolumeNameLength > prevVolumeNameLength) &&
volume["FreeSpace"] != null
)
{
freeSpace = ulong.Parse(volume["FreeSpace"].ToString());
prevVolumeNameLength = volume["Name"].ToString().Length;
}
}
}
if (prevVolumeNameLength > 0)
{
return freeSpace;
}
throw new Exception("Could not find Volume Information for path " + path);
}
This works like a charm, fast and accurate:
function replace_string_in_file($filename, $string_to_replace, $replace_with){
$content=file_get_contents($filename);
$content_chunks=explode($string_to_replace, $content);
$content=implode($replace_with, $content_chunks);
file_put_contents($filename, $content);
}
Usage:
$filename="users/data/letter.txt";
$string_to_replace="US$";
$replace_with="Yuan";
replace_string_in_file($filename, $string_to_replace, $replace_with);
// never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool
This is rather a method than just a single script but gives you much more flexibility.
First of all There are 3 objects:
ColumnActionList
] -> holds data as
parameter proc_PivotPrepare
] -> prepares our dataproc_PivotExecute
] -> execute the scriptCREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO
CREATE PROCEDURE [dbo].[proc_PivotPrepare]
(
@DB_Name nvarchar(128),
@TableName nvarchar(128)
)
AS
SELECT @DB_Name = ISNULL(@DB_Name,db_name())
DECLARE @SQL_Code nvarchar(max)
DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));
SELECT @SQL_Code = 'SELECT [<| SQL_Code |>] = '' '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
+ 'UNION ALL '
+ 'SELECT ''-----|'''
+ 'UNION ALL '
+ 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''INSERT INTO @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
+ 'FROM [' + @DB_Name + '].sys.columns '
+ 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
+ 'UNION ALL '
+ 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
+ 'UNION ALL '
+ 'SELECT ''----------------------------------------------------------------------------------------------------'' '
EXECUTE SP_EXECUTESQL @SQL_Code;
GO
CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions ColumnActionList ReadOnly
,@TableName nvarchar(128)
)
AS
--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################
IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions;
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;
--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################
DECLARE @ColumnName nvarchar(128)
DECLARE @Destiny nchar(1)
DECLARE @ListOfColumns_Stable nvarchar(max)
DECLARE @ListOfColumns_Dimension nvarchar(max)
DECLARE @ListOfColumns_Variable nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################
DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
END
CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;
--############################
--###| Cursor for List of Dimension Columns
--############################
DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
END
CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;
--############################
--###| Cursor for List of Variable Columns
--############################
DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT [ColumnName]
FROM #ColumnListWithActions
WHERE [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
END
CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;
SELECT @ListOfColumns_Variable = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);
--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';
DECLARE @DIM_ID smallint;
SELECT @DIM_ID = 1;
DECLARE @SQL_Dimentions nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions;
SELECT @SQL_Dimentions = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
+ ' INTO ##ALL_Dimentions '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
SELECT @DIM_ID = @DIM_ID + 1;
END
SELECT @SQL_Dimentions = @SQL_Dimentions + ' )x';
EXECUTE SP_EXECUTESQL @SQL_Dimentions;
--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @StabPos_ID smallint;
SELECT @StabPos_ID = 1;
DECLARE @SQL_MainStableColumnTable nvarchar(max);
IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns;
SELECT @SQL_MainStableColumnTable = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
+ ' INTO ##ALL_StableColumns '
+ ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM ' + @TableName
+ ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
BEGIN
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
SELECT @StabPos_ID = @StabPos_ID + 1;
END
SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + ' )x';
EXECUTE SP_EXECUTESQL @SQL_MainStableColumnTable;
--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################
DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''
DECLARE @i smallint
IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab;
SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
+ ' INTO ##FinalTab '
+ 'FROM ' + @TableName + ' t '
+ 'JOIN ##ALL_Dimentions dim '
+ 'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
SELECT @i = 2
WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
BEGIN
SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
SELECT @i = @i +1
END
EXECUTE SP_EXECUTESQL @FULL_SQL_1
--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';
DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';
DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;
DECLARE @FinalCode nvarchar(max)
SELECT @FinalCode = ' SELECT ID1.*'
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @z = 1
WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] = ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
SELECT @z = @z + 1
END
SELECT @y = @y + 1
END
SELECT @FinalCode = @FinalCode +
' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
SELECT @y = 1
WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
BEGIN
SELECT @x = 1
SELECT @FinalCode = @FinalCode
+ ' LEFT JOIN (SELECT ' + @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable
+ ' FROM ##FinalTab WHERE [xxx_ID_xxx] = '
+ CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))
+ ' ON 1 = 1'
WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
BEGIN
SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
SELECT @x = @x +1
END
SELECT @y = @y + 1
END
SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;
From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)
Names and datatypes will be defined automatically!
I cant recommend it for any production environments but does the job for adhoc BI requests.
Most answers and explanations are not to explain what is a valid string of endDate
or startDate
.
Danny gave us two useful example.
$('#datepicker').datepicker({
startDate: '-2m',
endDate: '+2d'
});
But why?let's take a look at the source code at bootstrap-datetimepicker.js
.
There are some code begin line 1343 tell us how does it work.
if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([-+]\d+)([dmwy])/,
parts = date.match(/([-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
}
There are four kinds of expressions.
w
means weekm
means monthy
means yeard
means dayLook at the regular expression ^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$
.
You can do more than these -0d
or +1m
.
Try harder like startDate:'+1y,-2m,+0d,-1w'
.And the separator ,
could be one of [\f\n\r\t\v,]