I'm very thoroughly investigating the matter of accuracy/rssi/proximity with iBeacons and I really really think that all the resources in the Internet (blogs, posts in StackOverflow) get it wrong.
davidgyoung (accepted answer, > 100 upvotes) says:
Note that the term "accuracy" here is iOS speak for distance in meters.
Actually, most people say this but I have no idea why! Documentation makes it very very clear that CLBeacon.proximity:
Indicates the one sigma horizontal accuracy in meters. Use this property to differentiate between beacons with the same proximity value. Do not use it to identify a precise location for the beacon. Accuracy values may fluctuate due to RF interference.
Let me repeat: one sigma accuracy in meters. All 10 top pages in google on the subject has term "one sigma" only in quotation from docs, but none of them analyses the term, which is core to understand this.
Very important is to explain what is actually one sigma accuracy. Following URLs to start with: http://en.wikipedia.org/wiki/Standard_error, http://en.wikipedia.org/wiki/Uncertainty
In physical world, when you make some measurement, you always get different results (because of noise, distortion, etc) and very often results form Gaussian distribution. There are two main parameters describing Gaussian curve:
one sigma is another way to describe how narrow/wide is gaussian curve.
It simply says that if mean of measurement is X, and one sigma is s, then 68% of all measurements will be between X - s
and X + s
.
Example. We measure distance and get a gaussian distribution as a result. The mean is 10m. If s is 4m, then it means that 68% of measurements were between 6m and 14m.
When we measure distance with beacons, we get RSSI and 1-meter calibration value, which allow us to measure distance in meters. But every measurement gives different values, which form gaussian curve. And one sigma (and accuracy) is accuracy of the measurement, not distance!
It may be misleading, because when we move beacon further away, one sigma actually increases because signal is worse. But with different beacon power-levels we can get totally different accuracy values without actually changing distance. The higher power, the less error.
There is a blog post which thoroughly analyses the matter: http://blog.shinetech.com/2014/02/17/the-beacon-experiments-low-energy-bluetooth-devices-in-action/
Author has a hypothesis that accuracy is actually distance. He claims that beacons from Kontakt.io are faulty beacuse when he increased power to the max value, accuracy value was very small for 1, 5 and even 15 meters. Before increasing power, accuracy was quite close to the distance values. I personally think that it's correct, because the higher power level, the less impact of interference. And it's strange why Estimote beacons don't behave this way.
I'm not saying I'm 100% right, but apart from being iOS developer I have degree in wireless electronics and I think that we shouldn't ignore "one sigma" term from docs and I would like to start discussion about it.
It may be possible that Apple's algorithm for accuracy just collects recent measurements and analyses the gaussian distribution of them. And that's how it sets accuracy. I wouldn't exclude possibility that they use info form accelerometer to detect whether user is moving (and how fast) in order to reset the previous distribution distance values because they have certainly changed.
With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:
Prefs > Package Control
. Here you can install, remove or see a list of all installed packages.Prefs > Package Settings
. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.Your sp_test: Return fullname
USE [MY_DB]
GO
IF (OBJECT_ID('[dbo].[sp_test]', 'P') IS NOT NULL)
DROP PROCEDURE [dbo].sp_test;
GO
CREATE PROCEDURE [dbo].sp_test
@name VARCHAR(20),
@last_name VARCHAR(30),
@full_name VARCHAR(50) OUTPUT
AS
SET @full_name = @name + @last_name;
GO
In your sp_main
...
DECLARE @my_name VARCHAR(20);
DECLARE @my_last_name VARCHAR(30);
DECLARE @my_full_name VARCHAR(50);
...
EXEC sp_test @my_name, @my_last_name, @my_full_name OUTPUT;
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
titolorecuperato = (TextView) findViewById(R.id.textView);
String stitolo = titolorecuperato.getText().toString();
Button btnHome = (Button) findViewById(R.id.button);
btnHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
same thing as Nic007 said before.
You do need to write code inside "onCreate" method. Sorry me too for the indent... (first comment here)
printf
is great, but people forget about it.
$ for num in 1 10 100 1000 10000 100000 1000000; do printf "%10s %s\n" $num "foobar"; done
1 foobar
10 foobar
100 foobar
1000 foobar
10000 foobar
100000 foobar
1000000 foobar
$ for((i=0;i<array_size;i++));
do
printf "%10s %10d %10s" stringarray[$i] numberarray[$i] anotherfieldarray[%i]
done
Notice I used %10s
for strings. %s
is the important part. It tells it to use a string. The 10
in the middle says how many columns it is to be. %d
is for numerics (digits).
man 1 printf
for more info.
I realize this is a very old question, but I stumbled across this problem today and I got it to work with
<div style="text-align:center;">
<button>button1</button>
<button>button2</button>
</div>
Cheers, Mark
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
My app closed with above code.
Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.
You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.
You can use the ProcessLifecycleOwner attaching a lifecycle observer to it.
public class ForegroundLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onAppCreated() {
Timber.d("onAppCreated() called");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppStarted() {
Timber.d("onAppStarted() called");
}
@OnLifecycleEvent(Event.ON_RESUME)
public void onAppResumed() {
Timber.d("onAppResumed() called");
}
@OnLifecycleEvent(Event.ON_PAUSE)
public void onAppPaused() {
Timber.d("onAppPaused() called");
}
@OnLifecycleEvent(Event.ON_STOP)
public void onAppStopped() {
Timber.d("onAppStopped() called");
}
}
then on the onCreate()
of your Application class you call this:
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ForegroundLifecycleObserver());
with this you will be able to capture the events of ON_PAUSE
and ON_STOP
of your application that happen when it goes in background.
With "thousands of rows" your best bet would obviously be to do server side paging. When I looked into the different AngularJs table/grid options a while back there were three clear favourites:
All three are good, but implemented differently. Which one you pick will probably be more based on personal preference than anything else.
ng-grid is probably the most known due to its association with angular-ui, but I personally prefer ng-table, I really like their implementation and how you use it, and they have great documentation and examples available and actively being improved.
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
Android Device Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2. To start the standalone Device Monitor application in Android Studio 3.1 and lower you can run android-sdk/tools/monitor.bat
Instead of shifting by one position you can make this function more general using module like this.
int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;
for(int i=0; i<original.length;i++)
reordered[i] = original[(shift+i)%original.length];
Have you looked in to web deployment projects?
There is a version for VS2005 as well, if you are not on 2008.
From JPA 2.1 , JPA supports to call stored procedures using the dynamic StoredProcedureQuery, and the declarative @NamedStoredProcedureQuery.
Improving on Reza's answer:
<html><head><style>
.splitter {
width: 100%;
height: 100px;
display: flex;
}
#separator {
cursor: col-resize;
background-color: #aaa;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
background-repeat: no-repeat;
background-position: center;
width: 10px;
height: 100%;
/* Prevent the browser's built-in drag from interfering */
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#first {
background-color: #dde;
width: 20%;
height: 100%;
min-width: 10px;
}
#second {
background-color: #eee;
width: 80%;
height: 100%;
min-width: 10px;
}
</style></head><body>
<div class="splitter">
<div id="first"></div>
<div id="separator" ></div>
<div id="second" ></div>
</div>
<script>
// A function is used for dragging and moving
function dragElement(element, direction)
{
var md; // remember mouse down info
const first = document.getElementById("first");
const second = document.getElementById("second");
element.onmousedown = onMouseDown;
function onMouseDown(e)
{
//console.log("mouse down: " + e.clientX);
md = {e,
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
firstWidth: first.offsetWidth,
secondWidth: second.offsetWidth
};
document.onmousemove = onMouseMove;
document.onmouseup = () => {
//console.log("mouse up");
document.onmousemove = document.onmouseup = null;
}
}
function onMouseMove(e)
{
//console.log("mouse move: " + e.clientX);
var delta = {x: e.clientX - md.e.clientX,
y: e.clientY - md.e.clientY};
if (direction === "H" ) // Horizontal
{
// Prevent negative-sized elements
delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
md.secondWidth);
element.style.left = md.offsetLeft + delta.x + "px";
first.style.width = (md.firstWidth + delta.x) + "px";
second.style.width = (md.secondWidth - delta.x) + "px";
}
}
}
dragElement( document.getElementById("separator"), "H" );
</script></body></html>
_x000D_
I needed to do this on a Cygwin setup on Windows 7 and found that I got syntax errors with the suggestions from above that I tried (though I may have missed a working option). However, this solution straight from Ubuntu forums worked out of the can :-)
ls | while read upName; do loName=`echo "${upName}" | tr '[:upper:]' '[:lower:]'`; mv "$upName" "$loName"; done
(NB: I had previously replaced whitespace with underscores using:
for f in *\ *; do mv "$f" "${f// /_}"; done
)
Just for super noobs like me wondering how or what people meant by
PRAGMA table_info('table_name')
You want to use use that as your prepare statement as shown below. Doing so selects a table that looks like this except is populated with values pertaining to your table.
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
Where id and name are the actual names of your columns. So to get that value you need to select column name by using:
//returns the name
sqlite3_column_text(stmt, 1);
//returns the type
sqlite3_column_text(stmt, 2);
Which will return the current row's column's name. To grab them all or find the one you want you need to iterate through all the rows. Simplest way to do so would be in the manner below.
//where rc is an int variable if wondering :/
rc = sqlite3_prepare_v2(dbPointer, "pragma table_info ('your table name goes here')", -1, &stmt, NULL);
if (rc==SQLITE_OK)
{
//will continue to go down the rows (columns in your table) till there are no more
while(sqlite3_step(stmt) == SQLITE_ROW)
{
sprintf(colName, "%s", sqlite3_column_text(stmt, 1));
//do something with colName because it contains the column's name
}
}
I solved just by: given correct host and port so:
in Listener on address 2 then copy host to Oracle Developer
finally connect to oracle
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
You either have to make the method Shared
or use an instance of the class General
:
Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)
or
General.updateDynamics(get_prospect.dynamicsID)
Public Shared Sub updateDynamics(dynID As Int32)
' ... '
End Sub
As Dan pointed out: you need to convert them to binary and then convert/correct the encoding.
E.g., for utf8 stored as latin1 the following SQL will fix it:
UPDATE table
SET field = CONVERT( CAST(field AS BINARY) USING utf8)
WHERE $broken_field_condition
Open inspect mode before navigating to the page. It worked.hehe
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}
You can extract the html string from the PartialViewResult object, similar to the answer to this thread:
PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.
Using the code from the thread above, you would be able to use:
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest())
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
}
return View(model);
}
Redirects the browser to the specified URL.
This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:
return Yii::$app->getResponse()->redirect($url);
In other places, if you want to send out the "Location" header immediately, you should use the following code:
Yii::$app->getResponse()->redirect($url)->send();
return;
git diff `git merge-base master branch`..branch
Merge base is the point where branch
diverged from master
.
Git diff supports a special syntax for this:
git diff master...branch
You must not swap the sides because then you would get the other branch. You want to know what changed in branch
since it diverged from master
, not the other way round.
Loosely related:
Note that ..
and ...
syntax does not have the same semantics as in other Git tools. It differs from the meaning specified in man gitrevisions
.
Quoting man git-diff
:
git diff [--options] <commit> <commit> [--] [<path>…]
This is to view the changes between two arbitrary
<commit>
.
git diff [--options] <commit>..<commit> [--] [<path>…]
This is synonymous to the previous form. If
<commit>
on one side is omitted, it will have the same effect as usingHEAD
instead.
git diff [--options] <commit>...<commit> [--] [<path>…]
This form is to view the changes on the branch containing and up to the second
<commit>
, starting at a common ancestor of both<commit>
. "git diff A...B
" is equivalent to "git diff $(git-merge-base A B) B
". You can omit any one of<commit>
, which has the same effect as usingHEAD
instead.Just in case you are doing something exotic, it should be noted that all of the
<commit>
in the above description, except in the last two forms that use ".." notations, can be any<tree>
.For a more complete list of ways to spell
<commit>
, see "SPECIFYING REVISIONS" section ingitrevisions[7]
. However, "diff" is about comparing two endpoints, not ranges, and the range notations ("<commit>..<commit>
" and "<commit>...<commit>
") do not mean a range as defined in the "SPECIFYING RANGES" section ingitrevisions[7]
.
While I was loading a new image in my asset folder, I just encountered the problem every time.
I run flutter clean
& then restarted the Android Studio. Seems like flutter packages caches the asset folder and there is no mechanism to update the cache when a developer adds a new image in the project (Personal thoughts).
You could use very easily reflection to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;
alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"
But since you use Firebug, why not just use console.log?
I used double quotes for the URL and it worked. So something like
git clone "??http://git.fedorahosted.org/git/ibus-typing-booster.git"
works.. single quotes dont help. It has to be double quotes.
Adding a relative path worked for me:
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json", "My App");
});
Work out what specific properties of a list
you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append()
method?
Look up the abstract base class which describes that particular type in the collections
module.
Use isinstance
:
isinstance(x, collections.MutableSequence)
You might ask "why not just use type(x) == list
?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:
I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck
In other words, you shouldn't require that the objects are list
s, just that they have the methods you will need. The collections
module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence
, for example, will support indexing.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the
XMLHttpRequest
send()
method.
With an XMLHttpRequest
you can set the custom headers and then do the POST
.
It's also much easier to manage native builds. Ant and Maven are effectively Java-only. Some plugins exist for Maven that try to handle some native projects, but they don't do an effective job. Ant tasks can be written that compile native projects, but they are too complex and awkward.
We do Java with JNI and lots of other native bits. Gradle simplified our Ant mess considerably. When we started to introduce dependency management to the native projects it was messy. We got Maven to do it, but the equivalent Gradle code was a tiny fraction of what was needed in Maven, and people could read it and understand it without becoming Maven gurus.
I faced this error once when I defined a class that extended a view but referred to this custom view in the layout file with the wrong name. Instead of <com.example.customview/>
, I had included <com.customview/>
in the XML layout file.
There is a deleted answer on this question that had a useful link: https://help.github.com/articles/duplicating-a-repository
The gist is
0. create the new empty repository (say, on github)
1. make a bare clone of the repository in some temporary location
2. change to the temporary location
3. perform a mirror-push to the new repository
4. change to another location and delete the temporary location
OP's example:
On your local machine
$ cd $HOME
$ git clone --bare https://git.fedorahosted.org/the/path/to/my_repo.git
$ cd my_repo.git
$ git push --mirror https://github.com/my_username/my_repo.git
$ cd ..
$ rm -rf my_repo.git
Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.
if not A[i]:
## do whatever
Anyway if you know the size of your list then you don't need to do all this.
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
This can also happen if there is a php.ini
file in the web app's current working directory. If one has been placed there to change certain settings, it will override the global one.
To avoid this problem, don't use a php.ini
file to change settings; instead you can:
For Swift 4
This code working for me!!
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var imageView: UIImageView!
@IBOutlet var chooseBuuton: UIButton!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
@IBAction func btnClicked() {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum)
{
print("Button capture")
imagePicker.sourceType = .savedPhotosAlbum;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = chosenImage
dismiss(animated: true, completion: nil)
}
}
The simplest solution is to add modal dialog styles to the top of the page or import css with this code:
<style>
.modal-dialog {
position:absolute;
top:50% !important;
transform: translate(0, -50%) !important;
-ms-transform: translate(0, -50%) !important;
-webkit-transform: translate(0, -50%) !important;
margin:auto 50%;
width:40%;
height:40%;
}
</style>
Modal declaration:
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Modal usage:
<a data-toggle="modal" data-target="#exampleModalCenter">
...
</a>
The solution for me (openSUSE Leap 42.3, KDE) was to rename the folder ~/.gnupg
which apparently contained the cached keys and profiles.
After KDE logout/logon the ssh-add/agent is running again and the folder is created from scratch, but the old keys are all gone.
I didn't have success with the other approaches.
Let me share an example which I developed with BS4, thymeleaf and Spring boot.
I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").
First, the thymeleaf snippet:
<div class="form-group">
<label th:for="topicId" th:text="#{label.topic}">Topic</label>
<select class="custom-select"
th:id="topicId" th:name="topicId"
th:field="*{topicId}"
th:errorclass="is-invalid" required>
<option value="" selected
th:text="#{option.select}">Select
</option>
<optgroup th:each="topicGroup : ${topicGroups}"
th:label="${topicGroup}">
<option th:each="topicItem : ${topics}"
th:if="${topicGroup == topicItem.grp} "
th:value="${{topicItem.baseIdentity.id}}"
th:text="${topicItem.name}"
th:selected="${{topicItem.baseIdentity.id==topicId}}">
</option>
</optgroup>
<option th:each="topicIter : ${topics}"
th:if="${topicIter.grp == ''} "
th:value="${{topicIter.baseIdentity.id}}"
th:text="${topicIter.name}"
th:selected="${{topicIter.baseIdentity?.id==topicId}}">
</option>
</select>
<small id="topicHelp" class="form-text text-muted"
th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->
<div class="form-group">
<label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
<select class="custom-select"
id="subtopicsId" name="subtopicsId"
th:field="*{subtopicsId}"
th:errorclass="is-invalid" multiple="multiple">
<option value="" disabled
th:text="#{option.multiple.optional}">Select
</option>
<option th:each="subtopicsIter : ${subtopicsList}"
th:value="${{subtopicsIter.baseIdentity.id}}"
th:text="${subtopicsIter.name}">
</option>
</select>
<small id="subtopicsHelp" class="form-text text-muted"
th:unless="${#fields.hasErrors('subtopicsId')}"
th:text="#{label.subtopics.tt}">select</small>
<small id="subtopicsIdError" class="invalid-feedback"
th:if="${#fields.hasErrors('subtopicsId')}"
th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->
I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.
Now, here's the jQuery that handles changes:
$('#topicId').change(function () {
selectedOption = $(this).val();
if (selectedOption === "") {
$('#subtopicsId').prop('disabled', 'disabled').val('');
$("#subtopicsId option").slice(1).remove(); // keep first
} else {
$('#subtopicsId').prop('disabled', false)
var orig = $(location).attr('origin');
var url = orig + "/getsubtopics/" + selectedOption;
$.ajax({
url: url,
success: function (response) {
var len = response.length;
$("#subtopicsId option[value!='']").remove(); // keep first
for (var i = 0; i < len; i++) {
var id = response[i]['baseIdentity']['id'];
var name = response[i]['name'];
$("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
}).change(); // and call it once defined
The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.
BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.
I am writing a php extension and also encounter this problem. When i call an extern function with complicated parameters from my extension, this error pop up.
The reason is my not allocating memory for a parameter(char *) in the extern function. If you are writing same kind of extension, please pay attention to this.
take a look at shutil
. shutil.copyfile(src, dst)
will copy a file to another file.
Note that shutil.copyfile
will not create directories that do not already exist. for that, use os.makedirs
That depends on what headers you are sending along with your CSS files. Check your server configuration as you are probably not sending them manually. Do a google search for "http caching" to learn about different caching options you can set. You can force the browser to download a fresh copy of the file everytime it loads it for instance, or you can cache the file for one week...
You can use replace and replaceAll with regular expressions.
String[] strings = {"a", "b", "c"};
String result = Arrays.asList(strings).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ",");
Because Arrays.asList().toString()
produces: "[a, b, c]", we do a replaceAll
to remove the first and last brackets and then (optionally) you can change the ", " sequence for "," (your new separator).
A stripped version (fewer chars):
String[] strings = {"a", "b", "c"};
String result = ("" + Arrays.asList(strings)).replaceAll("(^.|.$)", "").replace(", ", "," );
Regular expressions are very powerful, specially String methods "replaceFirst" and "replaceAll". Give them a try.
On my Mobo (ASRock A320M-HD with Ryzen 3 2200G) I have to:
SR-IOV support: enabled
IOMMU: enabled
SVM: enabled
On the OS enable Hyper V.
Here is a forum thread that provides a C# image resizing code sample. You could use one of the GD library binders to do resampling in C#.
(function(angular) {
'use strict';
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
element.bind("keydown keypress", function (event) {
console.log('keydown keypress', event.which);
if(event.which === 13) {
event.preventDefault();
}
});
}
};
}]);
})(window.angular);
Another solution:
public class CountryInfoResponse {
private List<Object> geonames;
}
Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.
In case anyone face pip issue like below
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
The root cause is openssl 1.1 doesn’t support python 3.6 anymore. So you need to install old version openssl 1.0
here is the solution:
brew uninstall --ignore-dependencies openssl
brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
Make sure your
AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
dependency is pulled from
"org.springframework:spring-context-support:4..."
and NOT from
"org.springframework:spring-support:2..."
It wanted me to use
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler)
instead of
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle)
so was failing to autowire job instance.
The error possibly comes because of the different structure of the code that you are committing and that present on GitHub. It creates conflicts which can be solved by
git pull
Merge conflicts resolving:
git push
If you confirm that your new code is all fine you can use:
git push -f origin master
Where -f
stands for "force commit".
Now that “all” browsers support ES6, I’ve incorporated the various suggestions above into a JavaScript class that takes a table as an argument and makes the body scrollable. It lets the browser’s layout engine determine header and body cell widths, and then makes the column widths match each other.
The height of a table can be set explicitly, or made to fill the remaining part of the browser window, and provides callbacks for events such as viewport resizing and/or details
elements opening or closing.
Multi-row header support is available, and is especially effective if the table uses the id/headers attributes for accessibility as specified in the WCAC Guidelines, which is not as onerous a requirement as it might seem.
The code does not depend on any libraries, but plays nicely with them if they are being used. (Tested on pages that use JQuery).
The code and sample usage are available on Github.
Your SVN passwords in Ubuntu (12.04) are in:
~/.subversion/auth/svn.simple/
However in newer versions they are encrypted, as earlier someone mentioned. To find gnome-keyring passwords, I suggest You to use 'gkeyring' program.
To install it on Ubuntu – add repository :
sudo add-apt-repository ppa:kampka/ppa
sudo apt-get update
Install it:
sudo apt-get install gkeyring
And run as following:
gkeyring --id 15 --output=name,secret
Try different key ids to find pair matching what you are looking for. Thanks to kampka for the soft.
Here's an approach that that doesn't require command line args or a separate launcher. It's not completely invisible because a window does show momentarily at startup. But it then quickly vanishes. Where that's OK, this is, I think, the easiest approach if you want to launch your script by double-clicking in explorer, or via a Start menu shortcut (including, of course the Startup submenu). And I like that it's part of the code of the script itself, not something external.
Put this at the front of your script:
$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
add-type -name win -member $t -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)
You can use a SqlDataAdapter
:
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
Just to simplify -
Entity framework doesn't support primitives. You either create a class to wrap it or add another property to format the list as a string:
public ICollection<string> List { get; set; }
public string ListString
{
get { return string.Join(",", List); }
set { List = value.Split(',').ToList(); }
}
It is same way as you do for the two divs, just float the third one to left or right too.
<style>
.left{float:left; width:33%;}
</style>
<div class="left">...</div>
<div class="left">...</div>
<div class="left">...</div>
Another simple example from here..
SELECT * FROM dbo.Employee
ORDER BY
CASE WHEN Gender='Male' THEN EmployeeName END Desc,
CASE WHEN Gender='Female' THEN Country END ASC
suppressWarnings()
has already been mentioned. An alternative is to manually convert the problematic characters to NA first. For your particular problem, taRifx::destring
does just that. This way if you get some other, unexpected warning out of your function, it won't be suppressed.
> library(taRifx)
> x <- as.numeric(c("1", "2", "X"))
Warning message:
NAs introduced by coercion
> y <- destring(c("1", "2", "X"))
> y
[1] 1 2 NA
> x
[1] 1 2 NA
The simple way is using ternary operator
var Link = React.createClass({
getInitialState: function(){
return {hover: false}
},
toggleHover: function(){
this.setState({hover: !this.state.hover})
},
render: function() {
var linkStyle;
if (this.state.hover) {
linkStyle = {backgroundColor: 'red'}
} else {
linkStyle = {backgroundColor: 'blue'}
}
return(
<div>
<a style={this.state.hover ? {"backgroundColor": 'red'}: {"backgroundColor": 'blue'}} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
</div>
)
}
You can also use strcspn(string, "e")
but this may be much slower since it's able to handle searching for multiple possible characters. Using strchr
and subtracting the pointer is the best way.
Start by registering your custom browser/uploader when you instantiate CKEditor.
<script type="text/javascript">
CKEDITOR.replace('content', {
filebrowserUploadUrl: "Upload File Url",//http://localhost/phpwork/test/ckFileUpload.php
filebrowserWindowWidth : 800,
filebrowserWindowHeight : 500
});
</script>
Code for upload file(ckFileUpload.php) & put the upload file on root dir of your project.
// HERE SET THE PATH TO THE FOLDERS FOR IMAGES AND AUDIO ON YOUR SERVER (RELATIVE TO THE ROOT OF YOUR WEBSITE ON SERVER)
$upload_dir = array(
'img'=> '/phpwork/test/uploads/editor-images/',
'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'
);
// HERE PERMISSIONS FOR IMAGE
$imgset = array(
'maxsize' => 2000, // maximum file size, in KiloBytes (2 MB)
'maxwidth' => 900, // maximum allowed width, in pixels
'maxheight' => 800, // maximum allowed height, in pixels
'minwidth' => 10, // minimum allowed width, in pixels
'minheight' => 10, // minimum allowed height, in pixels
'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'), // allowed extensions
);
// HERE PERMISSIONS FOR AUDIO
$audioset = array(
'maxsize' => 20000, // maximum file size, in KiloBytes (20 MB)
'type' => array('mp3', 'ogg', 'wav'), // allowed extensions
);
// If 1 and filename exists, RENAME file, adding "_NR" to the end of filename (name_1.ext, name_2.ext, ..)
// If 0, will OVERWRITE the existing file
define('RENAME_F', 1);
$re = '';
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name']))); //get filename without extension
// get protocol and host name to send the absolute image path to CKEditor
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$site = $protocol. $_SERVER['SERVER_NAME'] .'/';
$sepext = explode('.', strtolower($_FILES['upload']['name']));
$type = end($sepext); // gets extension
$upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
$upload_dir = trim($upload_dir, '/') .'/';
//checkings for image or audio
if(in_array($type, $imgset['type'])){
list($width, $height) = getimagesize($_FILES['upload']['tmp_name']); // image width and height
if(isset($width) && isset($height)) {
if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
}
}
else if(in_array($type, $audioset['type'])){
if($_FILES['upload']['size'] > $audioset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $audioset['maxsize']. ' KB.';
}
else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';
//set filename; if file exists, and RENAME_F is 1, set "img_name_I"
// $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
function setFName($p, $fn, $ex, $i){
if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
else return $fn .$ex;
}
$f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
$uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name; // full file path
// If no errors, upload the image, else, output the errors
if($re == '') {
if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
$CKEditorFuncNum = $_GET['CKEditorFuncNum'];
$url = $site. $upload_dir . $f_name;
$msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
$re = in_array($type, $imgset['type']) ? "window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')" //for img
: 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent(); dialog.hide();';
}
else $re = 'alert("Unable to upload the file")';
}
else $re = 'alert("'. $re .'")';
}
@header('Content-type: text/html; charset=utf-8');
echo '<script>'. $re .';</script>';
Ck-editor documentation is not clear after doing alot of R&D for custom file upload finally i have found this solution. It work for me and i hope it will helpful to others as well.
This Code work for me :
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
Take a look at the INFORMATION_SCHEMA
.TABLES
table. It contains metadata about all your tables.
Example:
SELECT * FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE TABLE_NAME LIKE 'table1'
The advantage of this over other methods is that you can easily use queries like the one above as subqueries in your other queries.
Example with some beautifying, similar to the sep option available in python 3.8
def prettyhex(nums, sep=''):
return sep.join(f'{a:02x}' for a in nums)
numbers = [0, 1, 2, 3, 127, 200, 255]
print(prettyhex(numbers,'-'))
output
00-01-02-03-7f-c8-ff
There are several options, including using the method you demonstrate, With, and using a variable.
My preference is option 4 below: Dim
a variable of type Worksheet
and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.
Sub Test()
Dim SheetName As String
Dim SearchText As String
Dim FoundRange As Range
SheetName = "test"
SearchText = "abc"
' 0. If you know the sheet is the ActiveSheet, you can use if directly.
Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
' Since I usually have a lot of Subs/Functions, I don't use this method often.
' If I do, I store it in a variable to make it easy to change in the future or
' to pass to functions, e.g.: Set MySheet = ActiveSheet
' If your methods need to work with multiple worksheets at the same time, using
' ActiveSheet probably isn't a good idea and you should just specify the sheets.
' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)
' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
' sheet names use the title/name of the worksheet, however the name must
' be a valid VBA identifier (no spaces or special characters. Use the Object
' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)
' 3. Using "With" (more efficient than #1)
With Sheets(SheetName)
Set FoundRange = .UsedRange.Find(What:=SearchText)
End With
' or possibly...
With Sheets(SheetName).UsedRange
Set FoundRange = .Find(What:=SearchText)
End With
' 4. Using Worksheet variable (more efficient than 1)
Dim MySheet As Worksheet
Set MySheet = Worksheets(SheetName)
Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)
' Calling a Function/Sub
Test2 Sheets(SheetName) ' Option 1
Test2 Sheet1 ' Option 2
Test2 MySheet ' Option 4
End Sub
Sub Test2(TestSheet As Worksheet)
Dim RowIndex As Long
For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
' Do something
End If
Next RowIndex
End Sub
The shuffling process is "with replacement", so the occurrence of each item may change! At least when when items in your list is also list.
E.g.,
ml = [[0], [1]] * 10
After,
random.shuffle(ml)
The number of [0] may be 9 or 8, but not exactly 10.
Put [] around any field names that had spaces (as Dreden says) and save your query, close it and reopen it.
Using Access 2016, I still had the error message on new queries after I added [] around any field names... until the Query was saved.
Once the Query is saved (and visible in the Objects' List), closed and reopened, the error message disappears. This seems to be a bug from Access.
The registry path for official images (without a slash in the name) is library/<image>
. Try this instead:
docker pull registry.hub.docker.com/library/busybox
The following should do the trick:
div[class^='myclass'], div[class*=' myclass']{
color: #F00;
}
Edit: Added wildcard (*
) as suggested by David
If you are looking to remove usernames and passwords from your docker-compose.yml you can use Docker Secrets, here is how I have approached it.
version: '3.6'
services:
db:
image: mongo:3
container_name: mycontainer
secrets:
- MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD
environment:
- MONGO_INITDB_ROOT_USERNAME_FILE=/var/run/secrets/MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD_FILE=/var/run/secrets/MONGO_INITDB_ROOT_PASSWORD
secrets:
MONGO_INITDB_ROOT_USERNAME:
file: secrets/${NODE_ENV}_mongo_root_username.txt
MONGO_INITDB_ROOT_PASSWORD:
file: secrets/${NODE_ENV}_mongo_root_password.txt
I have use the file: option for my secrets however, you can also use external: and use the secrets in a swarm.
The secrets are available to any script in the container at /var/run/secrets
The Docker documentation has this to say about storing sensitive data...
https://docs.docker.com/engine/swarm/secrets/
You can use secrets to manage any sensitive data which a container needs at runtime but you don’t want to store in the image or in source control, such as:
Usernames and passwords TLS certificates and keys SSH keys Other important data such as the name of a database or internal server Generic strings or binary content (up to 500 kb in size)
In case the dictionaries are only uniquely identified by all items (ID is not available) you can use the answer using JSON. The following is an alternative that does not use JSON, and will work as long as all dictionary values are immutable
[dict(s) for s in set(frozenset(d.items()) for d in L)]
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
Your NFS server disappeared.
Ideally your best bet is if the NFS server comes back.
If not, the "umount -f" should have done the trick. It doesn't ALWAYS work, but it often will.
If you happen to know what processes are USING the NFS filesystem, you could try killing those processes and then maybe an unmount would work.
Finally, I'd guess you need to reboot.
Also, DON'T soft-mount your NFS drives. You use hard-mounts to guarantee that they worked. That's necessary if you're doing writes.
This is what works
var value= $('option:selected', $('#dropDownId')).val();
In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...
var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
if(sortAscending) {
qry = qry.OrderBy(x=>x.Property);
} else {
qry = qry.OrderByDescending(x=>x.Property);
}
Any use? You can create the entire "order" dynamically, but it is more involved...
Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.
Here is some C code that produces the above mentioned error:
int main(int argc, char **argv) {
exit(1);
}
Compiled like this on Fedora 17 Linux 64 bit with gcc:
el@defiant ~/foo2 $ gcc -o n n2.c
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n
el@defiant ~/foo2 $
To make the warning go away, add this declaration to the top of the file:
#include <stdlib.h>
Here is tiny function that left pad value with a given padding char You can specify how many characters to be padded to left..
Create function fsPadLeft(@var varchar(200),@padChar char(1)='0',@len int)
returns varchar(300)
as
Begin
return replicate(@PadChar,@len-Len(@var))+@var
end
To call :
declare @value int; set @value =2
select dbo.fsPadLeft(@value,'0',2)
Android Studio v.2.3.3
Highlight the code context you want to test, and use the hotkey: CTRL
+SHIFT
+T
Use the dialog interface to complete your setup.
The testing framework is supposed to mirror your project package layout for best results, but you can manually create custom tests, provided you have the correct directory and build settings.
>>> df = pd.DataFrame(np.random.rand(5, 4) * 10, columns=list('PQRS'))
>>> print(df)
... P Q R S
... 0 4.395994 0.844292 8.543430 1.933934
... 1 0.311974 9.519054 6.171577 3.859993
... 2 2.056797 0.836150 5.270513 3.224497
... 3 3.919300 8.562298 6.852941 1.415992
... 4 9.958550 9.013425 8.703142 3.588733
>>> float_col = df.select_dtypes(include=['float64']) # This will select float columns only
>>> # list(float_col.columns.values)
>>> for col in float_col.columns.values:
... df[col] = df[col].astype('int64')
>>> print(df)
... P Q R S
... 0 4 0 8 1
... 1 0 9 6 3
... 2 2 0 5 3
... 3 3 8 6 1
... 4 9 9 8 3
I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:
try:
pass
log.info('Success')
except:
log.exception('Failed')
I know maybe it is unnecessary, but I made a function which converts float to string:
#include <stdio.h>
/** Number on countu **/
int n_tu(int number, int count)
{
int result = 1;
while(count-- > 0)
result *= number;
return result;
}
/*** Convert float to string ***/
void float_to_string(float f, char r[])
{
long long int length, length2, i, number, position, sign;
float number2;
sign = -1; // -1 == positive number
if (f < 0)
{
sign = '-';
f *= -1;
}
number2 = f;
number = f;
length = 0; // Size of decimal part
length2 = 0; // Size of tenth
/* Calculate length2 tenth part */
while( (number2 - (float)number) != 0.0 && !((number2 - (float)number) < 0.0) )
{
number2 = f * (n_tu(10.0, length2 + 1));
number = number2;
length2++;
}
/* Calculate length decimal part */
for (length = (f > 1) ? 0 : 1; f > 1; length++)
f /= 10;
position = length;
length = length + 1 + length2;
number = number2;
if (sign == '-')
{
length++;
position++;
}
for (i = length; i >= 0 ; i--)
{
if (i == (length))
r[i] = '\0';
else if(i == (position))
r[i] = '.';
else if(sign == '-' && i == 0)
r[i] = '-';
else
{
r[i] = (number % 10) + '0';
number /=10;
}
}
}
Here is another example using HOOKS fontAwesomeIcon and Kendo UI React
[![screenshot here][1]][1]
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
const ScrollBackToTop = () => {
const [show, handleShow] = useState(false);
useEffect(() => {
window.addEventListener('scroll', () => {
if (window.scrollY > 1200) {
handleShow(true);
} else handleShow(false);
});
return () => {
window.removeEventListener('scroll');
};
}, []);
const backToTop = () => {
window.scroll({ top: 0, behavior: 'smooth' });
};
return (
<div>
{show && (
<div className="backToTop text-center">
<button className="backToTop-btn k-button " onClick={() => backToTop()} >
<div className="d-none d-xl-block mr-1">Top</div>
<FontAwesomeIcon icon="chevron-up"/>
</button>
</div>
)}
</div>
);
};
export default ScrollBackToTop;```
[1]: https://i.stack.imgur.com/ZquHI.png
A simple tricks here you can use strtotime() function workable as per your need, a convert number to month name.
1.If you want a result in Jan, Feb and Mar Then try below one with the 'M' as a parameter inside the date.
$month=5;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;
Output : May
/2. You can try with the 'F' instead of 'M' to get the full month name as an output January February March etc.
$month=1;
$nmonth = date('M',strtotime("01-".$month."-".date("Y")));
echo $nmonth;
Output : January
Worked on 08/08/2018 and on DRF version 3.8.2:
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField(source='category.name')
class Meta:
model = Item
read_only_fields = ('id', 'category_name')
fields = ('id', 'category_name', 'name',)
Using the Meta read_only_fields
we can declare exactly which fields should be read_only. Then we need to declare the foreign
field on the Meta fields
(better be explicit as the mantra goes: zen of python).
Note, the parentheses are required for UPDATE statements:
update top (100) table1 set field1 = 1
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
There are such of ways to Bind a Placeholder to View:
1) With use of MVC Data Annotations:
Model:
[Required]
[Display(Prompt = "Enter Your First Name")]
public string FirstName { get; set; }
Razor Syntax:
@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})
2) With use of MVC Data Annotations But with DisplayName:
Model:
[Required]
[DisplayName("Enter Your First Name")]
public string FirstName { get; set; }
Razor Syntax:
@Html.TextBoxFor(m => m.FirstName, new { placeholder = @Html.DisplayNameFor(n => n.UserName)})
3) Without use of MVC Data Annotation (recommended):
Razor Syntax:
@Html.TextBoxFor(m => m.FirstName, new { @placeholder = "Enter Your First Name")
SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).
If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).
I am very late but if some one working on SLIM to make rest api and getting same error can solve this problem by adding below line as:
<?php
// DbConnect.php file
class DbConnect
{
//Variable to store database link
private $con;
//Class constructor
function __construct()
{
}
//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
mysqli_set_charset($this->con, "utf8"); // add this line
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
}
Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.
name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to 3.6, the closest you can get to this is
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
The %
operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals()
to map the field name name
to its value as a local variable.
The same code using the .format()
method of recent Python versions would look like this:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
There is also the string.Template
class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
another way would be to use dplyr
package:
x = c(1,1,2,3,4,4,4)
dplyr::distinct(as.data.frame(x))
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
To rename a folder (which is technically a set of objects with a common prefix as key) you can use the aws cli move command with --recursive option.
aws s3 mv s3://bucket/old_folder s3://bucket/new_folder --recursive
Also the destination file system is important.
Under NTFS, some files can not be created in specific directories. E.G. $Boot in root
My solution is to use these 2 mappings:
map <leader>n <Esc><Esc>0qq
map <leader>m q:'<,'>-1normal!@q<CR><Down>
How to use them:
V12j
<leader>n
<leader>m
To make another edit you don't need to make the selection again. Just press <leader>n
, make your edit and press <leader>m
to apply.
How this works:
<Esc><Esc>0qq
Exit the visual selection, go to the beginning of the line and start recording a macro.
q
Stop recording the macro.
:'<,'>-1normal!@q<CR>
From the start of the visual selection to the line before the end, play the macro on each line.
<Down>
Go back down to the last line.
You can also just map the same key but for different modes:
vmap <leader>m <Esc><Esc>0qq
nmap <leader>m q:'<,'>-1normal!@q<CR><Down>
Although this messes up your ability to make another edit. You'll have to re-select your lines.
Right click in the query pane, select Query Options...
and in the Execution->General section (the default when you first open it) there is an Execution time-out
setting.
See the correct way with your example:
<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>
Regards, Nicholls
Try this, with strings:
set "var=string1string2string3"
and with string variables:
set "var=%string1%%string2%%string3%"
What I did:
composer update --prefer-source vendor/library-name
It fetches the library again along with it's git repo
you can try with
document.getElementById('btn').disabled = !this.checked"
<input type="submit" name="btn" id="btn" value="submit" disabled/>_x000D_
_x000D_
<input type="checkbox" onchange="document.getElementById('btn').disabled = !this.checked"/>
_x000D_
Call this method:
public static void shareApp(Context context)
{
final String appPackageName = context.getPackageName();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out the App at: https://play.google.com/store/apps/details?id=" + appPackageName);
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
Ok, You should "construct" the html and find the .content div.
like this:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html($(data).find('#content').html());
}
});
Simple!
You can use any attribute as selector with [attribute_name=value]
.
$('td[name=tcol1]').hide();
Give them a trivial pom with these jars listed as dependencies and instructions to run:
mvn dependency:go-offline
This will pull the dependencies to the local repo.
A more direct solution is dependency:get, but it's a lot of arguments to type:
mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version
Here is the example from the SocketServer documentation which would make an excellent starting point
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Try it from a terminal like this
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.
You'll probably need to use A Forking or Threading Mixin too
The problem with system.gc, is that the JVM already automatically allocates time to the garbage collector based on memory usage.
However, if you are, for instance, working in a very memory limited condition, like a mobile device, System.gc allows you to manually allocate more time towards this garbage collection, but at the cost of cpu time (but, as you said, you aren't that concerned about performance issues of gc).
Best practice would probably be to only use it where you might be doing large amounts of deallocation (like flushing a large array).
All considered, since you are simply concerned about memory usage, feel free to call gc, or, better yet, see if it makes much of a memory difference in your case, and then decide.
I managed to get the value of the DataKeys using this code:
In the GridView I added:
DataKeyNames="ID" OnRowCommand="myRowCommand"
Then in my row command function:
protected void myRowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnkBtn = (LinkButton)e.CommandSource; // the button
GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent; // the row
GridView myGrid = (GridView)sender; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString(); // value of the datakey
switch (e.CommandName)
{
case "cmd1":
// do something using the ID
break;
case "cmd2":
// do something else using the ID
break;
}
}
You can use set
with the /p
argument:
SET /P variable=[promptString]
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
So, simply use something like
set /p Input=Enter some text:
Later you can use that variable as argument to a command:
myCommand %Input%
Be careful though, that if your input might contain spaces it's probably a good idea to quote it:
myCommand "%Input%"
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
To just trim trailing spaces you should use
UPDATE
TableName
SET
ColumnName = RTRIM(ColumnName)
However, if you want to trim all leading and trailing spaces then use this
UPDATE
TableName
SET
ColumnName = LTRIM(RTRIM(ColumnName))
That should be:
java -Dtest="true" -jar myApplication.jar
Then the following will return the value:
System.getProperty("test");
The value could be null
, though, so guard against an exception using a Boolean
:
boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );
Note that the getBoolean
method delegates the system property value, simplifying the code to:
if( Boolean.getBoolean( "test" ) ) {
// ...
}
You might take advantage of ruby's "splat" or flattening syntax.
This makes overgrown when
clauses — you have about 10 values to test per branch if I understand correctly — a little more readable in my opinion. Additionally, you can modify the values to test at runtime. For example:
honda = ['honda', 'acura', 'civic', 'element', 'fit', ...]
toyota = ['toyota', 'lexus', 'tercel', 'rx', 'yaris', ...]
...
if include_concept_cars
honda += ['ev-ster', 'concept c', 'concept s', ...]
...
end
case car
when *toyota
# Do something for Toyota cars
when *honda
# Do something for Honda cars
...
end
Another common approach would be to use a hash as a dispatch table, with keys for each value of car
and values that are some callable object encapsulating the code you wish to execute.
In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}
, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.
This is helpful when your equals method call throws some exception e.g. NullPointerException
;
boolean isMatch = false;
try{
isMatch = email1.equals (email2);
}catch(NullPointerException npe){
.....
}
System.out.print("Match=="+isMatch);
if(isMatch){
......
}
Late answer, but I figured I should add a link to my site because I have written a tutorial how to make an image cache for android: http://squarewolf.nl/2010/11/android-image-cache/ Update: the page has been taken offline as the source was outdated. I join @elenasys in her advice to use Ignition.
So to all the people who stumble upon this question and haven't found a solution: hope you enjoy! =D
How does it work? How does it know it's me?
Most sessions set a user-key(called the sessionid) on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key and runs to the server to get your variables.
If you mistakenly clear the cache, then your user-key will also be cleared. You won't be able to get your variables from the server any more since you don't know your id.
I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm
The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.
I just ran into that issue and after all the explanations about fixing it with command prompt I found that if you add it directly to the project you can then simply include the library on each page that it's needed
Here is a pure css version
.example-print {_x000D_
display: none;_x000D_
}_x000D_
@media print {_x000D_
.example-screen {_x000D_
display: none;_x000D_
}_x000D_
.example-print {_x000D_
display: block;_x000D_
}_x000D_
}
_x000D_
<div class="example-screen">You only see me in the browser</div>_x000D_
_x000D_
<div class="example-print">You only see me in the print</div>
_x000D_
You can use substring
function:
s.substring(0,s.length() - 2));
With the first 0
, you say to substring
that it has to start in the first character of your string and with the s.length() - 2
that it has to finish 2 characters before the String ends.
For more information about substring
function you can see here:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Let me emphasise that Docker doesn't even allow mixed characters.
Good:
docker build -t myfirstechoimage:0.1 .
Bad:
docker build -t myFirstEchoImage:0.1 .
When ever I got this problem:
AttributeError: module 'enum' has no attribute 'IntFlag'
simply first i run the command:
unset PYTHONPATH
and then run my desired command then got success in that.
Use the built-in function dir()
.
System.Environment.NewLine
is the constant you are looking for - http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx which will provide environment specific combination that most programs on given OS will consider "next line of text".
In practice most of the text tools treat all variations that include \n
as "new line" and you can just use it in your text "foo\nbar"
. Especially if you are trying to construct multi-line format strings like $"V1 = {value1}\nV2 = {value2}\n"
. If you are building text with string concatenation consider using NewLine
. In any case make sure tools you are using understand output the way you want and you may need for example always use \r\n
irrespective of platform if editor of your choice can't correctly open files otherwise.
Note that WriteLine
methods use NewLine
so if you plan to write text with one these methods avoid using just \n
as resulting text may contain mix of \r\n
and just \n
which may confuse some tools and definitely does not look neat.
For historical background see Difference between \n and \r?
You can also specify the TNS name in the JDBC URL as below
jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))
Have you included the System.Web
assembly in the application?
using System.Web;
If not, try specifying the System.Web
namespace, for example:
System.Web.HttpContext.Current
For string operations use StringBuilder or StringBuffer classes for accumulating string data blocks. Do not use +=
operations for string objects. String
class is immutable and you will produce a large amount of string objects upon runtime and it will affect on performance.
Use .append()
method of StringBuilder/StringBuffer class instance instead.
I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr
), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:
```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```
Then all the images will be written as PDF files, and LaTeX will be happy.
Your second problem is you are mixing up the HTML units with LaTeX units in out.width
/ out.height
. LaTeX and HTML are very different technologies. You should not expect \maxwidth
to work in HTML, or 200px
in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width
/ out.height
(use fig.width
/ fig.height
and let LaTeX use the original size).
As far as I know, an input element may not have a href
attribute, which is where Fancybox gets its information about the content. The following code uses an a
element instead of the input
element. Also, this is what I would call the "standard way".
<html>
<head>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
<link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>
<a href="#divForm" id="btnForm">Load Form</a>
<div id="divForm" style="display:none">
<form action="tbd">
File: <input type="file" /><br /><br />
<input type="submit" />
</form>
</div>
<script type="text/javascript">
$(function(){
$("#btnForm").fancybox();
});
</script>
</body>
</html>
Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e
For this to work properly, you'll have to run everything this way.
you can use this as well
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var queryValue = getParameterByName('test_user_bLzgB');
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
change
public static final String URL = "http://api-Location";
to
public static final String URL = "https://api-Location"
it's happen because i'm using 000webhostapp app
Quoting from the language specs:Iota
Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:
const ( // iota is reset to 0
c0 = iota // c0 == 0
c1 = iota // c1 == 1
c2 = iota // c2 == 2
)
const (
a = 1 << iota // a == 1 (iota has been reset)
b = 1 << iota // b == 2
c = 1 << iota // c == 4
)
const (
u = iota * 42 // u == 0 (untyped integer constant)
v float64 = iota * 42 // v == 42.0 (float64 constant)
w = iota * 42 // w == 84 (untyped integer constant)
)
const x = iota // x == 0 (iota has been reset)
const y = iota // y == 0 (iota has been reset)
Within an ExpressionList, the value of each iota is the same because it is only incremented after each ConstSpec:
const (
bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0
bit1, mask1 // bit1 == 2, mask1 == 1
_, _ // skips iota == 2
bit3, mask3 // bit3 == 8, mask3 == 7
)
This last example exploits the implicit repetition of the last non-empty expression list.
So your code might be like
const (
A = iota
C
T
G
)
or
type Base int
const (
A Base = iota
C
T
G
)
if you want bases to be a separate type from int.
my suggestion will be add a function call settings like this inside the function check the header which is appropriate for it. I am sure it will definitely work. it is perfectly working for me.
function getSettings(requestData) {
return {
url: requestData.url,
dataType: requestData.dataType || "json",
data: requestData.data || {},
headers: requestData.headers || {
"accept": "application/json; charset=utf-8",
'Authorization': 'Bearer ' + requestData.token
},
async: requestData.async || "false",
cache: requestData.cache || "false",
success: requestData.success || {},
error: requestData.error || {},
complete: requestData.complete || {},
fail: requestData.fail || {}
};
}
then call your data like this
var requestData = {
url: 'API end point',
data: Your Request Data,
token: Your Token
};
var settings = getSettings(requestData);
settings.method = "POST"; //("Your request type")
return $http(settings);
Or like this
class Movie
{
public string FilmName { get; set; }
public string Genre { get; set; }
}
...
var listofGenres = new List<string> { "action", "comedy" };
var Movies = new List<Movie> {new Movie {Genre="action", FilmName="Film1"},
new Movie {Genre="comedy", FilmName="Film2"},
new Movie {Genre="comedy", FilmName="Film3"},
new Movie {Genre="tragedy", FilmName="Film4"}};
var movies = Movies.Join(listofGenres, x => x.Genre, y => y, (x, y) => x).ToList();
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
With the following function you are just sending the pure ICMP packets using socket_create. I got the following code from a user note there. N.B. You must run the following as root.
Although you can't put this in a standard web page you can run it as a cron job and populate a database with the results.
So it's best suited if you need to monitor a site.
function twitterIsUp() {
return ping('twitter.com');
}
function ping ($host, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
$socket = socket_create(AF_INET, SOCK_RAW, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
socket_connect($socket, $host, null);
$ts = microtime(true);
socket_send($socket, $package, strLen($package), 0);
if (socket_read($socket, 255)) {
$result = microtime(true) - $ts;
} else {
$result = false;
}
socket_close($socket);
return $result;
}
Note that you can also use the C99 fixed-width types perfectly well in Objective-C:
#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform
The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h
and inttypes.h
to be useful.
In case someone gets similar issues, I had such an issue while inflating the view:
View.inflate(getApplicationContext(), R.layout.my_layout, null)
fixed by replacing getApplicationContext()
with this
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED
, DOCUMENT_POSITION_PRECEDING
, and DOCUMENT_POSITION_FOLLOWING
.
Not supported in IE<=8.
For me the solution was to have
"location=0"
in the 3rd parameter. Tested on latest FF/Chrome and an old version of IE11
Full method call I use is below (As I like to use a variable width):
window.open(url, "window" + id, 'toolbar=0,location=0,scrollbars=1,statusbar=1,menubar=0,resizable=1,width=' + width + ',height=800,left=100,top=50');
One other way would be using colorbox
function createConfirm(message, okHandler) {
var confirm = '<p id="confirmMessage">'+message+'</p><div class="clearfix dropbig">'+
'<input type="button" id="confirmYes" class="alignleft ui-button ui-widget ui-state-default" value="Yes" />' +
'<input type="button" id="confirmNo" class="ui-button ui-widget ui-state-default" value="No" /></div>';
$.fn.colorbox({html:confirm,
onComplete: function(){
$("#confirmYes").click(function(){
okHandler();
$.fn.colorbox.close();
});
$("#confirmNo").click(function(){
$.fn.colorbox.close();
});
}});
}
npm uninstal @angular/material
and also clear file custom-theme.scss
You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.
>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])
>>> A
array([[1, 2, 0],
[0, 0, 3],
[1, 0, 4]])
>>> sA = sparse.csr_matrix(A) # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)
>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>
>>> print sA
(0, 0) 1
(0, 1) 2
(1, 2) 3
(2, 0) 1
(2, 2) 4
Try to use
table {
table-layout: auto;
}
If you use Bootstrap, class table
has table-layout: fixed;
by default.
You can pass via GET. So if you want to pass the value foobar
from PageA.php
to PageB.php
, call it as PageB.php?value=foobar
.
In PageB.php, you can access it this way:
$value = $_GET['value'];
I do not think that this can be done. Here is some code copied with no modifications from Chip Pearson's site: http://www.cpearson.com/excel/UnSelect.aspx.
UnSelectActiveCell
This procedure will remove the Active Cell from the Selection.
Sub UnSelectActiveCell()
Dim R As Range
Dim RR As Range
For Each R In Selection.Cells
If StrComp(R.Address, ActiveCell.Address, vbBinaryCompare) <> 0 Then
If RR Is Nothing Then
Set RR = R
Else
Set RR = Application.Union(RR, R)
End If
End If
Next R
If Not RR Is Nothing Then
RR.Select
End If
End Sub
UnSelectCurrentArea
This procedure will remove the Area containing the Active Cell from the Selection.
Sub UnSelectCurrentArea()
Dim Area As Range
Dim RR As Range
For Each Area In Selection.Areas
If Application.Intersect(Area, ActiveCell) Is Nothing Then
If RR Is Nothing Then
Set RR = Area
Else
Set RR = Application.Union(RR, Area)
End If
End If
Next Area
If Not RR Is Nothing Then
RR.Select
End If
End Sub
Here is my solution I use for my app.
I have several asset folder with css / js / img anf font files.
The application gets all filenames and looks if a file with this name is requested. If yes, it loads it from asset folder.
//get list of files of specific asset folder
private ArrayList listAssetFiles(String path) {
List myArrayList = new ArrayList();
String [] list;
try {
list = getAssets().list(path);
for(String f1 : list){
myArrayList.add(f1);
}
} catch (IOException e) {
e.printStackTrace();
}
return (ArrayList) myArrayList;
}
//get mime type by url
public String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
if (extension.equals("js")) {
return "text/javascript";
}
else if (extension.equals("woff")) {
return "application/font-woff";
}
else if (extension.equals("woff2")) {
return "application/font-woff2";
}
else if (extension.equals("ttf")) {
return "application/x-font-ttf";
}
else if (extension.equals("eot")) {
return "application/vnd.ms-fontobject";
}
else if (extension.equals("svg")) {
return "image/svg+xml";
}
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
//return webresourceresponse
public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
List myArrayList = listAssetFiles(folder);
for (Object str : myArrayList) {
if (url.contains((CharSequence) str)) {
try {
Log.i(TAG2, "File:" + str);
Log.i(TAG2, "MIME:" + getMimeType(url));
return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
//@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("NewApi")
@Override
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
//Log.i(TAG2, "SHOULD OVERRIDE INIT");
//String url = webResourceRequest.getUrl().toString();
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
//I have some folders for files with the same extension
if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
return loadFilesFromAssetFolder(extension, url);
}
//more possible extensions for font folder
if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
return loadFilesFromAssetFolder("font", url);
}
return null;
}
You can try this, I know is not the answers you are looking for but the concept is the same.
Where you are setting the styles for all the children and then removing it from the last child.
Code Snippet
li
margin-right: 10px
&:last-child
margin-right: 0
Image
CONTROL + SHIFT + P and execute command "Tree View: Show"
Both of the answers presented here will not handle repeated elements. For example, if you are testing whether [1,2,2] is a sublist of [1,2,3,4], both will return True. That may be what you mean to do, but I just wanted to clarify. If you want to return false for [1,2,2] in [1,2,3,4], you would need to sort both lists and check each item with a moving index on each list. Just a slightly more complicated for loop.
Do you mean full calendar days, or groups of 24 hours?
For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:
days = (a - b).days
For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:
roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days
Optionals and default parameters are two different things.
An Optional is a variable that can be nil
, that's it.
Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)
If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil
. If your function looks like this func test(param: Int?)
, you can't call it like this test()
. Even though the parameter is optional, it doesn't have a default value.
You can also combine the two and have a parameter that takes an optional where nil
is the default value, like this: func test(param: Int? = nil)
.
MySQL has a concept of user-defined variables.
They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.
They are prepended with an @
sign, like this: @var
You can initialize this variable with a SET
statement or inside a query:
SET @var = 1
SELECT @var2 := 2
When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:
DELIMITER //
CREATE PROCEDURE prc_test (var INT)
BEGIN
DECLARE var2 INT;
SET var2 = 1;
SELECT var2;
END;
//
DELIMITER ;
These variables are not prepended with any prefixes.
The difference between a procedure variable and a session-specific user-defined variable is that a procedure variable is reinitialized to NULL
each time the procedure is called, while the session-specific variable is not:
CREATE PROCEDURE prc_test ()
BEGIN
DECLARE var2 INT DEFAULT 1;
SET var2 = var2 + 1;
SET @var2 = @var2 + 1;
SELECT var2, @var2;
END;
SET @var2 = 1;
CALL prc_test();
var2 @var2
--- ---
2 2
CALL prc_test();
var2 @var2
--- ---
2 3
CALL prc_test();
var2 @var2
--- ---
2 4
As you can see, var2
(procedure variable) is reinitialized each time the procedure is called, while @var2
(session-specific variable) is not.
(In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port
or "session variables" such as @@session.sql_mode
; these "session variables" are unrelated to session-specific user-defined variables.)
MapReduce is just a computing framework. HBase has nothing to do with it. That said, you can efficiently put or fetch data to/from HBase by writing MapReduce jobs. Alternatively you can write sequential programs using other HBase APIs, such as Java, to put or fetch the data. But we use Hadoop, HBase etc to deal with gigantic amounts of data, so that doesn't make much sense. Using normal sequential programs would be highly inefficient when your data is too huge.
Coming back to the first part of your question, Hadoop is basically 2 things: a Distributed FileSystem (HDFS) + a Computation or Processing framework (MapReduce). Like all other FS, HDFS also provides us storage, but in a fault tolerant manner with high throughput and lower risk of data loss (because of the replication). But, being a FS, HDFS lacks random read and write access. This is where HBase comes into picture. It's a distributed, scalable, big data store, modelled after Google's BigTable. It stores data as key/value pairs.
Coming to Hive. It provides us data warehousing facilities on top of an existing Hadoop cluster. Along with that it provides an SQL like interface which makes your work easier, in case you are coming from an SQL background. You can create tables in Hive and store data there. Along with that you can even map your existing HBase tables to Hive and operate on them.
While Pig is basically a dataflow language that allows us to process enormous amounts of data very easily and quickly. Pig basically has 2 parts: the Pig Interpreter and the language, PigLatin. You write Pig script in PigLatin and using Pig interpreter process them. Pig makes our life a lot easier, otherwise writing MapReduce is always not easy. In fact in some cases it can really become a pain.
I had written an article on a short comparison of different tools of the Hadoop ecosystem some time ago. It's not an in depth comparison, but a short intro to each of these tools which can help you to get started. (Just to add on to my answer. No self promotion intended)
Both Hive and Pig queries get converted into MapReduce jobs under the hood.
HTH
new Date().toTimeString().slice(0,8)
Note that toLocaleTimeString() might return something like 9:00:00 AM
.
It's really easy to do with github pages, it's just a bit weird the first time you do it. Sorta like the first time you had to juggle 3 kittens while learning to knit. (OK, it's not all that bad)
You need a gh-pages branch:
Basically github.com looks for a gh-pages branch of the repository. It will serve all HTML pages it finds in here as normal HTML directly to the browser.
How do I get this gh-pages branch?
Easy. Just create a branch of your github repo called gh-pages
.
Specify --orphan
when you create this branch, as you don't actually want to merge this branch back into your github branch, you just want a branch that contains your HTML resources.
$ git checkout --orphan gh-pages
What about all the other gunk in my repo, how does that fit in to it?
Nah, you can just go ahead and delete it. And it's safe to do now, because you've been paying attention and created an orphan branch which can't be merged back into your main branch and remove all your code.
I've created the branch, now what?
You need to push this branch up to github.com, so that their automation can kick in and start hosting these pages for you.
git push -u origin gh-pages
But.. My HTML is still not being served!
It takes a few minutes for github to index these branches and fire up the required infrastructure to serve up the content. Up to 10 minutes according to github.
The steps layed out by github.com
https://help.github.com/articles/creating-project-pages-manually
May be this will help:
wget --no-check-certificate https://blah-blah.tld/path/filename
First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be
import math as m
a=int(input("Enter the no"))
print(m.sqrt(a))
from math import sqrt
print(sqrt(25))
from math import sqrt as s
print(s(25))
from math import *
print(sqrt(25))
All works.
Try this:
Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
On Error GoTo the_dark
Dim wsSheet As Worksheet
Dim bFoundWS As Boolean
bFoundWS = False
If inNamePrefix <> "" Then
Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
End If
If inBeforeOrAfter = iAfter Then
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
Else
Worksheets.Add(After:=wsSheet).Name = inName
End If
Else
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(Before:=Worksheets(1)).Name = inName
Else
Worksheets.Add(Before:=wsSheet).Name = inName
End If
End If
Set addSheet = findWS(inWB, inName, bFoundWS) ' just to confirm it exists and gets it handle
the_light:
Exit Function
the_dark:
MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
Err.Clear
GoTo the_light
End Function
If you stick to HTML structure and proper selectors according to the Bootstrap convention, you should be alright.
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse in">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
</h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
</h4>
</div>
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
</div>
For those who can not figure out this in instructions from this answer there:
Try to set padding value more then 0, if child divs have margin-top or margin-bottom you can replace it with padding
For example if you have
#childRightCol
{
margin-top: 30px;
}
#childLeftCol
{
margin-bottom: 20px;
}
it'll be better to replace it with:
#parent
{
padding: 30px 0px 20px 0px;
}
Using Java 8 this can be performed in various ways using streams, parallel streams and removeIf
method:
List<String> stringList = new ArrayList<>(Arrays.asList(null, "A", "B", null, "C", null));
List<String> listWithoutNulls1 = stringList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
List<String> listWithoutNulls2 = stringList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList()); //[A,B,C]
stringList.removeIf(Objects::isNull); //[A,B,C]
The parallel stream will make use of available processors and will speed up the process for reasonable sized lists. It is always advisable to benchmark before using streams.
What I really wanted was a GUI to reorder them and output them as one file
Playlist Producer does exactly that, decoding and reencoding them into a combined MP3. It's designed for creating mix tapes or simple podcasts, but you might find it useful.
(Disclosure: I wrote the software, and I profit if you buy the Pro Edition. The Lite edition is a free version with a few limitations).
If you'd like to add text at the end of each line in-place (in the same file), you can use -i
parameter, for example:
sed -i'.bak' 's/$/:80/' foo.txt
However -i
option is non-standard Unix extension and may not be available on all operating systems.
So you can consider using ex
(which is equivalent to vi -e
/vim -e
):
ex +"%s/$/:80/g" -cwq foo.txt
which will add :80
to each line, but sometimes it can append it to blank lines.
So better method is to check if the line actually contain any number, and then append it, for example:
ex +"g/[0-9]/s/$/:80/g" -cwq foo.txt
If the file has more complex format, consider using proper regex, instead of [0-9]
.
My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer
as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .
How do we do for CI CD
The easiest way is:
s = '"sajdkasjdsaasdasdasds"'
import json
s = json.loads(s)
You can use the limit(n)
function:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()
Or:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()
MDN: https://developer.mozilla.org/en/DOM/window.location
It seems that you will get the same result for both, but hostname
contains clear host name without brackets or port number.
You can use the "-r" option to set the sender address:
mailx -r [email protected] -s ...
Reference link: http://www.programering.com/a/MTNyUDMwATA.html
Steps I followed
1) Execute the command adb nodaemon server
in command prompt
Output at command prompt will be: The following error occurred cannot bind 'tcp:5037'
The original ADB server port binding failed
2) Enter the following command query which using port 5037
netstat -ano | findstr "5037"
The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288
3) View the task manager, close all adb.exe
4) Restart eclipse or other IDE
The above steps worked for me.
I fixed this (for development) with a simple nginx proxy...
# /etc/nginx/sites-enabled/default
server {
listen 80;
root /path/to/Development/dir;
index index.html;
# from your example
location /search {
proxy_pass http://api.master18.tiket.com;
}
}
Code is below:
set datefirst 7
declare @dt datetime='29/04/2016 00:00:00'
select (day(@dt)+datepart(WEEKDAY,dateadd(d,-day(@dt),@dt+1)))/7
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function scollPos() {
var div = document.getElementById("myDiv").scrollTop;
document.getElementById("pos").innerHTML = div;
}
</script>
</head>
<body>
<form id="form1">
<div id="pos">
</div>
<div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
Place some large content here
</div>
</form>
</body>
</html>
Is this the kind of output you're looking for?
for(var b in window) {
if(window.hasOwnProperty(b)) console.log(b);
}
This will list everything available on the window
object (all the functions and variables, e.g., $
and jQuery
on this page, etc.). Though, this is quite a list; not sure how helpful it is...
Otherwise just do window
and start going down its tree:
window
This will give you DOMWindow
, an expandable/explorable object.
As PPK points out here, in IE you can also use
e.cancelBubble = true;
In the MongoDB shell:
db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})
In my nodeJS code ( using Mongoose )
SensorEvent.Model.find( {
from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
} )
I am querying my sensor events collection to return values where the 'from' field is greater than the given date
You need to wrap the forward slash to avoid cross browser issues or //commenting out.
str = 'this/that and/if';
var newstr = str.replace(/[/]/g, 'ForwardSlash');
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
browsers are smart enough to detect the link and downloading it directly when clicking on an anchor tag without using the download attribute.
after getting your file link from the api, just use plain javascript by creating anchor tag and delete it after clicking on it dynamically immediately on the fly.
const link = document.createElement('a');
link.href = `your_link.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
I faced exactly the same issue. My home drive mapped to a network drive. Also
However below worked from command line and I was able to add HOME
to environment variables.
rundll32 sysdm.cpl,EditEnvironmentVariables
This one I implemented for my website , If some one got more no's of menu item and longer search bar can use this
Here is the code
<style>
.navbar-inverse .navbar-nav > li > a {
color: white !important;
}
.navbar-inverse .navbar-nav > li > a:hover {
text-decoration: underline;
}
.navbar-collapse ul li {
padding-top: 0px;
padding-bottom: 0px;
}
.navbar-collapse ul li a {
padding-top: 0px;
padding-bottom: 0px;
}
.navbar-brand img {
width: 200px;
height: 40px;
}
.navbar-inverse {
background-color: #3A1B37;
}
</style>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" runat="server" href="~/">
<img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin"></a>
<div class="col-md-6 col-sm-8 col-xs-11 navbar-left">
<div class="navbar-form " role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term" style="max-width: 100%; width: 100%;">
<div class="input-group-btn">
<button class="btn btn-default" style="background: rgb(72, 166, 72);" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</div>
</div>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="navbar-brand visible-md visible-lg visible-sm" style="visibility: hidden;" runat="server">
<img src="http://placehold.it/200x40/3A1B37/ffffff/?text=Apllicatin" />
</li>
<li><a runat="server" href="~/">Home</a></li>
<li><a runat="server" href="~/About">About</a></li>
<li><a runat="server" href="~/Contact">Contact</a></li>
<li><a runat="server" href="~/">Somthing</a></li>
<li><a runat="server" href="~/">Somthing</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a runat="server" href="~/Account/Register">Register</a></li>
<li><a runat="server" href="~/Account/Login">Log in</a></li>
</ul> </div>
</div>
</div>
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc"
value to integer..
this is valid string is eg"123"
. in your case split by space..
split(" ");
will split line by " "
by space..
how to convert JTextField to string and string to JTextField in java
If you mean how to get and set String from jTextField then you can use following methods:
String str = jTextField.getText() // get string from jtextfield
and
jTextField.setText(str) // set string to jtextfield
//or
new JTextField(str) // set string to jtextfield
You should check JavaDoc for JTextField
I had the same problem. So I took the source code of java.util.TreeMap and wrote IndexedTreeMap. It implements my own IndexedNavigableMap:
public interface IndexedNavigableMap<K, V> extends NavigableMap<K, V> {
K exactKey(int index);
Entry<K, V> exactEntry(int index);
int keyIndex(K k);
}
The implementation is based on updating node weights in the red-black tree when it is changed. Weight is the number of child nodes beneath a given node, plus one - self. For example when a tree is rotated to the left:
private void rotateLeft(Entry<K, V> p) {
if (p != null) {
Entry<K, V> r = p.right;
int delta = getWeight(r.left) - getWeight(p.right);
p.right = r.left;
p.updateWeight(delta);
if (r.left != null) {
r.left.parent = p;
}
r.parent = p.parent;
if (p.parent == null) {
root = r;
} else if (p.parent.left == p) {
delta = getWeight(r) - getWeight(p.parent.left);
p.parent.left = r;
p.parent.updateWeight(delta);
} else {
delta = getWeight(r) - getWeight(p.parent.right);
p.parent.right = r;
p.parent.updateWeight(delta);
}
delta = getWeight(p) - getWeight(r.left);
r.left = p;
r.updateWeight(delta);
p.parent = r;
}
}
updateWeight simply updates weights up to the root:
void updateWeight(int delta) {
weight += delta;
Entry<K, V> p = parent;
while (p != null) {
p.weight += delta;
p = p.parent;
}
}
And when we need to find the element by index here is the implementation that uses weights:
public K exactKey(int index) {
if (index < 0 || index > size() - 1) {
throw new ArrayIndexOutOfBoundsException();
}
return getExactKey(root, index);
}
private K getExactKey(Entry<K, V> e, int index) {
if (e.left == null && index == 0) {
return e.key;
}
if (e.left == null && e.right == null) {
return e.key;
}
if (e.left != null && e.left.weight > index) {
return getExactKey(e.left, index);
}
if (e.left != null && e.left.weight == index) {
return e.key;
}
return getExactKey(e.right, index - (e.left == null ? 0 : e.left.weight) - 1);
}
Also comes in very handy finding the index of a key:
public int keyIndex(K key) {
if (key == null) {
throw new NullPointerException();
}
Entry<K, V> e = getEntry(key);
if (e == null) {
throw new NullPointerException();
}
if (e == root) {
return getWeight(e) - getWeight(e.right) - 1;//index to return
}
int index = 0;
int cmp;
index += getWeight(e.left);
Entry<K, V> p = e.parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
while (p != null) {
cmp = cpr.compare(key, p.key);
if (cmp > 0) {
index += getWeight(p.left) + 1;
}
p = p.parent;
}
} else {
Comparable<? super K> k = (Comparable<? super K>) key;
while (p != null) {
if (k.compareTo(p.key) > 0) {
index += getWeight(p.left) + 1;
}
p = p.parent;
}
}
return index;
}
You can find the result of this work at http://code.google.com/p/indexed-tree-map/
TreeSet/TreeMap (as well as their indexed counterparts from the indexed-tree-map project) do not allow duplicate keys , you can use 1 key for an array of values. If you need a SortedSet with duplicates use TreeMap with values as arrays. I would do that.
You're almost there, you just have to append:
-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword