Saving state is a kludge at best as far as I'm concerned. If you need to save persistent data, just use an SQLite database. Android makes it SOOO easy.
Something like this:
import java.util.Date;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class dataHelper {
private static final String DATABASE_NAME = "autoMate.db";
private static final int DATABASE_VERSION = 1;
private Context context;
private SQLiteDatabase db;
private OpenHelper oh ;
public dataHelper(Context context) {
this.context = context;
this.oh = new OpenHelper(this.context);
this.db = oh.getWritableDatabase();
}
public void close() {
db.close();
oh.close();
db = null;
oh = null;
SQLiteDatabase.releaseMemory();
}
public void setCode(String codeName, Object codeValue, String codeDataType) {
Cursor codeRow = db.rawQuery("SELECT * FROM code WHERE codeName = '"+ codeName + "'", null);
String cv = "" ;
if (codeDataType.toLowerCase().trim().equals("long") == true){
cv = String.valueOf(codeValue);
}
else if (codeDataType.toLowerCase().trim().equals("int") == true)
{
cv = String.valueOf(codeValue);
}
else if (codeDataType.toLowerCase().trim().equals("date") == true)
{
cv = String.valueOf(((Date)codeValue).getTime());
}
else if (codeDataType.toLowerCase().trim().equals("boolean") == true)
{
String.valueOf(codeValue);
}
else
{
cv = String.valueOf(codeValue);
}
if(codeRow.getCount() > 0) //exists-- update
{
db.execSQL("update code set codeValue = '" + cv +
"' where codeName = '" + codeName + "'");
}
else // does not exist, insert
{
db.execSQL("INSERT INTO code (codeName, codeValue, codeDataType) VALUES(" +
"'" + codeName + "'," +
"'" + cv + "'," +
"'" + codeDataType + "')" );
}
}
public Object getCode(String codeName, Object defaultValue){
//Check to see if it already exists
String codeValue = "";
String codeDataType = "";
boolean found = false;
Cursor codeRow = db.rawQuery("SELECT * FROM code WHERE codeName = '"+ codeName + "'", null);
if (codeRow.moveToFirst())
{
codeValue = codeRow.getString(codeRow.getColumnIndex("codeValue"));
codeDataType = codeRow.getString(codeRow.getColumnIndex("codeDataType"));
found = true;
}
if (found == false)
{
return defaultValue;
}
else if (codeDataType.toLowerCase().trim().equals("long") == true)
{
if (codeValue.equals("") == true)
{
return (long)0;
}
return Long.parseLong(codeValue);
}
else if (codeDataType.toLowerCase().trim().equals("int") == true)
{
if (codeValue.equals("") == true)
{
return (int)0;
}
return Integer.parseInt(codeValue);
}
else if (codeDataType.toLowerCase().trim().equals("date") == true)
{
if (codeValue.equals("") == true)
{
return null;
}
return new Date(Long.parseLong(codeValue));
}
else if (codeDataType.toLowerCase().trim().equals("boolean") == true)
{
if (codeValue.equals("") == true)
{
return false;
}
return Boolean.parseBoolean(codeValue);
}
else
{
return (String)codeValue;
}
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS code" +
"(id INTEGER PRIMARY KEY, codeName TEXT, codeValue TEXT, codeDataType TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
A simple call after that
dataHelper dh = new dataHelper(getBaseContext());
String status = (String) dh.getCode("appState", "safetyDisabled");
Date serviceStart = (Date) dh.getCode("serviceStartTime", null);
dh.close();
dh = null;
You have misspelt the second pixels
as pixel
. The following works:
pixels = [1,2,3]
pixels[0] = 5
It appears that due to the typo you were trying to accidentally modify some tuple called pixel
, and in Python tuples are immutable. Hence the confusing error message.
$("#frame").click(function () {
this.src="http://www.google.com/";
});
Sometimes plain JavaScript is even cooler and faster than jQuery ;-)
Maybe the "K" format specifier would be of some use. This is the only one that seems to mention the use of capital "Z".
"Z" is kind of a unique case for DateTimes. The literal "Z" is actually part of the ISO 8601 datetime standard for UTC times. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time. This probably creates a few problems for the date format library in .NET, since it's actually a literal, rather than a format specifier.
I'm not sure how helpful this answer is for your current application, but it may prove helpful for the next applications that you will be developing.
As iOS does not use Java like Android, your options are quite limited:
1) if your application is written mostly in C/C++ using JNI, you can write a wrapper and interface it with the iOS (i.e. provide callbacks from iOS to your JNI written function). There may be frameworks out there that help you do this easier, but there's still the problem of integrating the application and adapting it to the framework (and of course the fact that the application has to be written in C/C++).
2) rewrite it for iOS. I don't know whether there are any good companies that do this for you. Also, due to the variety of applications that can be written which can use different services and API, there may not be any software that can port it for you (I guess this kind of software is like a gold mine heh) or do a very good job at that.
3) I think that there are Java->C/C++ converters, but there won't help you at all when it comes to API differences. Also, you may find yourself struggling more to get the converted code working on any of the platforms rather than rewriting your application from scratch for iOS.
The problem depends quite a bit on the services and APIs your application is using. I haven't really look this up, but there may be some APIs that provide certain functionality in Android that iOS doesn't provide.
Using C/C++ and natively compiling it for the desired platform looks like the way to go for Android-iOS-Win7Mobile cross-platform development. This gets you somewhat of an application core/kernel which you can use to do the actual application logic.
As for the OS specific parts (APIs) that your application is using, you'll have to set up communication interfaces between them and your application's core.
look this happend to me when I created new file inside a folder with the same name of class in the project { folder name : Folder } and there is class name { Folder } so the namespace was the namespace.Folder so that the compiler assume that the cass defined in two places
in new file :
namespace APP.Folder
{
partial class NewFile
{
// ....
}
}
in the other file (the file that hase the problem):
namespace APP
{
partial class Folder
{
// ....
}
}
-- so you can edit the folder name or remove the .Folder from the namespace at the new file
git checkout
has the --ours
option to check out the version of the file that you had locally (as opposed to --theirs
, which is the version that you pulled in). You can pass .
to git checkout
to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add
, and commit your work once done:
git checkout --ours . # checkout our local version of all files
git add -u # mark all conflicted files as merged
git commit # commit the merge
Note the .
in the git checkout
command. That's very important, and easy to miss. git checkout
has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in .
or a filename in order to get the second behavior from git checkout
.
It's also a good habit to have, when passing in a filename, to offset it with --
, such as git checkout --ours -- <filename>
. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout
command.
I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.
The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.
Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD
is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff
).
Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit
if you need to edit it beforehand (for instance, if you rename function foo
to bar
, and someone else adds new code that calls foo
, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).
The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<
, =======
, and >>>>>>>
) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add
before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD
(your side of the merge), and the version from the remote branch.
In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours
or git checkout --theirs
. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add
, and then you can commit the merge with git commit
.
From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.
EDIT:
There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):
The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.
At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.
Instead of using the full plugin name (with groupId) like described in Bartosz's answer, you could add
<pluginGroups>
<pluginGroup>org.springframework.boot</pluginGroup>
</pluginGroups>
to your .m2/settings.xml.
Try to use redoc-cli.
I was using bootprint-openapi by which I was generating a bunch of files (bundle.js
, bundle.js.map
, index.html
, main.css
and main.css.map
) and then you can convert it into a single .html
file using html-inline to generate a simple index.html
file.
Then I found redoc-cli very easy to to use and output is really-2 awesome, a single and beautiful index.html file.
Installation:
npm install -g redoc-cli
Usage:
redoc-cli bundle -o index.html swagger.json
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
If there were uncommitted worktree changes present when the merge started,
git merge --abort
will in some cases be unable to reconstruct these changes. It is therefore recommended to always commit or stash your changes before running git merge.
git merge --abort
is equivalent togit reset --merge
whenMERGE_HEAD
is present.
std::move
?A: std::move()
is a function from the C++ Standard Library for casting to a rvalue reference.
Simplisticly std::move(t)
is equivalent to:
static_cast<T&&>(t);
An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.
int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
int b = a; // a is a lvalue, keeps existing after expression is evaluated
An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:
template <class T>
typename remove_reference<T>::type&&
std::move(T&& a)
{
return a;
}
As you can see, std::move
returns T&&
no matter if called with a value (T
), reference type (T&
), or rvalue reference (T&&
).
A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.
foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)
int a = 3 * 5;
foo(a); // how to tell the compiler to treat `a` as an rvalue?
foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`
What it does not do:
A: You should use std::move
if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).
This begs the following follow-up questions for me:
What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.
What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.
Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.
In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged.
Also possible by looking for substring with index() function:
awk '(index($3, "snow") != 0) {print}' dummy_file
Shorter version:
awk 'index($3, "snow")' dummy_file
GET Scroll Position:
var scrolled_val = window.scrollY;
DETECT Scroll Position:
$(window).scroll
(
function (event)
{
var scrolled_val = window.scrollY;
alert(scrolled_val);
}
);
Right click on folder.
Click Properties
Click Security Tab. You will see something like this:
Check/uncheck whatever access you need to grant to the account
Click Apply button and then OK.
Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).
If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all
, without any external libraries:
function asyncAction(i) {
return new Promise(function(resolve, reject) {
var result = calculateResult();
if (result.hasError()) {
return reject(result.error);
}
return resolve(result);
});
}
var promises = [];
for (var i=0; i < 10; i++) {
promises.push(asyncAction(i));
}
Promise.all(promises).then(function AcceptHandler(results) {
handleResults(results),
}, function ErrorHandler(error) {
handleError(error);
});
If it says the API key is listed as a header, more than likely you need to set it in the headers
option of your http request. Normally something like this :
headers: {'Authorization': '[your API key]'}
Here is an example from another Question
$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});
Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :
$.ajax({
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});
I got this from this question and I'm at work so I can't test it at the moment but looks solid
Edit 2: Pretty sure you should be able to use this line :
headers: {'Authorization': '[your API key]'},
instead of the beforeSend
line in the first edit. This may be simpler for you
Faced more issues while making this work. Here are the details:
apache-log4j-extras-1.1.jar
in the classpath, didn't notice this at first.RollingFileAppender
should be org.apache.log4j.rolling.RollingFileAppender
instead of org.apache.log4j.RollingFileAppender
. This can give the error: log4j:ERROR No output stream or file set for the appender named [file].
log4j-1.2.14.jar
to log4j-1.2.16.jar
.Below is the appender configuration which worked for me:
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="threshold" value="debug" />
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="logs/MyLog-%d{yyyy-MM-dd-HH-mm}.log.gz" />
<!-- The below param will keep the live update file in a different location-->
<!-- param name="ActiveFileName" value="current/MyLog.log" /-->
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
</layout>
</appender>
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
Use TRY_CONVERT which is an SQL alternative to TryParse in .NET. IsNumeric() isn’t aware that empty strings are counted as (integer)zero, and that some perfectly valid money symbols, by themselves, are not converted to (money)zero. reference
SELECT @MY_VAR = CASE WHEN TRY_CONVERT(INT,MY_FIELD) IS NOT NULL THEN MY_FIELD
ELSE 0
END
FROM MY_TABLE
WHERE MY_OTHER_FIELD = 'MY_FILTER'
It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?
something like this:
$("#gender").trigger("pageinit");
There is actually no need to check whether it exists or not. Since you already wants to create it if it exists , just mkdir will do
mkdir -p /home/mlzboy/b2c2/shared/db
You can use the controls PointToScreen
method to get the absolute position with respect to the screen.
You can do the Forms PointToScreen
method, and with basic math, get the control's position.
You can't have two elements with the same ID.
Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.
Instead, try something like this:
<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>
CSS:
.link {
width: 50%;
float: left;
text-align: center;
}
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
TelephonyManger.getDeviceId() Returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones.
final TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String myAndroidDeviceId = mTelephony.getDeviceId();
But i recommend to use:
Settings.Secure.ANDROID_ID that returns the Android ID as an unique 64-bit hex string.
String myAndroidDeviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
Sometimes TelephonyManger.getDeviceId() will return null, so to assure an unique id you will use this method:
public String getUniqueID(){
String myAndroidDeviceId = "";
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null){
myAndroidDeviceId = mTelephony.getDeviceId();
}else{
myAndroidDeviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
}
return myAndroidDeviceId;
}
You can use urllib2 as well:
import urllib2
req = urllib2.Request('http://www.python.org/fish.html')
try:
resp = urllib2.urlopen(req)
except urllib2.HTTPError as e:
if e.code == 404:
# do something...
else:
# ...
except urllib2.URLError as e:
# Not an HTTP-specific error (e.g. connection refused)
# ...
else:
# 200
body = resp.read()
Note that HTTPError
is a subclass of URLError
which stores the HTTP status code.
window.history.pushState({urlPath:'/page1'},"",'/page1')
Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.
What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.
Just change moveCamera to animateCamera like below
Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))
It means that you're trying to insert into table2
a UserID
value that doesn't exist in table1
.
The execution of maven command required pom.xml file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.
Make sure that porject should contains pom.xml at the root level.
we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.
If I understand that stack trace, it's not your timer which is the problem, it's one in the control itself - it might be them who are not cleaning-up properly.
Are you explicitly calling Dispose on their control?
As far as I know, can't you just make it abstract?
class parent {
public:
virtual void handle_event(int something) const = 0 {
// boring default code
}
};
I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.
Am currently using the solution below to tackle the same issue:
//set locale,
setlocale(LC_ALL,"US");
//set the date to be converted
$date = '2016-08-07';
//convert date to month name
$month_name = ucfirst(strftime("%B", strtotime($date)));
echo $month_name;
To read more about set locale go to http://php.net/manual/en/function.setlocale.php
To learn more about strftime go to http://php.net/manual/en/function.strftime.php
Ucfirst()
is used to capitalize the first letter in a string.
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
I believe if you use delegates, it would work..
$("textarea").on('change paste keyup', function () {
var currText = $(this).val();
if (currText.length > 500) {
var text = $(this).text();
$(this).text(text.substr(0, 500));
alert("You have reached the maximum length for this field");
}
});
The option 1 sounds not too efficient. What if there is no space in the client to do a clone and then remove the .git
folder?
Today I found myself trying to do this, where the client is a Raspberry Pi with almost no space left. Furthermore, I also want to exclude some heavy folder from the repository.
Option 2 and others answers here do not help in this scenario. Neither git archive
(because require to commit a .gitattributes
file, and I don't want to save this exclusion in the repository).
Here I share my solution, similar to option 3, but without the need of git clone
:
tmp=`mktemp`
git ls-tree --name-only -r HEAD > $tmp
rsync -avz --files-from=$tmp --exclude='fonts/*' . raspberry:
Changing the rsync
line for an equivalent line for compress will also work as a git archive
but with a sort of exclusion option (as is asked here).
I had the same problem and found it was caused by permission problems creating the user profile in C:\Users. I gave ApplicationPoolIdentity full permissions to the C:\Users folder, started the site and everything worked, the profile must have been created properly, and my site worked as it should. I then removed access to C:\Users from ApplicationPoolIdentity.
Try this:
window.onclick=(function(){
try {
var file = window.open("file://mnt/sdcard/download/Click.ogg");
setTimeout('file.close()', 100);
setTimeout("alert('Audio file found. Have a nice day!');", 101);
} catch(err) {
var wantstodl=confirm("Warning:\n the file, Click.ogg is not found.\n do you want to download it?\n "+err.message);
if (wantstodl) {
window.open("https://www.dropbox.com/s/qs9v6g2vru32xoe/Click.ogg?dl=1"); //downloads the audio file
}
}
});
$.ajax({
type: "POST",
data: formData,
url: "/Forms/GetJobData",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
Controller:
[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
var mimeType = jobData.File.ContentType;
var isFileSupported = IsFileSupported(mimeType);
if (!isFileSupported){
// Send "false"
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
else
{
// Send "Success"
return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
}
}
---Supplement:---
basically you can send multiple parameters this way:
Controller:
return Json(new {
success = true,
Name = model.Name,
Phone = model.Phone,
Email = model.Email
},
JsonRequestBehavior.AllowGet);
Html:
<script>
$.ajax({
type: "POST",
url: '@Url.Action("GetData")',
contentType: 'application/json; charset=utf-8',
success: function (response) {
if(response.success){
console.log(response.Name);
console.log(response.Phone);
console.log(response.Email);
}
},
error: function (response) {
alert("error!");
}
});
Basically there's three things you can do
I've just writen an answer to a very similar answer here where I explain how you can disable UAC since Windows 8.
Guess you are looking for .focusout()
Whenever possible, I set the field visibility as package-protected so it can be accessed from the test class. I document that using Guava's @VisibleForTesting annotation (in case the next guy wonders why it's not private). This way I don't have to rely on the string name of the field and everything stays type-safe.
I know it goes against standard encapsulation practices we were taught in school. But as soon as there is some agreement in the team to go this way, I found it the most pragmatic solution.
I am using embedded CSS on a local computer. I put the atom.jpg file in the same folder as my html file, then this code worked:
background-image:url(atom.jpg);
More elegant solution:
HTML:
<html ng-app="phoneCat">
<body>
{{ "AngularJS string limit example" | strLimit: 20 }}
</body>
</html>
Angular Code:
var phoneCat = angular.module('phoneCat', []);
phoneCat.filter('strLimit', ['$filter', function($filter) {
return function(input, limit) {
if (! input) return;
if (input.length <= limit) {
return input;
}
return $filter('limitTo')(input, limit) + '...';
};
}]);
Demo:
http://code-chunk.com/chunks/547bfb3f15aa1/str-limit-implementation-for-angularjs
Please take a look here
HH is hour in a day (starting from 0 to 23)
hh are hours in am/pm format
kk is hour in day (starting from 1 to 24)
mm is minute in hour
ss are the seconds in a minute
refer to http://www.w3schools.com/php/php_mysql_select.asp . If you are a beginner and want to learn, w3schools is a good place.
<?php
$con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM employee");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
echo "<br />";
}
mysqli_close($con);
?>
You can similarly echo
it inside your table
<?php
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
}
echo "</table>";
mysqli_close($con);
?>
The follows might be helpful:
# Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None
plt.xticks(
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='medium',
)
Here is the function xticks
[reference] with example and API
def xticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Call signatures::
locs, labels = xticks() # Get locations and labels
xticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
ticks : array_like
A list of positions at which ticks should be placed. You can pass an
empty list to disable xticks.
labels : array_like, optional
A list of explicit labels to place at the given *locs*.
**kwargs
:class:`.Text` properties can be used to control the appearance of
the labels.
Returns
-------
locs
An array of label locations.
labels
A list of `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
Examples
--------
Get the current locations and labels:
>>> locs, labels = xticks()
Set label locations:
>>> xticks(np.arange(0, 1, step=0.2))
Set text labels:
>>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
Set text labels and properties:
>>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
Disable xticks:
>>> xticks([])
"""
To iterate through all elements
XDocument xdoc = XDocument.Load("input.xml");
foreach (XElement element in xdoc.Descendants())
{
Console.WriteLine(element.Name);
}
JavaScript: Convert String to Array JavaScript Split
var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."_x000D_
_x000D_
var result = str.split('-'); _x000D_
_x000D_
console.log(result);_x000D_
_x000D_
document.getElementById("show").innerHTML = result;
_x000D_
<html>_x000D_
<head>_x000D_
<title>How do you split a string, breaking at a particular character in javascript?</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p id="show"></p> _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
https://www.tutsmake.com/javascript-convert-string-to-array-javascript/
Use:
import color
class Color(color.Color):
...
If this were Python 2.x, you would also want to derive color.Color
from object
, to make it a new-style class:
class Color(object):
...
This is not necessary in Python 3.x.
Disclaimer: this works only for tornado
You can do this by setting the fd to be nonblocking and then use ioloop to register callbacks. I have packaged this in an egg called tornado_subprocess and you can install it via PyPI:
easy_install tornado_subprocess
now you can do something like this:
import tornado_subprocess
import tornado.ioloop
def print_res( status, stdout, stderr ) :
print status, stdout, stderr
if status == 0:
print "OK:"
print stdout
else:
print "ERROR:"
print stderr
t = tornado_subprocess.Subprocess( print_res, timeout=30, args=[ "cat", "/etc/passwd" ] )
t.start()
tornado.ioloop.IOLoop.instance().start()
you can also use it with a RequestHandler
class MyHandler(tornado.web.RequestHandler):
def on_done(self, status, stdout, stderr):
self.write( stdout )
self.finish()
@tornado.web.asynchronous
def get(self):
t = tornado_subprocess.Subprocess( self.on_done, timeout=30, args=[ "cat", "/etc/passwd" ] )
t.start()
None of these worked for me in SSIS v18.0, so I would up doing something like this:
WHERE CHARINDEX('_', thingyoursearching) < 1
..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:
WHERE CHARINDEX('_', thingyoursearching) > 0
$("form#submit input").on('keypress',function(event) {
event.preventDefault();
if (event.which === 13) {
$('button.submit').trigger('click');
}
});
The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename
method. See this deprecation note in the documentation for more detail.
This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg
method.
These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.
Before we get there, let's create a four column DataFrame.
df = pd.DataFrame({'A' : list('wwwwxxxx'),
'B':list('yyzzyyzz'),
'C':np.random.rand(8),
'D':np.random.rand(8)})
A B C D
0 w y 0.643784 0.828486
1 w y 0.308682 0.994078
2 w z 0.518000 0.725663
3 w z 0.486656 0.259547
4 x y 0.089913 0.238452
5 x y 0.688177 0.753107
6 x z 0.955035 0.462677
7 x z 0.892066 0.368850
Let's say we want to group by columns A, B
and aggregate column C
with mean
and median
and aggregate column D
with max
. The following code would do this.
df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})
D C
max mean median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:
df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'},
'D':{'D_max': 'max'}})
D C
D_max C_mean C_median
A B
w y 0.994078 0.476233 0.476233
z 0.725663 0.502328 0.502328
x y 0.753107 0.389045 0.389045
z 0.462677 0.923551 0.923551
This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0)
.
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles
you can override the paint method of JFrame and then fill that by your favorite color like this:
@Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0;
does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17
How about
^[A-Za-z]\S*
a letter followed by 0 or more non-space characters (will include all special symbols).
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate
and CollectionTime
to char sequences, combine them, and then convert them to a datetime
.
The parameters to CONVERT
are data_type
, expression
and the optional style
(see syntax documentation).
The date and time style
value 112
converts to an ISO yyyymmdd
format. The style
value 108
converts to hh:mi:ss
format. Evidently both are 8 characters long which is why the data_type
is CHAR(8)
for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss
and then converted to a datetime
.
@Nam's answer works great if you just want to display your custom view but if your custom view needs user interaction you need to disable interaction for the navigationBar
.
self.navigationController.navigationBar.layer.zPosition = -1
self.navigationController.navigationBar.isUserInteractionEnabled = false
Like said in Nam's answer don't forget to reverse these changes:
self.navigationController.navigationBar.layer.zPosition = 0
self.navigationController.navigationBar.isUserInteractionEnabled = true
extension UINavigationBar {
func toggle() {
if self.layer.zPosition == -1 {
self.layer.zPosition = 0
self.isUserInteractionEnabled = true
} else {
self.layer.zPosition = -1
self.isUserInteractionEnabled = false
}
}
}
And simply use it like this:
self.navigationController.navigationBar.toggle()
The reason is that php://input
returns all the raw data after the HTTP-headers of the request, regardless of the content type.
The PHP superglobal $_POST
, only is supposed to wrap data that is either
application/x-www-form-urlencoded
(standard content type for simple form-posts) ormultipart/form-data
(mostly used for file uploads)This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).
So, if you simply POST a good old HTML form
, the request looks something like this:
POST /page.php HTTP/1.1
key1=value1&key2=value2&key3=value3
But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:
POST /page.php HTTP/1.1
{"key1":"value1","key2":"value2","key3":"value3"}
The content would now be application/json
(or at least none of the above mentioned), so PHP's $_POST
-wrapper doesn't know how to handle that (yet).
The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input')
(as long as it's not multipart/form-data
-encoded).
This is also how you would access XML-data or any other non-standard content type.
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
This will get you the difference between two DateTime objects in milliseconds:
DateTime d1 = new DateTime();
DateTime d2 = new DateTime();
long diffInMillis = d2.getMillis() - d1.getMillis();
Use a join with a temporary table. You don't need to pass temporary tables to functions, they are global.
create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;
delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
-- use the temporary table `ids` in the SELECT statement or
-- whatever query you have
select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;
CALL tsel() ; -- call the procedure
The HttpServletRequest object provides a map of parameters already. See request.getParameterMap() for more details.
I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)
Database: 5555555555x555
Display: (555) 555-5555 ext 555
Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
You can resize using style and width to resize the textbox. Here is the code for it.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div align="center">_x000D_
_x000D_
<form method="post">_x000D_
<div class="w3-row w3-section">_x000D_
<div class="w3-rest" align = "center">_x000D_
<input name="lastName" type="text" id="myInput" style="width: 50%">_x000D_
</div>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Use align to center the textbox.
Had the same issue. I used a dirty trick like so:
var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;
Now, you can add styles the way you like:
htmlObject.style.marginTop = something;
You can add a RedirectViewController like:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/", "/index.html");
}
}
It's working completely try this:
<div class="button pull-left" style="padding-left:40%;" >
Python is not the best tool for this task. I tried several approaches in Python but none of them work 100% (e.g. 10% converts to 0.1, or column types are messed up, etc). The right tool here is PowerShell, because it is an MS product (as is Excel) and has the best integration.
Simply download this PowerShell script, edit line 47 to enter the path for the folder containing the Excel files and run the script using PowerShell.
Therefore, I would like to separate the string by the furthest delimiter.
I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.
SQL> WITH DATA AS
2 ( SELECT 'F/P/O' str FROM dual
3 )
4 SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
5 SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
6 FROM DATA
7 /
PART1 PART2
----- -----
F/P O
As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.
You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR
function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
var monthIndex = 1;
return month = DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(monthIndex);
You can try this one as well
In a more general way you can use "INTERVAL". Here some examples:
1) add a day
select sysdate + INTERVAL '1' DAY from dual;
2) add 20 days
select sysdate + INTERVAL '20' DAY from dual;
2) add some minutes
select sysdate + INTERVAL '15' MINUTE from dual;
Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:
xx <- reshape(df, idvar=c("skew","version","color"),
v.names="price", timevar="product", direction="wide")
xx will have columns price.p1, ... price.p4, so:
ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
geom_point(shape=19, size=5)
ggp + facet_grid(color~version)
gives the result from your image.
Plain Java 8 solutions using a Stream
.
Assuming private Collection<T> c, c2, c3
.
One solution:
public Stream<T> stream() {
return Stream.concat(Stream.concat(c.stream(), c2.stream()), c3.stream());
}
Another solution:
public Stream<T> stream() {
return Stream.of(c, c2, c3).flatMap(Collection::stream);
}
Assuming private Collection<Collection<T>> cs
:
public Stream<T> stream() {
return cs.stream().flatMap(Collection::stream);
}
Okay this code does exactly what you need:
HTML:
<div class="class1">nothing happens hear.</div>
<div class="class1 class2">This element will receive yout code.</div>
<div class="class1">nothing happens hear.</div>
JS:
function getElementMultipleClasses() {
var x = document.getElementsByClassName("class1 class2");
x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();
Hope it helps! ;)
You might want to use insert
method. You can find the documentation for the Tkinter Entry Widget here.
This script inserts a text into Entry
. The inserted text can be changed in command
parameter of the Button.
from tkinter import *
def set_text(text):
e.delete(0,END)
e.insert(0,text)
return
win = Tk()
e = Entry(win,width=10)
e.pack()
b1 = Button(win,text="animal",command=lambda:set_text("animal"))
b1.pack()
b2 = Button(win,text="plant",command=lambda:set_text("plant"))
b2.pack()
win.mainloop()
Try to run sql query to discard tablespace before copying idb-file:
ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;
Copy idb-file
ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;
Restart MySql
Simply, @Id: This annotation specifies the primary key of the entity.
@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.
GenerationType enum defines four strategies:
1. Generation Type . TABLE,
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY
4. Generation Type. AUTO
GenerationType.SEQUENCE
With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.
GenerationType.TABLE
With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html
A key difference between __getattr__
and __getattribute__
is that __getattr__
is only invoked if the attribute wasn't found the usual ways. It's good for implementing a fallback for missing attributes, and is probably the one of two you want.
__getattribute__
is invoked before looking at the actual attributes on the object, and so can be tricky to implement correctly. You can end up in infinite recursions very easily.
New-style classes derive from object
, old-style classes are those in Python 2.x with no explicit base class. But the distinction between old-style and new-style classes is not the important one when choosing between __getattr__
and __getattribute__
.
You almost certainly want __getattr__
.
<p:ajax listener="#{my.handleChange}" update="id of component that need to be rerender after change" process="@this" />
import javax.faces.component.UIOutput;
import javax.faces.event.AjaxBehaviorEvent;
public void handleChange(AjaxBehaviorEvent vce){
String name= (String) ((UIOutput) vce.getSource()).getValue();
}
Yet another answer:
-1
... requires import
+1
... is very readable
import operator
a = [1,2,3,4]
b = [10,11,12,13]
list(map(operator.mul, a, b))
outputs [10, 22, 36, 52]
You can adding a +
before the string without using parseInt and parseFloat and radix, Simply
sample:
var votevalue = +$('button').data('votevalue');
alert(typeof(votevalue));
I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.
The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.
You can create a temp file, then rename it back to original file:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream
strLine = ts.ReadLine
' do something with strLine
objOutFile.Write(strLine)
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
Usage is almost the same using OpenTextFile:
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
' do something with strLine
objOutFile.Write(strLine & "kndfffffff")
Loop
objOutFile.Close
objFile.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile
If you look at the inheritance tree (in version 2.6), HTMLParser
inherits from SGMLParser
which inherits from ParserBase
which doesn't inherits from object
. I.e. HTMLParser is an old-style class.
About your checking with isinstance
, I did a quick test in ipython:
In [1]: class A: ...: pass ...: In [2]: isinstance(A, object) Out[2]: True
Even if a class is old-style class, it's still an instance of object
.
Here the function which I created for scaling vector drawables. I used it for setting TextView compound drawable.
/**
* Used to load vector drawable and set it's size to intrinsic values
*
* @param context Reference to {@link Context}
* @param resId Vector image resource id
* @param tint If not 0 - colour resource to tint the drawable with.
* @param newWidth If not 0 then set the drawable's width to this value and scale
* height accordingly.
* @return On success a reference to a vector drawable
*/
@Nullable
public static Drawable getVectorDrawable(@NonNull Context context,
@DrawableRes int resId,
@ColorRes int tint,
float newWidth)
{
VectorDrawableCompat drawableCompat =
VectorDrawableCompat.create(context.getResources(), resId, context.getTheme());
if (drawableCompat != null)
{
if (tint != 0)
{
drawableCompat.setTint(ResourcesCompat.getColor(context.getResources(), tint, context.getTheme()));
}
drawableCompat.setBounds(0, 0, drawableCompat.getIntrinsicWidth(), drawableCompat.getIntrinsicHeight());
if (newWidth != 0.0)
{
float scale = newWidth / drawableCompat.getIntrinsicWidth();
float height = scale * drawableCompat.getIntrinsicHeight();
ScaleDrawable scaledDrawable = new ScaleDrawable(drawableCompat, Gravity.CENTER, 1.0f, 1.0f);
scaledDrawable.setBounds(0,0, (int) newWidth, (int) height);
scaledDrawable.setLevel(10000);
return scaledDrawable;
}
}
return drawableCompat;
}
I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.
No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.
A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.
#divID {
background-image: url("http://imageurlhere.com");
background-repeat: no-repeat;
width: auto; /*or your image's width*/
height: auto; /*or your image's height*/
margin: 0;
padding: 0;
}
Actually, they are different:
$('#GridName').data('kendoGrid').dataSource.read()
refreshes the uid
attributes of the table row
$('#GridName').data('kendoGrid').refresh()
leaves the same uid
Have you tried this?
$('.myClass, .myOtherClass').removeClass('theclass');
As of Chrome 48+, you can access the print preview via the following steps:
Open dev tools – Ctrl/Cmd + Shift + I or right click on the page and choose 'Inspect'.
Hit Esc to open the additional drawer.
If 'Rendering' isn't already being show, click the 3 dot kebab and choose 'rendering'.
Check the 'Emulate print media' checkbox.
From there Chrome will show you a print version of your page and you can inspect element and troubleshoot like you would the browser version.
This was mentioned in a comment to another answer, but I wanted to move it to an actual answer since this was also the problem in my case and I would have upvoted it if it had been an answer.
I'm on Linux and the tnsnames.ora file was not set to readable by everyone. After making it readable connecting via tns locally worked.
$ chmod +r tnsnames.ora
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
I organize packages by feature, not by patterns or implementation roles. I think packages like:
beans
factories
collections
are wrong.
I prefer, for example:
orders
store
reports
so I can hide implementation details through package visibility. Factory of orders should be in the orders
package so details about how to create an order are hidden.
The more general answer to this question involves shadowed variables and how they are accessed.
In the following example (from Oracle), the variable x in main() is shadowing Test.x:
class Test {
static int x = 1;
public static void main(String[] args) {
InnerClass innerClassInstance = new InnerClass()
{
public void printX()
{
System.out.print("x=" + x);
System.out.println(", Test.this.x=" + Test.this.x);
}
}
innerClassInstance.printX();
}
public abstract static class InnerClass
{
int x = 0;
public InnerClass() { }
public abstract void printX();
}
}
Running this program will print:
x=0, Test.this.x=1
More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6
If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.
def foo():
print(self.bar)
>NameError: name 'self' is not defined
def foo(self):
print(self.bar)
I usually do it using Seaborn which is built on top of matplotlib
import seaborn as sns
iris = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length', y='sepal_width',
hue='species', data=iris);
There is also some simple solution without mapping node_module
directory into another volume. It's about to move installing npm packages into final CMD command.
Disadvantage of this approach:
- run
npm install
each time you run container (switching fromnpm
toyarn
might also speed up this process a bit).
FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
COPY . /worker/
CMD /bin/bash -c 'npm install; npm start'
redis:
image: redis
worker:
build: ./worker
ports:
- "9730:9730"
volumes:
- worker/:/worker/
links:
- redis
You need to either put the code below the HTML or load if using the document load event:
<input type="text" id="goal-input" name="goal" />
<script type="text/javascript">
$(function(){
$("#goal-input").focus();
});
</script>
Update:
Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:
if (goal) {
step1.fadeOut('fast', function() {
step1.hide();
step2.fadeIn('fast', function() {
$("#name").focus();
});
});
}
As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.
You can check console output. It prints error:
The following assertion was thrown during performResize(): Horizontal viewport was given unbounded height. Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
You need to add height constraint to your horizontal list. E.g. wrap in Container with height:
Container(
height: 44.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
RaisedButton(
onPressed: null,
child: Text("Facebook"),
),
Padding(padding: EdgeInsets.all(5.00)),
RaisedButton(
onPressed: null,
child: Text("Google"),
)
],
),
)
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
Starting in MongoDB 3.4, you can use the $sortByCount
aggregation.
Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.
https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/
For example:
db.contest.aggregate([
{ $sortByCount: "$province" }
]);
I faced the same problem. I found two solutions: (1) Editing the jar file manually:
Open the jar file with WinRar (or similar tools). Go to Meta-info > services , and edit "org.apache.hadoop.fs.FileSystem" by appending:
org.apache.hadoop.fs.LocalFileSystem
(2) Changing the order of my dependencies as follow
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
A generic solution using Khoth's answer as a starting point.
/**
* @param set a Set in which to look for a random element
* @param <T> generic type of the Set elements
* @return a random element in the Set or null if the set is empty
*/
public <T> T randomElement(Set<T> set) {
int size = set.size();
int item = random.nextInt(size);
int i = 0;
for (T obj : set) {
if (i == item) {
return obj;
}
i++;
}
return null;
}
For spaces use "[^a-z A-Z 0-9]" this pattern
int code = 2;
Environment.Exit( code );
There's a ton of answers already here, but I stumbled upon a great article about how to use Razor with email templating. Razor was pushed with ASP.NET MVC 3, but MVC is not required to use Razor. This is pretty slick processing of doing email templates
As the article identifies, "The best thing of Razor is that unlike its predecessor(webforms) it is not tied with the web environment, we can easily host it outside the web and use it as template engine for various purpose. "
Generating HTML emails with RazorEngine - Part 01 - Introduction
Leveraging Razor Templates Outside of ASP.NET: They’re Not Just for HTML Anymore!
Smarter email templates in ASP.NET with RazorEngine
Similar Stackoverflow QA
I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.
I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.
So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.
I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.
UPDATE: Following your comment, it is not currently possible to change the default registry, see this issue for more info.
You should be able to do this, substituting the host and port to your own:
docker pull localhost:5000/registry-demo
If the server is remote/has auth you may need to log into the server with:
docker login https://<YOUR-DOMAIN>:8080
Then running:
docker pull <YOUR-DOMAIN>:8080/test-image
You can also remove the line
require: 'ngModel',
if you don't need ngModel
in this directive. Removing ngModel
will allow you to make a directive without thatngModel
error.
And this famous code from a famous JS Ninja
var isPrime = n => Array(Math.ceil(Math.sqrt(n)+1)).fill().map((e,i)=>i).slice(2).every(m => n%m);
console.log(Array(100).fill().map((e,i)=>i+1).slice(1).filter(isPrime));
Short answer: you can't. Use MSIEXEC /x
Long answer: When you run the MSI file directly at the command line, all that's happening is that it runs MSIEXEC for you. This association is stored in the registry. You can see a list of associations by (in Windows Explorer) going to Tools / Folder Options / File Types.
For example, you can run a .DOC file from the command line, and WordPad or WinWord will open it for you.
If you look in the registry under HKEY_CLASSES_ROOT\.msi
, you'll see that .MSI files are associated with the ProgID "Msi.Package". If you look in HKEY_CLASSES_ROOT\Msi.Package\shell\Open\command
, you'll see the command line that Windows actually uses when you "run" a .MSI file.
I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled
, it may have left a temp file e.g. default~
(watch the ~
).
Depending on your editor, the file could be named .save
or something like it. Just run $ ls -lah
to see which files are unintended to be there and remove them (Thanks @Tisch for this).
Delete this file, and it will solve your problem.
You can bind the json to a POJO using MappingJacksonHttpMessageConverter
. Thus your controller signature can read :-
public ResponseEntity<Boolean> saveData(@RequestBody RequestDTO req)
Where RequestDTO needs to be a bean appropriately annotated to work with jackson serializing/deserializing. Your *-servlet.xml file should have the Jackson message converter registered in RequestMappingHandler as follows :-
<list >
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:
The Map object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.
As you mentioned, you can easily create an instance of Map using new keyword... In your case:
let myMap = new Map().set('a', 1).set('b', 2);
So let's see...
The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...
Map has many methods which you can use, like set()
which you already used to assign the key values...
One of them is keys()
which returns all the keys...
In your case, it will return:
MapIterator {"a", "b"}
and you easily convert them to an Array using ES6 ways, like spread operator...
const b = [...myMap.keys()];
Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.
Another simple solution is to use map()
as follows:
tensor_shape = map(int, my_tensor.shape)
This converts all the Dimension
objects to int
Try string manipulation:
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
console.log(newTxt[i].split(')')[0]);
}
or regex (which is somewhat slow compare to the above)
var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
var str = matches[i];
console.log(str.substring(1, str.length - 1));
}
This is an ultimate solution to set the border color of a TextBox:
public class BorderedTextBox : UserControl
{
TextBox textBox;
public BorderedTextBox()
{
textBox = new TextBox()
{
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(-1, -1),
Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
AnchorStyles.Left | AnchorStyles.Right
};
Control container = new ContainerControl()
{
Dock = DockStyle.Fill,
Padding = new Padding(-1)
};
container.Controls.Add(textBox);
this.Controls.Add(container);
DefaultBorderColor = SystemColors.ControlDark;
FocusedBorderColor = Color.Red;
BackColor = DefaultBorderColor;
Padding = new Padding(1);
Size = textBox.Size;
}
public Color DefaultBorderColor { get; set; }
public Color FocusedBorderColor { get; set; }
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
protected override void OnEnter(EventArgs e)
{
BackColor = FocusedBorderColor;
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
BackColor = DefaultBorderColor;
base.OnLeave(e);
}
protected override void SetBoundsCore(int x, int y,
int width, int height, BoundsSpecified specified)
{
base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
}
}
REPLACE(REPLACE(a.CUST_ADDRESS1,CHR(10),' '),CHR(13),' ') as ADDRESS
After reading through the answers, I'm going to use:
(L[n:] or [somedefault])[0]
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
<a href="#" style="text-decoration:none !important; text-decoration:none;">BOOK NOW</a>
Outlook will strip out the style with !important
tag leaving the regular style, thus no underline. The !important
tag will over rule the web based email clients' default style, thus leaving no underline.
There are tools that should help you find your leak, like JProbe, YourKit, AD4J or JRockit Mission Control. The last is the one that I personally know best. Any good tool should let you drill down to a level where you can easily identify what leaks, and where the leaking objects are allocated.
Using HashTables, Hashmaps or similar is one of the few ways that you can acually leak memory in Java at all. If I had to find the leak by hand I would peridically print the size of my HashMaps, and from there find the one where I add items and forget to delete them.
The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt")
, just build the path to the file yourself.
Let the user pass in the base directory, read it from a config file, fall back to user.dir
if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.
This can be done in three simple steps:
1) Add item id with url
tag:
{% for item in post %}
<tr>
<th>{{ item.id }}</th>
<td>{{ item.title }}</td>
<td>{{ item.body }}</td>
<td>
<a href={% url 'edit' id=item.id %}>Edit</a>
<a href={% url 'delete' id=item.id %}>Delete</a>
</td>
</tr>
{% endfor %}
2) Add path to urls.py:
path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')
3) Use the id on views.py:
def delete(request, id):
obj = post.objects.get(id=id)
obj.delete()
return redirect('dashboard')
First, note that the function parameter named i
and the variable named i
in main()
are two different variables. I think that doesn't matter that much to the present discussion, but it's important to know.
Second, you use the postincrement operator in fun()
. That means the result of the expression is the value before i
is incremented; the final value 11 of i
is simply discarded, and the function returns 10. The variable i
back in main, being a different variable, is assigned the value 10, which you then decrement to get 9.
WARNING: Never use this method for untrusted input, such as URL parameters.
You can use the eval()
function.
Directly pass your string to eval()
function.
console.log(eval('true'), typeof eval('true'))
console.log(eval('false'), typeof eval('false'))
_x000D_
All the order-preserving approaches I've seen here so far either use naive comparison (with O(n^2) time-complexity at best) or heavy-weight OrderedDicts
/set
+list
combinations that are limited to hashable inputs. Here is a hash-independent O(nlogn) solution:
Update added the key
argument, documentation and Python 3 compatibility.
# from functools import reduce <-- add this import on Python 3
def uniq(iterable, key=lambda x: x):
"""
Remove duplicates from an iterable. Preserves order.
:type iterable: Iterable[Ord => A]
:param iterable: an iterable of objects of any orderable type
:type key: Callable[A] -> (Ord => B)
:param key: optional argument; by default an item (A) is discarded
if another item (B), such that A == B, has already been encountered and taken.
If you provide a key, this condition changes to key(A) == key(B); the callable
must return orderable objects.
"""
# Enumerate the list to restore order lately; reduce the sorted list; restore order
def append_unique(acc, item):
return acc if key(acc[-1][1]) == key(item[1]) else acc.append(item) or acc
srt_enum = sorted(enumerate(iterable), key=lambda item: key(item[1]))
return [item[1] for item in sorted(reduce(append_unique, srt_enum, [srt_enum[0]]))]
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.
Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference
Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.
Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin
A constructor initializes an object when it is created . It has the same name as its class and is syntactically similar to a method , but constructor have no expicit return type.Typically , we use constructor to give initial value to the instance variables defined by the class , or to perform any other startup procedures required to make a fully formed object.
Here is an example of constructor:
class queen(){
int beauty;
queen(){
beauty = 98;
}
}
class constructor demo{
public static void main(String[] args){
queen arth = new queen();
queen y = new queen();
System.out.println(arth.beauty+" "+y.beauty);
}
}
output is:
98 98
Here the construcor is :
queen(){
beauty =98;
}
Now the turn of parameterized constructor.
class queen(){
int beauty;
queen(int x){
beauty = x;
}
}
class constructor demo{
public static void main(String[] args){
queen arth = new queen(100);
queen y = new queen(98);
System.out.println(arth.beauty+" "+y.beauty);
}
}
output is:
100 98
event.target
to get the element
window.onclick = e => {
console.log(e.target); // to get the element
console.log(e.target.tagName); // to get the element tag name alone
}
to get the text from clicked element
window.onclick = e => {
console.log(e.target.innerText);
}
To get information about the table's column, you can use:
\dt+ [tablename]
To get information about the datatype in the table, you can use:
\dT+ [datatype]
Oddly nobody mentioned mobx
. The idea is similar to redux
. If I have a piece of data that multiple components are subscribed to it, then I can use this data to drive multiple components.
This is the best way for me:
cat filename.tsv |
while read FILENAME
do
sudo find /PATH_FROM/ -name "$FILENAME" -maxdepth 4 -exec cp '{}' /PATH_TO/ \; ;
done
You can use the CorFlags CLI tool (for instance, C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\CorFlags.exe) to determine the status of an assembly, based on its output and opening an assembly as a binary asset you should be able to determine where you need to seek to determine if the 32BIT flag is set to 1 (x86) or 0 (Any CPU or x64, depending on PE
):
Option | PE | 32BIT
----------|-------|---------
x86 | PE32 | 1
Any CPU | PE32 | 0
x64 | PE32+ | 0
The blog post x64 Development with .NET has some information about corflags
.
Even better, you can use Module.GetPEKind
to determine whether an assembly is PortableExecutableKinds
value PE32Plus
(64-bit), Required32Bit
(32-bit and WOW), or ILOnly
(any CPU) along with other attributes.
You can do this with jQuery :
$(document).ready(function(){_x000D_
_x000D_
$('.claimedRight').each(function (f) {_x000D_
_x000D_
var newstr = $(this).text().substring(0,20);_x000D_
$(this).text(newstr);_x000D_
_x000D_
});_x000D_
})
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title></title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<span class="claimedRight" maxlength="20">Hello this is the first test string. _x000D_
</span><br>_x000D_
<span class="claimedRight" maxlength="20">Hello this is the second test string. _x000D_
</span>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Here is another illustrative example:
>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!
It exploits the fact that if i
evaluates to False
for 0
and to True
for all other values generated by the function range()
. Therefore the list comprehension evaluates as follows:
>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']
I looked at several of the options. Here are my two favorites, because I needed to round the value.
,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2 = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy ---------
--- Hank Freeman : [email protected]
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
SELECT
FileGroupName = DS.name
,FileGroupType =
CASE DS.[type]
WHEN 'FG' THEN 'Filegroup'
WHEN 'FD' THEN 'Filestream'
WHEN 'FX' THEN 'Memory-optimized'
WHEN 'PS' THEN 'Partition Scheme'
ELSE 'Unknown'
END
,SchemaName = SCH.name
,TableName = OBJ.name
,IndexType =
CASE IDX.[type]
WHEN 0 THEN 'Heap'
WHEN 1 THEN 'Clustered'
WHEN 2 THEN 'Nonclustered'
WHEN 3 THEN 'XML'
WHEN 4 THEN 'Spatial'
WHEN 5 THEN 'Clustered columnstore'
WHEN 6 THEN 'Nonclustered columnstore'
WHEN 7 THEN 'Nonclustered hash'
END
,IndexName = IDX.name
,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','') --- MUST show for all types when no Primary key
--,( Case WHEN IDX.[type] IN (2,6,7) then 0 else p.rows end )as Rowcounts_T
,AllocationDesc = AU.type_desc
/*
,RowCounts = p.rows --- MUST show for all types when no Primary key
,TotalSizeKB2 = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
,UsedSizeKB = Cast(Round(SUM(AU.used_pages / 0.128),0)as int)
,DataSizeKB = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
--replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
,TotalSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
,UsedSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','')
,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
,DataSizeKB2 = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
,DataSizeKB3 = format(SUM(AU.data_pages / 0.128),'##,##0')
--SELECT Format(1234567.8, '##,##0.00')
---
,is_default = CONVERT(INT,DS.is_default)
,is_read_only = CONVERT(INT,DS.is_read_only)
FROM
sys.filegroups DS -- you could also use sys.data_spaces
LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
LEFT JOIN sys.partitions PA
ON (AU.[type] IN (1,3) AND
AU.container_id = PA.hobt_id) OR
(AU.[type] = 2 AND
AU.container_id = PA.[partition_id])
LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
LEFT JOIN sys.indexes IDX
ON PA.[object_id] = IDX.[object_id] AND
PA.index_id = IDX.index_id
-----
INNER JOIN
sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
WHERE
OBJ.type_desc = 'USER_TABLE' -- only include user tables
OR
DS.[type] = 'FD' -- or the filestream filegroup
GROUP BY
DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type] ,DS.is_default ,DS.is_read_only -- discard different allocation units
,p.rows ,AU.type_desc ---
ORDER BY
DS.name ,SCH.name ,OBJ.name ,IDX.name
---
;
HTML
<div id="fixedbtn"><button type="button" value="Delete"></button></div>
CSS
#fixedbtn{
position: fixed;
margin: 0px 10px 0px 10px;
width: 10%;
}
If you are working on windows, you can use pywin32
(old link: see update below).
I found an example here:
import win32com.client
wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
print usb.DeviceID
Update Apr 2020:
'pywin32' release versions from 218 and up can be found here at github. Current version 227.
You can do as follows
For a single repo
git config http.sslVerify false
For all repo
git config --global http.sslVerify false
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
You might just use a Boolean flag to indicate when to end the while loop. Break
and go to
were reasons for software being to hard to maintain - the software-crisis(tm) - and should be avoided, and easily can be too.
It's a question if you are pragmatic or not. Pragmatic coders might just use break in that simple situation.
But it's good to get the habbit of not using them, else you might use them out of habbit in unsuitable situations, like in complicated nested loops where readability and maintainability of your code becomes harder by using break
.
As opposed to most of the answers here, I actually think that PUT should return the updated resource (in addition to the HTTP code of course).
The reason why you would want to return the resource as a response for PUT operation is because when you send a resource representation to the server, the server can also apply some processing to this resource, so the client would like to know how does this resource look like after the request completed successfully. (otherwise it will have to issue another GET request).
Use FUNCTION:
CREATE OR REPLACE FUNCTION test_function
RETURN VARCHAR2 IS
BEGIN
RETURN 'This is being returned from a function';
END test_function;
The Main Reason for the denying permission is that we don’t have permission for drawing over another apps,We have to provide the permission for the Drawing over other apps that can be done by the following code
Request code for Permission
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
add this in your MainActivity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
askPermission();
}
private void askPermission() {
Intent intent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
Add this also
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE){
if(!Settings.canDrawOverlays(this)){
askPermission();
}
}
}
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
return word
def anotherFunction():
for letter in word:
print("_",end=" ")
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
I benchmarked the answers of Anthony Damico, Brian Diggs and data_steve on a small sample tbl_df
and got the following results.
> data <- data.frame('a' = 1:3,
+ 'b' = c('a','b','c'),
+ 'c' = c('d', 'e', 'f'),
+ 'd' = c('g', 'h', 'i'))
> data <- tbl_df(data)
> cols <- c("b", "c", "d")
> microbenchmark(
+ do.call(paste, c(data[cols], sep="-")),
+ apply( data[ , cols ] , 1 , paste , collapse = "-" ),
+ tidyr::unite_(data, "x", cols, sep="-")$x,
+ times=1000
+ )
Unit: microseconds
expr min lq mean median uq max neval
do.call(paste, c(data[cols], sep = "-")) 65.248 78.380 93.90888 86.177 99.3090 436.220 1000
apply(data[, cols], 1, paste, collapse = "-") 223.239 263.044 313.11977 289.514 338.5520 743.583 1000
tidyr::unite_(data, "x", cols, sep = "-")$x 376.716 448.120 556.65424 501.877 606.9315 11537.846 1000
However, when I evaluated on my own tbl_df
with ~1 million rows and 10 columns the results were quite different.
> microbenchmark(
+ do.call(paste, c(data[c("a", "b")], sep="-")),
+ apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" ),
+ tidyr::unite_(data, "c", c("a", "b"), sep="-")$c,
+ times=25
+ )
Unit: milliseconds
expr min lq mean median uq max neval
do.call(paste, c(data[c("a", "b")], sep="-")) 930.7208 951.3048 1129.334 997.2744 1066.084 2169.147 25
apply( data[ , c("a", "b") ] , 1 , paste , collapse = "-" ) 9368.2800 10948.0124 11678.393 11136.3756 11878.308 17587.617 25
tidyr::unite_(data, "c", c("a", "b"), sep="-")$c 968.5861 1008.4716 1095.886 1035.8348 1082.726 1759.349 25
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
Here is another answer:
With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With
Source: Show the
Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :
As of the November 2016 release, Raspbian has the SSH server disabled by default.
There are now multiple ways to enable it. Choose one:
- Launch
Raspberry Pi Configuration
from thePreferences
menu- Navigate to the
Interfaces
tab- Select
Enabled
next toSSH
- Click
OK
raspi-config
- Enter
sudo raspi-config
in a terminal window- Select
Interfacing Options
- Navigate to and select
SSH
- Choose
Yes
- Select
Ok
- Choose
Finish
systemctl
sudo systemctl enable ssh sudo systemctl start ssh
For headless setup, SSH can be enabled by placing a file named
ssh
, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for thessh
file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.
If anybody is looking to replace a button with something like a loading animation when clicked (for example when a "Submit" button submits the form in the dialog) - you can replace the button with your image like this:
...
buttons: {
"Submit": function(evt) {
$(evt.target).closest('button').replaceWith('<img src="loading.gif">');
}
}
The code you posted gives the critical value for a one-sided test (Hence the answer to you question is simply:
abs(qt(0.25, 40)) # 75% confidence, 1 sided (same as qt(0.75, 40))
abs(qt(0.01, 40)) # 99% confidence, 1 sided (same as qt(0.99, 40))
Note that the t-distribution is symmetric. For a 2-sided test (say with 99% confidence) you can use the critical value
abs(qt(0.01/2, 40)) # 99% confidence, 2 sided
like this?
doc.addEeventListener("touchstart", function(){
// your code ...
}, false);
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.
Encountered a similar problem today. Did not see my fix listed here, so I thought I'd share.
Root could not erase a file.
I did my research. Turns out there's something called an immutable bit.
# lsattr /path/file
----i-------- /path/file
#
This bit being configured prevents even root from modifying/removing it.
To remove this I did:
# chattr -i /path/file
After that I could rm the file.
In reverse, it's a neat trick to know if you have something you want to keep from being gone.
:)
Also internationalization.
I fooled around with this some a while back. Did this in my model:
[Display(Name = "XXX", ResourceType = typeof(Labels))]
I had a separate class library for all the resources, so I had Labels.resx, Labels.culture.resx, etc.
In there I had key = XXX, value = "meaningful string in that culture."
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
In the latest version of the SDK, you would use the setBackgroundResource
method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
You need the return so the true/false gets passed up to the form's submit event (which looks for this and prevents submission if it gets a false).
Lets look at some standard JS:
function testReturn() { return false; }
If you just call that within any other code (be it an onclick handler or in JS elsewhere) it will get back false, but you need to do something with that value.
...
testReturn()
...
In that example the return value is coming back, but nothing is happening with it. You're basically saying execute this function, and I don't care what it returns. In contrast if you do this:
...
var wasSuccessful = testReturn();
...
then you've done something with the return value.
The same applies to onclick handlers. If you just call the function without the return in the onsubmit, then you're saying "execute this, but don't prevent the event if it return false." It's a way of saying execute this code when the form is submitted, but don't let it stop the event.
Once you add the return, you're saying that what you're calling should determine if the event (submit) should continue.
This logic applies to many of the onXXXX events in HTML (onclick, onsubmit, onfocus, etc).
If you want to change a color to single column try this:
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;
dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;
What about using a combination of some/findIndex and indexOf?
So something like this:
var array1 = ["apple","banana","orange"];
var array2 = ["grape", "pineapple"];
var found = array1.some(function(v) { return array2.indexOf(v) != -1; });
To make it more readable you could add this functionality to the Array object itself.
Array.prototype.indexOfAny = function (array) {
return this.findIndex(function(v) { return array.indexOf(v) != -1; });
}
Array.prototype.containsAny = function (array) {
return this.indexOfAny(array) != -1;
}
Note: If you'd want to do something with a predicate you could replace the inner indexOf with another findIndex and a predicate
From the Tools menu, click NuGet Package Manger, then click Package Manager Console (PMC). Enter the following commands in the PMC.
Enable-Migrations Add-Migration Init Update-Database Run the application. The solution to the problem is from here
Your class Delivery
has no access modifier, which means it defaults to internal
. If you then try to expose a property of that type as public
, it won't work. Your type (class) needs to have the same, or higher access as your property.
More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx
use below code
Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
Java 8 LocalDate class is another option to get the year from a java.util.Date,
int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();
Another option is,
int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
insert into bookmarks (users_id, lessoninfo_id)
select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;
This is the fastest way.
For some other SQL engines, you can use a Dummy table containing 1 record. e.g:
select 1, 167 from ONE_RECORD_DUMMY_TABLE
Try this it might solve your problem.
Css:
.item{padding-top:1px;}
.jobs .item:hover {
background: #e1e1e1;
border-top: 1px solid #d0d0d0;
padding-top:0;
}
HTML:
<div class="jobs">
<div class="item">
content goes here
</div>
</div>
See fiddle for output: http://jsfiddle.net/dLDNA/
sort
method has been deprecated and replaced with sort_values
. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])
df.sort_values(by=['Date'])
Note: to sort in-place and/or in a descending order (the most recent first):
df.sort_values(by=['Date'], inplace=True, ascending=False)
if (condition){ // where condition evaluates to true
return false
}
see similar question asked 3 days ago.
First I recommand you can try use print and observe the action:
for i in range(0, 5, 1):
print i
the result:
0
1
2
3
4
You can understand the function principle.
In fact, range
scan range is from 0
to 5-1
.
It equals 0 <= i < 5
When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.
You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.
for i in range(5, 0, -1):
print i
the result:
5
4
3
2
1
Thus it can be seen, it equals 5 >= i > 0
You want to implement your java code in python:
for (int index = last-1; index >= posn; index--)
It should code this:
for i in range(last-1, posn-1, -1)
In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.
select 'Tag', counts.cnt
from
(
select count(*) as cnt, 'Tag'
from 'images-tags'
group by 'tag'
) counts
order by counts.cnt desc
In my case UAC was disabled (the infamous regedit trick) and so the installer clearly could not handle it.
You could revert back to UAC for the installer, or simply try launching it as admin, it worked for me.
Below worked for me:
<head>
<meta charset="UTF-8">
<meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
</head>
One could also do a raise NotImplementedError()
inside the child method of an @abstractmethod
-decorated base class method.
Imagine writing a control script for a family of measurement modules (physical devices). The functionality of each module is narrowly-defined, implementing just one dedicated function: one could be an array of relays, another a multi-channel DAC or ADC, another an ammeter etc.
Much of the low-level commands in use would be shared between the modules for example to read their ID numbers or to send a command to them. Let's see what we have at this point:
from abc import ABC, abstractmethod #< we'll make use of these later
class Generic(ABC):
''' Base class for all measurement modules. '''
# Shared functions
def __init__(self):
# do what you must...
def _read_ID(self):
# same for all the modules
def _send_command(self, value):
# same for all the modules
We then realise that much of the module-specific command verbs and, therefore, the logic of their interfaces is also shared. Here are 3 different verbs whose meaning would be self-explanatory considering a number of target modules.
get(channel)
relay: get the on/off status of the relay on channel
DAC: get the output voltage on channel
ADC: get the input voltage on channel
enable(channel)
relay: enable the use of the relay on channel
DAC: enable the use of the output channel on channel
ADC: enable the use of the input channel on channel
set(channel)
relay: set the relay on channel
on/off
DAC: set the output voltage on channel
ADC: hmm... nothing logical comes to mind.
I'd argue that there is a strong case for the above verbs to be shared across the modules
as we saw that their meaning is evident for each one of them. I'd continue writing my
base class Generic
like so:
class Generic(ABC): # ...continued
@abstractmethod
def get(self, channel):
pass
@abstractmethod
def enable(self, channel):
pass
@abstractmethod
def set(self, channel):
pass
We now know that our subclasses will all have to define these methods. Let's see what it could look like for the ADC module:
class ADC(Generic):
def __init__(self):
super().__init__() #< applies to all modules
# more init code specific to the ADC module
def get(self, channel):
# returns the input voltage measured on the given 'channel'
def enable(self, channel):
# enables accessing the given 'channel'
You may now be wondering:
But this won't work for the ADC module as
set
makes no sense there as we've just seen this above!
You're right: not implementing set
is not an option as Python would then fire the error below
when you tried to instantiate your ADC object.
TypeError: Can't instantiate abstract class 'ADC' with abstract methods 'set'
So you must implement something, because we made set
an enforced verb (aka '@abstractmethod'),
which is shared by two other modules but, at the same time, you must also not implement anything as
set
does not make sense for this particular module.
By completing the ADC class like this:
class ADC(Generic): # ...continued
def set(self, channel):
raise NotImplementedError("Can't use 'set' on an ADC!")
You are doing three very good things at once:
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
In SQL Server 2012 you have IIF
, e.g you can use it like
SELECT IIF(field IS NULL, 1, 0) AS IsNull
The same way you can check if field is empty.
Also: git diff master..feature foo
Since git diff foo master:foo
doesn't work on directories for me.
"You can store as many objects as you want within a bucket, and write, read, and delete objects in your bucket. Objects can be up to 5 terabytes in size."
from http://aws.amazon.com/s3/details/ (as of Mar 4th 2015)
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding
(or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:
sys.stdout.buffer.write(some_bytes_object)
This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.
Just use textarea Id by its type like it:
$("textarea#samplID").val()
I will try to go a little deeper than other answers.
Even if JS had better hashing support it would not magically hash everything perfectly, in many cases you will have to define your own hash function. For example Java has good hashing support, but you still have to think and do some work.
One problem is with the term hash/hashcode ... there is cryptographic hashing and non-cryptographic hashing. The other problem, is you have to understand why hashing is useful and how it works.
When we talk about hashing in JavaScript or Java most of the time we are talking about non-cryptographic hashing, usually about hashing for hashmap/hashtable (unless we are working on authentication or passwords, which you could be doing server-side using NodeJS ...).
It depends on what data you have and what you want to achieve.
Your data has some natural "simple" uniqueness:
Your data has some natural "composite" uniqueness:
You have no idea what your data will be:
There is no magically efficient hashing technique for unknown data, in some cases it is quite easy, in other cases you may have to think twice. So even if JavaScript/ECMAScript adds more support, there is no magic language solution for this problem.
In practice you need two things: enough uniqueness, enough speed
In addition to that it is great to have: "hashcode equal if objects are equal"
To Replace backslash at particular location:
if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
stringValue=stringValue.substring(0,location-1);
}
Here is the solution I'm using:
const result = `${ window.location.protocol }//${ window.location.host }`;
EDIT:
To add cross-browser compatibility, use the following:
const result = `${ window.location.protocol }//${ window.location.hostname + (window.location.port ? ':' + window.location.port: '') }`;
Convert your solution to x64. If you still face an issue, grant max length to everything that throws an exception like below :
var jsSerializer = new JavaScriptSerializer();
jsSerializer.MaxJsonLength = Int32.MaxValue;