in your location block you can do:
location / {
try_files $uri $uri/index.html;
}
which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html
use both format it works fine in all browser:
<video width="640" height="360" controls>
<!-- MP4 must be first for iPad! -->
<source src="unbelievable.mp4" type="video/mp4" /><!-- Safari / iOS video -->
<source src="movie.ogg" type="video/ogg" /><!-- Firefox / Opera / Chrome10 -->
</video>
Best Option I could find is Git Windows Just install it and then right click on and click "Git Bash Here" this will open a bash window
This will open a bash window like this:
and the linux commands work...
I've tried 'sh' , 'vi' , 'ssh' , 'curl' ,etc... commands
if you want use VectorDrawable and ConstraintLayout
<FrameLayout
android:id="@+id/ok_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:foreground="?attr/selectableItemBackgroundBorderless"
android:background="@drawable/circle_button">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/icon_of_button"
android:layout_width="32dp"
android:layout_height="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:srcCompat="@drawable/ic_thumbs_up"/>
<TextView
android:id="@+id/text_of_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/icon_of_button"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="5dp"
android:textColor="@android:color/white"
android:text="ok"
/>
</android.support.constraint.ConstraintLayout>
</FrameLayout>
circle background: circle_button.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="1000dp" />
<solid android:color="#41ba7a" />
<stroke
android:width="2dip"
android:color="#03ae3c" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
Using array .map function that executes a function for every value in an array seems cleanest to me.
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
I had a similar problem setting up eclipse.
I changed: NATIVE connection to MANUAL and cleared the proxy settings for SOCKS in Windows
-> Preferences
-> General
-> Network connection
. That fixed the problem for me.
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.
Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt
) such as /mnt/c/Users/yourusername/files
within WSL. These files stay synced between WSL and Windows.
For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/
One additional comment regarding Vineet Reynolds answer.
I found out that I had to set -XX:+UseParallelGC
in eclipse.ini
I setup the virtual machine (vm) arguments as follows
-vmargs
-Dosgi.requiredJavaVersion=1.7
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
that solved the issue.
First installed sudo apt-get install php5-gd
, then sudo apt-get install php5-intl
and last one was sudo apt-get install php5-xsl
.
After that, it's installing as it should.
Try the code below, using jQuery extend method:
var json1 = {"name":"ramesh","age":"12"};
var json2 = {"member":"true"};
document.write(JSON.stringify($.extend(true,{},json1,json2)))
Use this syntax:
CREATE TEMPORARY TABLE t1 (select * from t2);
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
How about you creat a batch file with the command you want, and call it with Process.Start
dir.bat content:
dir
then call:
Process.Start("dir.bat");
Will call the bat file and execute the dir
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
In PyQt there are a lot of options for getting asynchronous behavior. For things that need event processing (ie. QtNetwork, etc) you should use the QThread example I provided in my other answer on this thread. But for the vast majority of your threading needs, I think this solution is far superior than the other methods.
The advantage of this is that the QThreadPool schedules your QRunnable instances as tasks. This is similar to the task pattern used in Intel's TBB. It's not quite as elegant as I like but it does pull off excellent asynchronous behavior.
This allows you to utilize most of the threading power of Qt in Python via QRunnable and still take advantage of signals and slots. I use this same code in several applications, some that make hundreds of asynchronous REST calls, some that open files or list directories, and the best part is using this method, Qt task balances the system resources for me.
import time
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
def async(method, args, uid, readycb, errorcb=None):
"""
Asynchronously runs a task
:param func method: the method to run in a thread
:param object uid: a unique identifier for this task (used for verification)
:param slot updatecb: the callback when data is receieved cb(uid, data)
:param slot errorcb: the callback when there is an error cb(uid, errmsg)
The uid option is useful when the calling code makes multiple async calls
and the callbacks need some context about what was sent to the async method.
For example, if you use this method to thread a long running database call
and the user decides they want to cancel it and start a different one, the
first one may complete before you have a chance to cancel the task. In that
case, the "readycb" will be called with the cancelled task's data. The uid
can be used to differentiate those two calls (ie. using the sql query).
:returns: Request instance
"""
request = Request(method, args, uid, readycb, errorcb)
QtCore.QThreadPool.globalInstance().start(request)
return request
class Request(QtCore.QRunnable):
"""
A Qt object that represents an asynchronous task
:param func method: the method to call
:param list args: list of arguments to pass to method
:param object uid: a unique identifier (used for verification)
:param slot readycb: the callback used when data is receieved
:param slot errorcb: the callback used when there is an error
The uid param is sent to your error and update callbacks as the
first argument. It's there to verify the data you're returning
After created it should be used by invoking:
.. code-block:: python
task = Request(...)
QtCore.QThreadPool.globalInstance().start(task)
"""
INSTANCES = []
FINISHED = []
def __init__(self, method, args, uid, readycb, errorcb=None):
super(Request, self).__init__()
self.setAutoDelete(True)
self.cancelled = False
self.method = method
self.args = args
self.uid = uid
self.dataReady = readycb
self.dataError = errorcb
Request.INSTANCES.append(self)
# release all of the finished tasks
Request.FINISHED = []
def run(self):
"""
Method automatically called by Qt when the runnable is ready to run.
This will run in a separate thread.
"""
# this allows us to "cancel" queued tasks if needed, should be done
# on shutdown to prevent the app from hanging
if self.cancelled:
self.cleanup()
return
# runs in a separate thread, for proper async signal/slot behavior
# the object that emits the signals must be created in this thread.
# Its not possible to run grabber.moveToThread(QThread.currentThread())
# so to get this QObject to properly exhibit asynchronous
# signal and slot behavior it needs to live in the thread that
# we're running in, creating the object from within this thread
# is an easy way to do that.
grabber = Requester()
grabber.Loaded.connect(self.dataReady, Qt.QueuedConnection)
if self.dataError is not None:
grabber.Error.connect(self.dataError, Qt.QueuedConnection)
try:
result = self.method(*self.args)
if self.cancelled:
# cleanup happens in 'finally' statement
return
grabber.Loaded.emit(self.uid, result)
except Exception as error:
if self.cancelled:
# cleanup happens in 'finally' statement
return
grabber.Error.emit(self.uid, unicode(error))
finally:
# this will run even if one of the above return statements
# is executed inside of the try/except statement see:
# https://docs.python.org/2.7/tutorial/errors.html#defining-clean-up-actions
self.cleanup(grabber)
def cleanup(self, grabber=None):
# remove references to any object or method for proper ref counting
self.method = None
self.args = None
self.uid = None
self.dataReady = None
self.dataError = None
if grabber is not None:
grabber.deleteLater()
# make sure this python obj gets cleaned up
self.remove()
def remove(self):
try:
Request.INSTANCES.remove(self)
# when the next request is created, it will clean this one up
# this will help us avoid this object being cleaned up
# when it's still being used
Request.FINISHED.append(self)
except ValueError:
# there might be a race condition on shutdown, when shutdown()
# is called while the thread is still running and the instance
# has already been removed from the list
return
@staticmethod
def shutdown():
for inst in Request.INSTANCES:
inst.cancelled = True
Request.INSTANCES = []
Request.FINISHED = []
class Requester(QtCore.QObject):
"""
A simple object designed to be used in a separate thread to allow
for asynchronous data fetching
"""
#
# Signals
#
Error = QtCore.pyqtSignal(object, unicode)
"""
Emitted if the fetch fails for any reason
:param unicode uid: an id to identify this request
:param unicode error: the error message
"""
Loaded = QtCore.pyqtSignal(object, object)
"""
Emitted whenever data comes back successfully
:param unicode uid: an id to identify this request
:param list data: the json list returned from the GET
"""
NetworkConnectionError = QtCore.pyqtSignal(unicode)
"""
Emitted when the task fails due to a network connection error
:param unicode message: network connection error message
"""
def __init__(self, parent=None):
super(Requester, self).__init__(parent)
class ExampleObject(QtCore.QObject):
def __init__(self, parent=None):
super(ExampleObject, self).__init__(parent)
self.uid = 0
self.request = None
def ready_callback(self, uid, result):
if uid != self.uid:
return
print "Data ready from %s: %s" % (uid, result)
def error_callback(self, uid, error):
if uid != self.uid:
return
print "Data error from %s: %s" % (uid, error)
def fetch(self):
if self.request is not None:
# cancel any pending requests
self.request.cancelled = True
self.request = None
self.uid += 1
self.request = async(slow_method, ["arg1", "arg2"], self.uid,
self.ready_callback,
self.error_callback)
def slow_method(arg1, arg2):
print "Starting slow method"
time.sleep(1)
return arg1 + arg2
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
obj = ExampleObject()
dialog = QtGui.QDialog()
layout = QtGui.QVBoxLayout(dialog)
button = QtGui.QPushButton("Generate", dialog)
progress = QtGui.QProgressBar(dialog)
progress.setRange(0, 0)
layout.addWidget(button)
layout.addWidget(progress)
button.clicked.connect(obj.fetch)
dialog.show()
app.exec_()
app.deleteLater() # avoids some QThread messages in the shell on exit
# cancel all running tasks avoid QThread/QTimer error messages
# on exit
Request.shutdown()
When exiting the application you'll want to make sure you cancel all of the tasks or the application will hang until every scheduled task has completed
I've made some string functions in order to split values, by using less pointers as I could because this code is intended to run on PIC18F processors. Those processors does not handle really good with pointers when you have few free RAM available:
#include <stdio.h>
#include <string.h>
char POSTREQ[255] = "pwd=123456&apply=Apply&d1=88&d2=100&pwr=1&mpx=Internal&stmo=Stereo&proc=Processor&cmp=Compressor&ip1=192&ip2=168&ip3=10&ip4=131&gw1=192&gw2=168&gw3=10&gw4=192&pt=80&lic=&A=A";
int findchar(char *string, int Start, char C) {
while((string[Start] != 0)) { Start++; if(string[Start] == C) return Start; }
return -1;
}
int findcharn(char *string, int Times, char C) {
int i = 0, pos = 0, fnd = 0;
while(i < Times) {
fnd = findchar(string, pos, C);
if(fnd < 0) return -1;
if(fnd > 0) pos = fnd;
i++;
}
return fnd;
}
void mid(char *in, char *out, int start, int end) {
int i = 0;
int size = end - start;
for(i = 0; i < size; i++){
out[i] = in[start + i + 1];
}
out[size] = 0;
}
void getvalue(char *out, int index) {
mid(POSTREQ, out, findcharn(POSTREQ, index, '='), (findcharn(POSTREQ, index, '&') - 1));
}
void main() {
char n_pwd[7];
char n_d1[7];
getvalue(n_d1, 1);
printf("Value: %s\n", n_d1);
}
Faced the same issue. To solve it,
$ sdk install gradle
using the package manager or $ brew install gradle
for mac. You might need to first install brew if not yet. If you want to find a workable C solution,
I believe you need this.
https://github.com/littlstar/b64.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "b64.h"
int
main (void) {
unsigned char *str = "brian the monkey and bradley the kinkajou are friends";
char *enc = b64_encode(str, strlen(str));
printf("%s\n", enc); // YnJpYW4gdGhlIG1vbmtleSBhbmQgYnJhZGxleSB0aGUga2lua2Fqb3UgYXJlIGZyaWVuZHM=
char *dec = b64_decode(enc, strlen(enc));
printf("%s\n", dec); // brian the monkey and bradley the kinkajou are friends
free(enc);
free(dec);
return 0;
}
The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook
While I totally agree there is no simple solution. There continues to be a single point of failure. Either the dockerfile, etcd, and so on. Apcera has a plan that looks like sidekick - dual authentication. In other words two container cannot talk unless there is a Apcera configuration rule. In their demo the uid/pwd was in the clear and could not be reused until the admin configured the linkage. For this to work, however, it probably meant patching Docker or at least the network plugin (if there is such a thing).
I think I came up with a really solid solution
OK! I know this problem is as old as the internet but I think I have a solution which I turned into a plugin called mutant-transition. My solution sets the style=""
attributes for tracked elements whenever theres a change in the DOM. the end result is that you can use good ole CSS for your transitions and not use hacky fixes or special javascript. The only thing you have to do is set what you want to track on the element in question using data-mutant-attributes="X"
.
<div data-mutant-attributes="height">
This is an example with mutant-transition
</div>
Thats it! This solution uses MutationObserver to follow changes in the DOM. Because of this, you don't really have to set anything up or use javascript to manually animate things. Changes are tracked automatically. However, because it uses MutationObserver, this will only transition in IE11+.
Fiddles!
You shouldn't need to set the value in the attributes parameter. MVC should automatically bind it for you.
@Html.HiddenFor(model => model.title, new { id= "natureOfVisitField" })
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
Your data is poorly formed. The value fields in particular have numerous spaces and new lines. Automated formatters won't work on this, as they will not modify the actual data. As you generate the data for output, filter it as needed to avoid the spaces.
Maybe something like this...
try
{
// ...
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = ex.Response as HttpWebResponse;
if (response != null)
{
Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
}
else
{
// no http status code available
}
}
else
{
// no http status code available
}
}
There are several ways to do that. Using HTML alone, you can write
<table border=1 frame=void rules=rows>
or, if you want a border above the first row and below the last row too,
<table border=1 frame=hsides rules=rows>
This is rather inflexible, though; you cannot e.g. make the lines dotted this way, or thicker than one pixel. This is why in the past people used special separator rows, consisting of nothing but some content intended to produce a line (it gets somewhat dirty, especially when you need to make rows e.g. just a few pixels high, but it’s possible).
For the most of it, people nowadays use CSS border
properties for the purpose. It’s fairly simple and cross-browser. But note that to make the lines continuous, you need to prevent spacing between cells, using either the cellspacing=0
attribute in the table
tag or the CSS rule table { border-collapse: collapse; }
. Removing such spacing may necessitate adding some padding (with CSS, preferably) inside the cells.
At the simplest, you could use
<style>
table {
border-collapse: collapse;
}
tr {
border: solid;
border-width: 1px 0;
}
</style>
This puts a border above the first row and below the last row too. To prevent that, add e.g. the following into the style sheet:
tr:first-child {
border-top: none;
}
tr:last-child {
border-bottom: none;
}
I suppose you could (using basic string manipulation) generate the query string in the PreparedStatement
to have a number of ?
's matching the number of items in your list.
Of course if you're doing that you're just a step away from generating a giant chained OR
in your query, but without having the right number of ?
in the query string, I don't see how else you can work around this.
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
You could try using the system stored procedure sp_help_job. This returns information on the job, its steps, schedules and servers. For example
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
SQL Books Online should contain lots of information about the records it returns.
For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job
Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).
Again, information on the fields can be found at MSDN. For example, check out the page for SysJobs
Based on this post here you can simply download the Microsoft Visual Studio 2010 Shell (Integrated) Redistributable Package and the targets are installed.
This avoids the need to install Visual Studio on the build server.
I have just tried this out now, and can verify that it works:
Before:
error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.
After the install:
[Builds correctly]
This is a far better solution than installing Visual Studio on a build server, obviously.
HTML Markup
<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>
Code
// JavaScript using jQuery
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
...
});
});
// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');
See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/
By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.
The push()
method adds new items to the end of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi
The exact answer to your question is already answered, but let's look at some other ways to add items to an array.
The unshift()
method adds new items to the beginning of an array, and returns the new length. Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango
And lastly, the concat()
method is used to join two or more arrays. Example:
var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);
// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon
Direct value
should work just fine:
var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex
returns -1 and the code breaks.
Make sure the element and its parents are visible. You cannot use focus on hidden elements
In Eclipse the Ant java.home variable is not based on the Windows JAVA_HOME environment variable. Instead it is set to the home directory of the project's JRE.
To change the default JRE (e.g. change it to a JDK) you can go to Windows->Preferences... and choose Java->Installed JREs.
To change just a single project's JRE you can go to Project->Properties and choose Java Build Path and choose the Libraries tab. Find the JRE System Library and click it, then choose Edit and choose the JRE (or JDK) that you want.
If that doesn't work then when running the build file you can choose Run as->Ant Build... and click the JRE tab, choose separate JRE and specify the JRE you want there.
In python 3.x. you use
print("Hello, World")
In Python 2.x. you use
print "Hello, World!"
Check whether you are scheduling a task to trigger an executable (.exe) or a batch (.bat) file. If you have scheduled any other file to open (for example a .txt or .docx file), the file not open.
Use this:
word = raw_input("Please enter a single word : ")
while True:
if " " in word:
word = raw_input("Please enter a single word : ")
else:
print "Thanks"
break
Keep in mind, the jQuery UI's datepicker is not initialized with datetimepicker(), there appears to be a plugin/addon here: http://trentrichardson.com/examples/timepicker/.
However, with just jquery-ui it's actually initialized as $("#example").datepicker()
. See jQuery's demo site here: http://jqueryui.com/demos/datepicker/
$(document).ready(function(){
$("#example1").datepicker();
});
To use the datetimepicker at the link referenced above, you will want to be certain that your scripts path is correct for the plugin.
The search criteria is one of these:
input[type=checkbox].MyClass:not(:checked)
input[type=checkbox].MyClass:checked
You probably want to connect to the change event.
Properly parenthesized for clarity, it is
hsb.s = (max != 0) ? (255 * delta / max) : 0;
meaning return either
255*delta/max
if max != 00
if max == 0The /i switch might be what your after.
From xcopy /?
/I If destination does not exist and copying more than one file, assumes that destination must be a directory.
C# 7.0 supports binary literals (and optional digit separators via underscore characters).
An example:
int myValue = 0b0010_0110_0000_0011;
You can also find more information on the Roslyn GitHub page.
I think that you have Spring Security on your class path and then spring security is automatically configured with a default user and generated password
Please look into your pom.xml file for:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
If you have that in your pom than you should have a log console message like this:
Using default security password: ce6c3d39-8f20-4a41-8e01-803166bb99b6
And in the browser prompt you will import the user user
and the password printed in the console.
Or if you want to configure spring security you can take a look at Spring Boot secured example
It is explained in the Spring Boot Reference documentation in the Security section, it indicates:
The default AuthenticationManager has a single user (‘user’ username and random password, printed at `INFO` level when the application starts up)
Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
Here is a simple demo to create customview (compoundview) by inflating from xml
attrs.xml
<resources>
<declare-styleable name="CustomView">
<attr format="string" name="text"/>
<attr format="reference" name="image"/>
</declare-styleable>
</resources>
CustomView.kt
class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
ConstraintLayout(context, attrs, defStyleAttr) {
init {
init(attrs)
}
private fun init(attrs: AttributeSet?) {
View.inflate(context, R.layout.custom_layout, this)
val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
try {
val text = ta.getString(R.styleable.CustomView_text)
val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
if (drawableId != 0) {
val drawable = AppCompatResources.getDrawable(context, drawableId)
image_thumb.setImageDrawable(drawable)
}
text_title.text = text
} finally {
ta.recycle()
}
}
}
custom_layout.xml
We should use merge
here instead of ConstraintLayout
because
If we use ConstraintLayout
here, layout hierarchy will be ConstraintLayout
->ConstraintLayout
-> ImageView
+ TextView
=> we have 1 redundant ConstraintLayout
=> not very good for performance
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:parentTag="android.support.constraint.ConstraintLayout">
<ImageView
android:id="@+id/image_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="@id/image_thumb"
app:layout_constraintStart_toStartOf="@id/image_thumb"
app:layout_constraintTop_toBottomOf="@id/image_thumb"
tools:text="Text" />
</merge>
Using activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f00"
app:image="@drawable/ic_android"
app:text="Android" />
<your_package.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0f0"
app:image="@drawable/ic_adb"
app:text="ADB" />
</LinearLayout>
Result
select
*
from sales
where
dateadd(dd, datediff(dd, 0, salesDate), 0) = '11/11/2010'
You can call a stored procedure using the following syntax:
$result = mysql_query('CALL getNodeChildren(2)');
To add to wflynny's answer above, you can find the available colormaps here
Example:
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)
or alternatively,
plt.scatter(x, y, c=t, cmap='jet')
Maybe you don't need this logic for a responsive behavior.
E.g.
placement: 'auto left'
Bootstrap 3 has auto value for placement. Bootstrap doc:
When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right.
I believe that I have the simplest answer yet using Spring Boot 1.4, included imports for the test class.:
public class SomeClass { /// this goes in it's own file
//// fields go here
}
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class ControllerTest {
@Autowired private MockMvc mvc;
@Autowired private ObjectMapper mapper;
private SomeClass someClass; //this could be Autowired
//, initialized in the test method
//, or created in setup block
@Before
public void setup() {
someClass = new SomeClass();
}
@Test
public void postTest() {
String json = mapper.writeValueAsString(someClass);
mvc.perform(post("/someControllerUrl")
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
I came across the same problem, and found that easier way is to undock the developer tool's video to a separate window! (Using the right hand top corner toolbar button of developer tools window) and in the new window , simply say select all and copy and paste to excel!!
The Range object has both width and height properties, which are measured in points.
One more solution via htmlfile
ActiveX:
Function EncodeUriComponent(strText)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
objHtmlfile.parentWindow.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
End If
EncodeUriComponent = objHtmlfile.parentWindow.encode(strText)
End Function
Declaring htmlfile
DOM document object as static variable gives the only small delay when called first time due to init, and makes this function very fast for numerous calls, e. g. for me it converts the string of 100 chars length 100000 times in 2 seconds approx..
I've got the same problem on Eclipse 3.8.1. For me it worked to set the artifact type to executable:
Right click on the project -> C/C++ Build -> Settings -> Build Artifact -> Artifact Type: Executable
Finally rebuilding the project produced the Binaries entry in the Project Explorer.
Here is the sample code, which is working in Android Oreo and less than Oreo.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
notificationManager.createNotificationChannel(notificationChannel);
builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
} else {
builder = new NotificationCompat.Builder(getApplicationContext());
}
builder = builder
.setSmallIcon(R.drawable.ic_notification_icon)
.setColor(ContextCompat.getColor(context, R.color.color))
.setContentTitle(context.getString(R.string.getTitel))
.setTicker(context.getString(R.string.text))
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
notificationManager.notify(requestCode, builder.build());
You must check the certificate hash code.
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain,
errors) =>
{
var hashString = certificate.GetCertHashString();
if (hashString != null)
{
var certHashString = hashString.ToLower();
return certHashString == "dec2b525ddeemma8ccfaa8df174455d6e38248c5";
}
return false;
};
No need to use string functions. You can use something that's actually designed for what you want: pathinfo()
:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
I follow this simple way:
ctrl + F
(Find/repace
).Find What:
field. But don't worry.space
in Replace With:
field.Replce All
.Done! :)
See:
Note: This method applies to reverse (Replace a space by a tab) case too.
You could make an AJAX call (likely using a library such as using Prototype.js or JQuery). AJAX can handle both GET and POST options.
By keys()
and values()
methods of dictionary and zip
.
zip
will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
This is a good case for using another thread:
// Call some method
this.Method();
Task.Factory.StartNew(() =>
{
Thread.Sleep(20000);
// Do things here.
// NOTE: You may need to invoke this to your main thread depending on what you're doing
});
The above code expects .NET 4.0 or above, otherwise try:
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
Thread.Sleep(20000);
// Do things here
}));
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState
to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}?
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView
:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
I solved it this way:
$ brew uninstall --force node
$ brew uninstall --force npm
after it
$ brew install node
which suggested me to overwrite simlinks
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink share/doc/node/gdbinit
Target /usr/local/share/doc/node/gdbinit
already exists. You may want to remove it:
rm '/usr/local/share/doc/node/gdbinit'
To force the link and overwrite all conflicting files:
brew link --overwrite node
after executing
$ brew link --overwrite node
everything worked again.
You will find these assemblies in the Extensions group under Assemblies in Visual Studio 2010, 2012 & 2013 (Reference Manager)
Unless you do some kind of post-processing work, the video will never be better than the original frames. Also just like a flip-book, if you have a big "jump" between keyframes it will look funny. You generally need enough "tweens" in between the keyframes to give smooth animation. HTH
JavaScript With Selenium WebDriver
Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver(); // This opens a window
String url = "----";
/*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/
JavascriptExecutor jse = (JavascriptExecutor) driver;
if (jse instanceof WebDriver) {
//Launching the browser application
jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");
//Opend Site and click on some links. then you can apply go(-1)--> back forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();
jse.executeScript("window.history.go(0)");
jse.executeScript("window.history.go(-2)");
jse.executeScript("window.history.forward(-2)");
String title = (String)jse.executeScript("return document.title");
System.out.println(" Title Of site : "+title);
String domain = (String)jse.executeScript("return document.domain");
System.out.println("Web Site Domain-Name : "+domain);
// To get all NodeList[1052] document.querySelectorAll('*'); or document.all
jse.executeAsyncScript("document.getElementsByTagName('*')");
String error=(String) jse.executeScript("return window.jsErrors");
System.out.println("Windowerrors : "+error);
System.out.println("To Find the input tag position from top");
ArrayList<?> al = (ArrayList<?>) jse.executeScript(
"var source = [];"+
"var inputs = document.getElementsByTagName('input');"+
"for(var i = 0; i < inputs.length; i++) { " +
" source[i] = inputs[i].offsetParent.offsetTop" + //" inputs[i].type = 'radio';"
"}"+
"return source"
);//inputs[i].offsetParent.offsetTop inputs[i].type
System.out.println("next");
System.out.println("array : "+al);
// (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys
Keys k = null;
String selectAll = Keys.chord(Keys.CONTROL, "a");
WebElement body = driver.findElement(By.tagName("body"));
body.sendKeys(selectAll);
// Search for text in Site. Gets all ViewSource content and checks their.
if (driver.getPageSource().contains("login")) {
System.out.println("Text present in Web Site");
}
Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
System.out.println("Client Body Height : "+clent_height);
// using selenium we con only execute script but not JS-functions.
}
driver.quit(); // to close browser
}
To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.
Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
String js_TxtFile = "";
while (sc.hasNext()) {
String[] s = sc.next().split("\r\n");
for (int i = 0; i < s.length; i++) {
js_TxtFile += s[i];
js_TxtFile += " ";
}
}
String title = (String) jse.executeScript(js_TxtFile);
System.out.println("Title : "+title);
document.title & document.getElementById() is a property/method available in Browsers.
JsFile.txt
var title = getTitle();
return title;
function getTitle() {
return document.title;
}
If can deviate a little from the straight path of DataTable -> SQL table, it can also be done via a list of objects:
1) DataTable -> Generic list of objects
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
Source and more details can be found here. Missing properties will remain to their default values (0 for int
s, null for reference types etc.)
2) Push the objects into the database
One way is to use EntityFramework.BulkInsert
extension. An EF datacontext is required, though.
It generates the BULK INSERT command required for fast insert (user defined table type solution is much slower than this).
Although not the straight method, it helps constructing a base of working with list of objects instead of DataTable
s which seems to be much more memory efficient.
I have found that 6 decimal places is sometimes required (at least in Chrome) for the 1/3 to return a perfect result.
E.g., 1140px / 3 = 380px
If you had 3 elements within the 1140 container, they would need to have a width set to 33.333333% before Chrome's inspector tool shows that they are at 380px. Any less amount of decimal places, and Chrome returns a lesser width of 379.XXXpx
What about using Replace all? Just replace All on bracket to space. And comma to space. And I think you can achieve it.
Doctrine now has Criteria
which offers a single API for filtering collections with SQL and in PHP, depending on the context.
Update
This will achieve the result in the accepted answer, without getting everything from the database.
use Doctrine\Common\Collections\Criteria;
/**
* @ORM\Entity
*/
class Member {
// ...
public function getCommentsFiltered($ids) {
$criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));
return $this->getComments()->matching($criteria);
}
}
for key, value in d.iteritems():
print key, '\t', value
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
Greg is right-- you can use sys.stdout.write
Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then
lst = ['h', 'm']
print "".join(lst)
It's very very simple when you use a library to do that for you. Try this library
You can call like this:
Icon.on(holderView).color(R.color.your_color).icon(R.mipmap.your_icon).put();
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
you can use your method by this way
var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();
$http({
url: '/api/apiControllerName/methodName',
method: 'POST',
params: {application:app, from:d1, to:d2},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
//timeout: 1,
//cache: false,
//transformRequest: false,
//transformResponse: false
}).then(function (results) {
return results;
}).catch(function (e) {
});
The built-in timeit module works best from the IPython command line.
To time functions from within a module:
from timeit import default_timer as timer
import sys
def timefunc(func, *args, **kwargs):
"""Time a function.
args:
iterations=3
Usage example:
timeit(myfunc, 1, b=2)
"""
try:
iterations = kwargs.pop('iterations')
except KeyError:
iterations = 3
elapsed = sys.maxsize
for _ in range(iterations):
start = timer()
result = func(*args, **kwargs)
elapsed = min(timer() - start, elapsed)
print(('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, elapsed)))
return result
You can do this simply like this
$('#image_id').click(function() {
$("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1');
});
where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.
EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').value = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Sum</TITLE>
<script type="text/javascript">
function sum()
{
var num1 = document.myform.number1.value;
var num2 = document.myform.number2.value;
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('add').innerHTML = sum;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" NAME="number1" VALUE=""/> +
<INPUT TYPE="text" NAME="number2" VALUE=""/>
<INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
<DIV ID="add"></DIV>
</FORM>
</BODY>
</HTML>
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
Set input type in XML as well as in JAVA file like this,
In XML,
android:inputType="textMultiLine|textCapSentences"
It will also allow multiline and in JAVA file,
edittext.setRawInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
make sure your keyboard's Auto-Capitalization setting is Enabled.
We can send data one Activty1 to Activity2 with multiple ways like.
1- Intent
2- bundle
3- create an object and send through intent
.................................................
1 - Using intent
Pass the data through intent
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
intentActivity1.putExtra("name", "Android");
startActivity(intentActivity1);
Get the data in Activity2 calss
Intent intent = getIntent();
if(intent.hasExtra("name")){
String userName = getIntent().getStringExtra("name");
}
..................................................
2- Using Bundle
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putExtra("name", "Android");
intentActivity1.putExtra(bundle);
startActivity(bundle);
Get the data in Activity2 calss
Intent intent = getIntent();
if(intent.hasExtra("name")){
String userName = getIntent().getStringExtra("name");
}
..................................................
3- Put your Object into Intent
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
intentActivity1.putExtra("myobject", myObject);
startActivity(intentActivity1);
Receive object in the Activity2 Class
Intent intent = getIntent();
Myobject obj = (Myobject) intent.getSerializableExtra("myobject");
I prefer this as the best way of reversing a string using a for loop.
def reverse_a_string(str):
result=" "
for i in range(len(str),1,-1):
result= result+ str[i-1]
return result
print reverse_a_string(input())
I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.
1.Class
@WebServlet("/display")
public class MyFirst extends HttpServlet {
2.Class
@WebServlet("/display")
public class MySecond extends HttpServlet {
no. You can use UDF in which you can pass parameters.
For those people still arriving at this question in 2020 or later, there are newer options that may be better than both of these. For example, utf8mb4_0900_ai_ci
.
All these collations are for the UTF-8 character encoding. The differences are in how text is sorted and compared.
_unicode_ci
and _general_ci
are two different sets of rules for sorting and comparing text according to the way we expect. Newer versions of MySQL introduce new sets of rules, too, such as _0900_ai_ci
for equivalent rules based on Unicode 9.0 - and with no equivalent _general_ci
variant. People reading this now should probably use one of these newer collations instead of either _unicode_ci
or _general_ci
. The description of those older collations below is provided for interest only.
MySQL is currently transitioning away from an older, flawed UTF-8 implementation. For now, you need to use utf8mb4
instead of utf8
for the character encoding part, to ensure you are getting the fixed version. The flawed version remains for backward compatibility, though it is being deprecated.
Key differences
utf8mb4_unicode_ci
is based on the official Unicode rules for universal sorting and comparison, which sorts accurately in a wide range of languages.
utf8mb4_general_ci
is a simplified set of sorting rules which aims to do as well as it can while taking many short-cuts designed to improve speed. It does not follow the Unicode rules and will result in undesirable sorting or comparison in some situations, such as when using particular languages or characters.
On modern servers, this performance boost will be all but negligible. It was devised in a time when servers had a tiny fraction of the CPU performance of today's computers.
Benefits of utf8mb4_unicode_ci
over utf8mb4_general_ci
utf8mb4_unicode_ci
, which uses the Unicode rules for sorting and comparison, employs a fairly complex algorithm for correct sorting in a wide range of languages and when using a wide range of special characters. These rules need to take into account language-specific conventions; not everybody sorts their characters in what we would call 'alphabetical order'.
As far as Latin (ie "European") languages go, there is not much difference between the Unicode sorting and the simplified utf8mb4_general_ci
sorting in MySQL, but there are still a few differences:
For examples, the Unicode collation sorts "ß" like "ss", and "Œ" like "OE" as people using those characters would normally want, whereas utf8mb4_general_ci
sorts them as single characters (presumably like "s" and "e" respectively).
Some Unicode characters are defined as ignorable, which means they shouldn't count toward the sort order and the comparison should move on to the next character instead. utf8mb4_unicode_ci
handles these properly.
In non-latin languages, such as Asian languages or languages with different alphabets, there may be a lot more differences between Unicode sorting and the simplified utf8mb4_general_ci
sorting. The suitability of utf8mb4_general_ci
will depend heavily on the language used. For some languages, it'll be quite inadequate.
What should you use?
There is almost certainly no reason to use utf8mb4_general_ci
anymore, as we have left behind the point where CPU speed is low enough that the performance difference would be important. Your database will almost certainly be limited by other bottlenecks than this.
In the past, some people recommended to use utf8mb4_general_ci
except when accurate sorting was going to be important enough to justify the performance cost. Today, that performance cost has all but disappeared, and developers are treating internationalization more seriously.
There's an argument to be made that if speed is more important to you than accuracy, you may as well not do any sorting at all. It's trivial to make an algorithm faster if you do not need it to be accurate. So, utf8mb4_general_ci
is a compromise that's probably not needed for speed reasons and probably also not suitable for accuracy reasons.
One other thing I'll add is that even if you know your application only supports the English language, it may still need to deal with people's names, which can often contain characters used in other languages in which it is just as important to sort correctly. Using the Unicode rules for everything helps add peace of mind that the very smart Unicode people have worked very hard to make sorting work properly.
What the parts mean
Firstly, ci
is for case-insensitive sorting and comparison. This means it's suitable for textual data, and case is not important. The other types of collation are cs
(case-sensitive) for textual data where case is important, and bin
, for where the encoding needs to match, bit for bit, which is suitable for fields which are really encoded binary data (including, for example, Base64). Case-sensitive sorting leads to some weird results and case-sensitive comparison can result in duplicate values differing only in letter case, so case-sensitive collations are falling out of favor for textual data - if case is significant to you, then otherwise ignorable punctuation and so on is probably also significant, and a binary collation might be more appropriate.
Next, unicode
or general
refers to the specific sorting and comparison rules - in particular, the way text is normalized or compared. There are many different sets of rules for the utf8mb4 character encoding, with unicode
and general
being two that attempt to work well in all possible languages rather than one specific one. The differences between these two sets of rules are the subject of this answer. Note that unicode
uses rules from Unicode 4.0. Recent versions of MySQL add the rulesets unicode_520
using rules from Unicode 5.2, and 0900
(dropping the "unicode_" part) using rules from Unicode 9.0.
And lastly, utf8mb4
is of course the character encoding used internally. In this answer I'm talking only about Unicode based encodings.
Mostly likely middle click your mouse.
Or try Shift + Insert.
It all depends on terminal used and X11-config for mouse.
just use bash
while read -r line
do
case "$line" in
*MYSQL_ROLE=master*)
echo "do your stuff";;
*) echo "doesn't exist";;
esac
done <"/etc/aws/hosts.conf"
We could also specify the files, to include just the files with relative changes, particularly when they span multiple directories e.x.
git diff ~/path1/file1.ext ~/path2/file2.ext...fileN.ext > ~/whatever_path/whatever_name.patch
I found this to be not specified in the answers or comments, which are all relevant and correct, so chose to add it. Explicit is better than implicit!
The issue here is that input()
returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.
To fix this, simply call int()
to convert your string to an integer:
int(input(...))
As a note, if you want to deal with decimal numbers, you will want to use one of float()
or decimal.Decimal()
(depending on your accuracy and speed needs).
Note that the more pythonic way of looping over a series of numbers (as opposed to a while
loop and counting) is to use range()
. For example:
def main():
print("Let me Retire Financial Calculator")
deposit = float(input("Please input annual deposit in dollars: $"))
rate = int(input ("Please input annual rate in percentage: %")) / 100
time = int(input("How many years until retirement?"))
value = 0
for x in range(1, time+1):
value = (value * rate) + deposit
print("The value of your account after" + str(x) + "years will be $" + str(value))
In this case, I map the height of the Author label to an appropriate IBOutlet:
@property (retain, nonatomic) IBOutlet NSLayoutConstraint* authorLabelHeight;
and when I set the height of the constraint to 0.0f, we preserve the "padding", because the Play button's height allows for it.
cell.authorLabelHeight.constant = 0;
import os, sys, re, glob
pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
for line in reader:
retline = pattern.sub(replacementStringMatchesPattern, "", line)
sys.stdout.write(retline)
print (retline)
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
string strConn = "Data Source=ORCL134; User ID=user; Password=psd;";
System.Data.OracleClient.OracleConnection con = newSystem.Data.OracleClient.OracleConnection(strConn);
con.Open();
System.Data.OracleClient.OracleCommand Cmd =
new System.Data.OracleClient.OracleCommand(
"SELECT * FROM TBLE_Name WHERE ColumnName_year= :year", con);
//for oracle..it is :object_name and for sql it s @object_name
Cmd.Parameters.Add(new System.Data.OracleClient.OracleParameter("year", (txtFinYear.Text).ToString()));
System.Data.OracleClient.OracleDataAdapter da = new System.Data.OracleClient.OracleDataAdapter(Cmd);
DataSet myDS = new DataSet();
da.Fill(myDS);
try
{
lblBatch.Text = "Batch Number is : " + Convert.ToString(myDS.Tables[0].Rows[0][19]);
lblBatch.ForeColor = System.Drawing.Color.Green;
lblBatch.Visible = true;
}
catch
{
lblBatch.Text = "No Data Found for the Year : " + txtFinYear.Text;
lblBatch.ForeColor = System.Drawing.Color.Red;
lblBatch.Visible = true;
}
da.Dispose();
con.Close();
As of API 21, you could also use:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Sometimes, tab
does mess up while indenting. One way is to obviously use the tab
and backspace
to correctly indent the code.
Another way is to use space
4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced
that line to the previous line and then pressed enter
. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.
Moreover, you can still use the "ordinary" if
syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
Make a string criteria to search for, like this:
string searchExpression = "ID = 5"
Then use the .Select()
method of the DataTable
object, like this:
DataRow[] foundRows = YourDataTable.Select(searchExpression);
Now you can loop through the results, like this:
int numberOfCalls;
bool result;
foreach(DataRow dr in foundRows)
{
// Get value of Calls here
result = Int32.TryParse(dr["Calls"], out numberOfCalls);
// Optionally, you can check the result of the attempted try parse here
// and do something if you wish
if(result)
{
// Try parse to 32-bit integer worked
}
else
{
// Try parse to 32-bit integer failed
}
}
I present a small hybrid script [BAT/VBS] to create a desktop shortcut. And you can of course modifie it to your purpose.
@echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo Dim objShell,DesktopPath,objShortCut,MyTab
echo Set objShell = CreateObject("WScript.Shell"^)
echo MyTab = Split(ApplicationPath,"\"^)
echo If Nom = "" Then
echo Nom = MyTab(UBound(MyTab^)^)
echo End if
echo DesktopPath = objShell.SpecialFolders("Desktop"^)
echo Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo objShortCut.TargetPath = Dblquote(ApplicationPath^)
echo ObjShortCut.IconLocation = "Winver.exe,0"
echo objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test
Pause > Nul
::********************************************************************************************
Try using
$("#mydialog").closest(".ui-dialog-titlebar").hide();
This will hide all dialogs titles
$(".ui-dialog-titlebar").hide();
A generic solution which translates any json list of flat objects to csv.
Pass the input.json file as first argument on command line.
import csv, json, sys
input = open(sys.argv[1])
data = json.load(input)
input.close()
output = csv.writer(sys.stdout)
output.writerow(data[0].keys()) # header row
for row in data:
output.writerow(row.values())
Generally, I agree with @kgrittn's advice. Go for it.
But to address your basic question about concat()
: The new function concat()
is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.
If you can rule out null values, the good old (SQL standard) concatenation operator ||
is still the best choice, and @luis' answer is just fine:
SELECT col_a || col_b;
If either of your columns can be null, the result would be null in that case. You could defend with COALESCE
:
SELECT COALESCE(col_a, '') || COALESCE(col_b, '');
But that get tedious quickly with more arguments. That's where concat()
comes in, which never returns null, not even if all arguments are null. Per documentation:
NULL arguments are ignored.
SELECT concat(col_a, col_b);
The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string ''
, but one might want null instead (at least I would). One possible way:
SELECT CASE
WHEN col_a IS NULL THEN col_b
WHEN col_b IS NULL THEN col_a
ELSE col_a || col_b
END;
This gets more complex with more columns quickly. Again, use concat()
but add a check for the special condition:
SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
ELSE concat(col_a, col_b) END;
How does this work?
(col_a, col_b)
is shorthand notation for a row type expression ROW (col_a, col_b)
. And a row type is only null if all columns are null. Detailed explanation:
Also, use concat_ws()
to add separators between elements (ws
for "with separator").
An expression like the one in Kevin's answer:
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
is tedious to prepare for null values in PostgreSQL 8.3 (without concat()
). One way (of many):
SELECT COALESCE(
CASE
WHEN $1.zipcode IS NULL THEN $1.city
WHEN $1.city IS NULL THEN $1.zipcode
ELSE $1.zipcode || ' - ' || $1.city
END, '')
|| COALESCE(', ' || $1.state, '');
STABLE
concat()
and concat_ws()
are STABLE
functions, not IMMUTABLE
because they can invoke datatype output functions (like timestamptz_out
) that depend on locale settings.
Explanation by Tom Lane.
This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE
function wrapper. Example here:
Probably the best way is via the built-in struct module:
>>> import struct
>>> x = 1245427
>>> struct.pack('>BH', x >> 16, x & 0xFFFF)
'\x13\x00\xf3'
>>> struct.pack('>L', x)[1:] # could do it this way too
'\x13\x00\xf3'
Alternatively -- and I wouldn't usually recommend this, because it's mistake-prone -- you can do it "manually" by shifting and the chr()
function:
>>> x = 1245427
>>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF)
'\x13\x00\xf3'
Out of curiosity, why do you only want three bytes? Usually you'd pack such an integer into a full 32 bits (a C unsigned long
), and use struct.pack('>L', 1245427)
but skip the [1:]
step?
If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL
A clean way to do this using modern JavaScript is as follows:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.
Also, the project is mostly dormant... the last release was in 2004.
For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.
If you don't care too much about performance and want to use the straightforward way, you can use either DIV
or IDIV
.
DIV
or IDIV
takes only one operand where it divides
a certain register with this operand, the operand can
be register or memory location only.
When operand is a byte: AL = AL / operand, AH = remainder (modulus).
Ex:
MOV AL,31h ; Al = 31h
DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h
when operand is a word: AX = (AX) / operand, DX = remainder (modulus).
Ex:
MOV AX,9031h ; Ax = 9031h
DIV BX ; Ax=1808h & Dx(remainder)= 01h
Official Python .msi installers are designed to replace:
A snapshot installer is designed to replace any snapshot with a lower micro version.
(See responsible code for 2.x, for 3.x)
Any other versions are not necessarily compatible and are thus installed alongside the existing one. If you wish to uninstall the old version, you'll need to do that manually. And also uninstall any 3rd-party modules you had for it:
bdist_wininst
packages (Windows .exe
s), uninstall them before uninstalling the version, or the uninstaller might not work correctly if it has custom logicsetuptools
/pip
that reside in Lib\site-packages
can just be deleted afterwards%APPDATA%/Python/PythonXY/site-packages
and can likewise be deletedI had a similar problem. I was using the "$. GetJSON" jQuery and everything worked perfectly in Firefox and Chrome.
But it did not work in IE. So I tried to directly access the URL of json, but in IE it asked if I wanted to download the file.
After much searching I saw that there must be a header in the result with a content-type, in my case, the content-type was:
header("Content-type: text/html; charset=iso-8859-1");
But when the page that made the request receives this json, in IE, you have to be specified SAME CONTENT-TYPE, in my case was:
$.getJSON (
"<? site_url php echo (" ajax / tipoMenu ")?>"
{contentType: 'text / html; charset = utf-8'},
function (result) {
hugs
If you are passing data to a DOM element from the server, you should set the data on the element:
<a id="foo" data-foo="bar" href="#">foo!</a>
The data can then be accessed using .data()
in jQuery:
console.log( $('#foo').data('foo') );
//outputs "bar"
However when you store data on a DOM node in jQuery using data, the variables are stored on the node object. This is to accommodate complex objects and references as storing the data on the node element as an attribute will only accommodate string values.
Continuing my example from above:$('#foo').data('foo', 'baz');
console.log( $('#foo').attr('data-foo') );
//outputs "bar" as the attribute was never changed
console.log( $('#foo').data('foo') );
//outputs "baz" as the value has been updated on the object
Also, the naming convention for data attributes has a bit of a hidden "gotcha":
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('fooBarBaz') );
//outputs "fizz-buzz" as hyphens are automatically camelCase'd
The hyphenated key will still work:
HTML:<a id="bar" data-foo-bar-baz="fizz-buzz" href="#">fizz buzz!</a>
JS:
console.log( $('#bar').data('foo-bar-baz') );
//still outputs "fizz-buzz"
However the object returned by .data()
will not have the hyphenated key set:
$('#bar').data().fooBarBaz; //works
$('#bar').data()['fooBarBaz']; //works
$('#bar').data()['foo-bar-baz']; //does not work
It's for this reason I suggest avoiding the hyphenated key in javascript.
For HTML, keep using the hyphenated form. HTML attributes are supposed to get ASCII-lowercased automatically, so <div data-foobar></div>
, <DIV DATA-FOOBAR></DIV>
, and <dIv DaTa-FoObAr></DiV>
are supposed to be treated as identical, but for the best compatibility the lower case form should be preferred.
The .data()
method will also perform some basic auto-casting if the value matches a recognized pattern:
<a id="foo"
href="#"
data-str="bar"
data-bool="true"
data-num="15"
data-json='{"fizz":["buzz"]}'>foo!</a>
JS:
$('#foo').data('str'); //`"bar"`
$('#foo').data('bool'); //`true`
$('#foo').data('num'); //`15`
$('#foo').data('json'); //`{fizz:['buzz']}`
This auto-casting ability is very convenient for instantiating widgets & plugins:
$('.widget').each(function () {
$(this).widget($(this).data());
//-or-
$(this).widget($(this).data('widget'));
});
If you absolutely must have the original value as a string, then you'll need to use .attr()
:
<a id="foo" href="#" data-color="ABC123"></a>
<a id="bar" href="#" data-color="654321"></a>
JS:
$('#foo').data('color').length; //6
$('#bar').data('color').length; //undefined, length isn't a property of numbers
$('#foo').attr('data-color').length; //6
$('#bar').attr('data-color').length; //6
This was a contrived example. For storing color values, I used to use numeric hex notation (i.e. 0xABC123), but it's worth noting that hex was parsed incorrectly in jQuery versions before 1.7.2, and is no longer parsed into a Number
as of jQuery 1.8 rc 1.
jQuery 1.8 rc 1 changed the behavior of auto-casting. Before, any format that was a valid representation of a Number
would be cast to Number
. Now, values that are numeric are only auto-cast if their representation stays the same. This is best illustrated with an example.
<a id="foo"
href="#"
data-int="1000"
data-decimal="1000.00"
data-scientific="1e3"
data-hex="0x03e8">foo!</a>
JS:
// pre 1.8 post 1.8
$('#foo').data('int'); // 1000 1000
$('#foo').data('decimal'); // 1000 "1000.00"
$('#foo').data('scientific'); // 1000 "1e3"
$('#foo').data('hex'); // 1000 "0x03e8"
If you plan on using alternative numeric syntaxes to access numeric values, be sure to cast the value to a Number
first, such as with a unary +
operator.
+$('#foo').data('hex'); // 1000
There is an Exception
constructor that takes also the cause argument: Exception(String message, Throwable t).
You can use it to propagate the stacktrace:
try{
//...
}catch(Exception E){
if(!transNbr.equals("")){
throw new Exception("transaction: " + transNbr, E);
}
//...
}
I would suggest:
SELECT DAY(EOMONTH(GETDATE()))
Unity is a library like many others that allows you to get an instance of a requested type without having to create it yourself. So given.
public interface ICalculator
{
void Add(int a, int b);
}
public class Calculator : ICalculator
{
public void Add(int a, int b)
{
return a + b;
}
}
You would use a library like Unity to register Calculator to be returned when the type ICalculator is requested aka IoC (Inversion of Control) (this example is theoretical, not technically correct).
IoCLlibrary.Register<ICalculator>.Return<Calculator>();
So now when you want an instance of an ICalculator you just...
Calculator calc = IoCLibrary.Resolve<ICalculator>();
IoC libraries can usually be configured to either hold a singleton or create a new instance every time you resolve a type.
Now let's say you have a class that relies on an ICalculator to be present you could have..
public class BankingSystem
{
public BankingSystem(ICalculator calc)
{
_calc = calc;
}
private ICalculator _calc;
}
And you can setup the library to inject a object into the constructor when it's created.
So DI or Dependency Injection means to inject any object another might require.
when using JavaScript it will work for me
<script src='https://www.google.com/recaptcha/api.js'></script>_x000D_
<script>_x000D_
function submitUserForm() {_x000D_
var response = grecaptcha.getResponse();_x000D_
if(response.length == 0) {_x000D_
document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
function verifyCaptcha() {_x000D_
document.getElementById('g-recaptcha-error').innerHTML = '';_x000D_
}_x000D_
</script>
_x000D_
<form method="post" onsubmit="return submitUserForm();">_x000D_
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY" data-callback="verifyCaptcha"></div>_x000D_
<div id="g-recaptcha-error"></div>_x000D_
<input type="submit" name="submit" value="Submit" />_x000D_
</form>
_x000D_
Try
sudo systemctl start postgresql@12-main
Here my postgresql version is 12.
If you store your colorcodes in a global variable you should be able to access it from either javascript file.
If you check the following SQL tutorial on splitting string using SQL, you will find a number of functions that can be used to split a given string on SQL Server
For example, SplitAndReturnNth UDF function can be used to split a text using a separator and return the Nth piece as the output of the function
select dbo.SplitAndReturnNth('Hello John Smith',' ',2)
I just ran into this error message (after upgrading to nextjs 9 some transpiled imports started giving this error). I managed to fix them using syntax like this:
import * as Home from './layouts/Home';
you can use below code to get email address after ? in the URL
<?php_x000D_
if (isset($_GET['email'])) {_x000D_
echo $_GET['email'];_x000D_
}
_x000D_
to accomplish what you want, you must getPaths from the polygon. Paths will be an array of LatLng points. you get the elements of the array and split the LatLng pairs with the methods .lat and .lng in the function below, i have a redundant array corresponding to a polyline that marks the perimeter around the polygon.
saving is another story. you can then opt for many methods. you may save your list of points as a csv formatted string and export that to a file (easiest solution, by far). i highly recommend GPS TXT formats, like the ones (there are 2) readable by GPS TRACKMAKER (great free version software). if you are competent to save them to a database, that is a great solution (i do both, for redundancy).
function areaPerimeterParse(areaPerimeterPath) {
var flag1stLoop = true;
var areaPerimeterPathArray = areaPerimeterPath.getPath();
var markerListParsedTXT = "Datum,WGS84,WGS84,0,0,0,0,0\r\n";
var counter01 = 0;
var jSpy = "";
for (var j = 0;j<areaPerimeterPathArray.length;j++) {
counter01++;
jSpy += j+" ";
if (flag1stLoop) {
markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,1'+'\r\n';
flag1stLoop = false;
} else {
markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
}
}
// last point repeats first point
markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(0).lat(), areaPerimeterPathArray.getAt(0).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
return markerListParsedTXT;
}
attention, the line that ends with ",1" (as opposed to ",0") starts a new polygon (this format allows you to save multiple polygons in the same file). i find TXT more human readable than the XML based formats GPX and KML.
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set
. You should realize that it has absolutely no meaning for most implementations of Set
. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare @thing varchar(100)
select @thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(@thing)
--This converts just fine.
select convert(float,@thing)
select @thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(@thing)
--This convert throws.
select convert(float,@thing)
You have to add the row explicitly to the table
table.Rows.Add(row);
If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url
command:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015)
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured urls.
Here is a script you can use to merge your master branch into your current branch.
The script does the following:
Save this code as a batch file (.bat) and place the script anywhere in your repository. Then click on it to run it and you are set.
:: This batch file pulls current master and merges into current branch
@echo off
:: Option to use the batch file outside the repo and pass the repo path as an arg
set repoPath=%1
cd %repoPath%
FOR /F "tokens=*" %%g IN ('git rev-parse --abbrev-ref HEAD') do (SET currentBranch=%%g)
echo current branch is %currentBranch%
echo switching to master
git checkout master
echo.
echo pulling origin master
git pull origin master
echo.
echo switching back to %currentBranch%
git checkout %currentBranch%
echo.
echo attemting merge master into %currentBranch%
git merge master
echo.
echo script finished successfully
PAUSE
Supplement to Mario Knezovic 's answer:
class IA
{
public:
virtual int getNum() const = 0;
};
class BaseA : public IA
{
public:
inline virtual int getNum() const final {return ...};
};
class ImplA : public BaseA {...};
IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);
//the following line should cause compiler to use the inlined function BaseA::getNum(),
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it
int n = impla->getNum();
The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.
No.
A workaround is to overload with another method that doesn't have out / ref parameters, and which just calls your current method.
public bool SomeMethod(out string input)
{
...
}
// new overload
public bool SomeMethod()
{
string temp;
return SomeMethod(out temp);
}
If you have C# 7.0, you can simplify:
// new overload
public bool SomeMethod()
{
return SomeMethod(out _); // declare out as an inline discard variable
}
(Thanks @Oskar / @Reiner for pointing this out.)
There is one case when you do it, with while
-loops.
When reading files, you usualy do like this:
void readFile(String pathToFile) {
// Create a FileInputStream object
FileInputStream fileIn = null;
try {
// Create the FileInputStream
fileIn = new FileInputStream(pathToFile);
// Create a variable to store the current line's text in
String currentLine;
// While the file has lines left, read the next line,
// store it in the variable and do whatever is in the loop
while((currentLine = in.readLine()) != null) {
// Print out the current line in the console
// (you can do whatever you want with the line. this is just an example)
System.out.println(currentLine);
}
} catch(IOException e) {
// Handle exception
} finally {
try {
// Close the FileInputStream
fileIn.close();
} catch(IOException e) {
// Handle exception
}
}
}
Look at the while
-loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if
-statement, but I guess a while loop can be included in your question as well.
The reason to this is that when using a FileInputStream
, every time you call FileInputStream.readLine()
, it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null
without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null
, and then called it from inside of the loop too, you would only get every second line.
Hope you understand, and good luck!
If you want to delete for example the last 3
commits, run the following command to remove the changes from the file system (working tree) and commit history (index) on your local branch:
git reset --hard HEAD~3
Then run the following command (on your local machine) to force the remote branch to rewrite its history:
git push --force
Congratulations! All DONE!
Some notes:
You can retrieve the desired commit id by running
git log
Then you can replace HEAD~N
with <desired-commit-id>
like this:
git reset --hard <desired-commit-id>
If you want to keep changes on file system and just modify index (commit history), use --soft
flag like git reset --soft HEAD~3
. Then you have chance to check your latest changes and keep or drop all or parts of them. In the latter case runnig git status
shows the files changed since <desired-commit-id>
. If you use --hard
option, git status
will tell you that your local branch is exactly the same as the remote one. If you don't use --hard
nor --soft
, the default mode is used that is --mixed
. In this mode, git help reset
says:
Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated.
You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.
You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.
However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table"
it emits code which actually creates a StringBuilder
behind the scenes and appends to it, so the end result is not that bad afterall.
But of course anyone looking at that code is bound to think that it is kind of retarded.
There are ToUnixTime()
and ToUnixTimeMs()
methods in DateTimeExtensions class
DateTime.UtcNow.ToUnixTimeMs()
var arr = [ 'fdgdfgdfg', 'gdfgf', 'gdfgdfhawsdgd', 'gdf', 'gdfhdfhjurvweadsd' ];
arr.sort(function (a, b) { return b.length - a.length })[0];
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
Use css on your label.
For example:
label {line-height:1em; margin:2px 5px 3px 5px; padding:2px 5px 3px 5px;}
Notice that the line-height will adjust the height of the line itself, whereas margin will dictate how far out other elements will be outside the lable and padding will dictate any inner space from the outside edge of the label. The margin and padding work like this (clockwise: Top Right Bottom Left), so 2px 5px 3px 5px is:
2px Top 5px Right 3px Bottom 5px Left
I would first want to know what you are trying to accomplish here to need an argument to be passed to new Runnable() or to run(). The usual way should be to have a Runnable object which passes data(str) to its threads by setting member variables before starting. The run() method then uses these member variable values to do execute someFunc()
Here's another one in case you don't want to use Collectors.toMap()
Map<String, Choice> result =
choices.stream().collect(HashMap<String, Choice>::new,
(m, c) -> m.put(c.getName(), c),
(m, u) -> {});
You can project into anonymous type, and then from it to model type
public IEnumerable<Product> GetProducts(int categoryID)
{
return (from p in Context.Set<Product>()
where p.CategoryID == categoryID
select new { Name = p.Name }).ToList()
.Select(x => new Product { Name = x.Name });
}
Edit: I am going to be a bit more specific since this question got a lot of attention.
You cannot project into model type directly (EF restriction), so there is no way around this. The only way is to project into anonymous type (1st iteration), and then to model type (2nd iteration).
Please also be aware that when you partially load entities in this manner, they cannot be updated, so they should remain detached, as they are.
I never did completely understand why this is not possible, and the answers on this thread do not give strong reasons against it (mostly speaking about partially loaded data). It is correct that in partially loaded state entity cannot be updated, but then, this entity would be detached, so accidental attempts to save them would not be possible.
Consider method I used above: we still have a partially loaded model entity as a result. This entity is detached.
Consider this (wish-to-exist) possible code:
return (from p in Context.Set<Product>()
where p.CategoryID == categoryID
select new Product { Name = p.Name }).AsNoTracking().ToList();
This could also result in a list of detached entities, so we would not need to make two iterations. A compiler would be smart to see that AsNoTracking() has been used, which will result in detached entities, so it could allow us to do this. If, however, AsNoTracking() was omitted, it could throw the same exception as it is throwing now, to warn us that we need to be specific enough about the result we want.
I think the DocumentCompleted event of the WebBrowser control should get you where you need to go.
I don't know of any JVM that actually checks the JAVA_OPTS
environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java
command-line.
The key thing to understand here is that arguments to java
that come before the -jar analyse.jar
bit will only affect the JVM and won't be passed along to your program. So, modifying the java
line in your script to:
java $JAVA_OPTS -jar analyse.jar $*
Should "just work".
ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it
Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
yum install java-1.8.0
and then:
alternatives --config java
and check:
java -version
PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:
import sip
sip.setapi('QString', 2)
With this API, QtCore.QString
class is no longer available and self.ui.comboBox.currentText()
will return a Python string or unicode object.
See Selecting Incompatible APIs from the doc.
The following should work nicely.
$(function() {
// Way 1
function doosomething()
{
//Doo something
}
// Way 2, equivalent to Way 1
var doosomething = function() {
// Doo something
}
$("div.class").click(doosomething);
$("div.secondclass").click(doosomething);
});
Basically, you are declaring your function in the same scope as your are using it (JavaScript uses Closures to determine scope).
Now, since functions in JavaScript behave like any other object, you can simply assign doosomething
as the function to call on click by using .click(doosomething);
Your function will not execute until you call it using doosomething()
(doosomething
without the ()
refers to the function but doesn't call it) or another function calls in (in this case, the click
handler).
hashMaps
can't have duplicate keys. That said, you can create a map with list values:
Map<Integer, List<String>>
However, using this approach will have performance implications.
Note: Ruby >= 1.9.2 has an order-preserving hash: the order keys are inserted will be the order they are enumerated. The below applies to older versions or to backward-compatible code.
There is no concept of a sorted hash. So no, what you're doing isn't right.
If you want it sorted for display, return a string:
"{" + h.sort.map{|k,v| "#{k.inspect}=>#{v.inspect}"}.join(", ") + "}"
or, if you want the keys in order:
h.keys.sort
or, if you want to access the elements in order:
h.sort.map do |key,value|
# keys will arrive in order to this block, with their associated value.
end
but in summary, it makes no sense to talk about a sorted hash. From the docs, "The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order." So inserting keys in a specific order into the hash won't help.
Sort the unsorted hashmap in ascending order.
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
Or if you are already using pandas, You can do it with json_normalize()
like so:
import pandas as pd
d = {'a': 1,
'c': {'a': 2, 'b': {'x': 5, 'y' : 10}},
'd': [1, 2, 3]}
df = pd.json_normalize(d, sep='_')
print(df.to_dict(orient='records')[0])
Output:
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'c_b_y': 10, 'd': [1, 2, 3]}
Difference between small and little
function getPosition( el ) {
var x = 0;
var y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
x += el.offsetLeft - el.scrollLeft;
y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: y, left: x };
}
Look a example coordinates: http://javascript.info/tutorial/coordinates
Open the XAMMP php.ini file (the default path is C:\xammp\php\php.ini) and change the code (;extension=ldap) to extension=php_ldap.dll and save. Restart XAMMP and save.
php.ini
; Notes for Windows environments :
;
; - Many DLL files are located in the extensions/ (PHP 4) or ext/ (PHP 5+)
; extension folders as well as the separate PECL DLL download (PHP 5+).
; Be sure to appropriately set the extension_dir directive.
;
extension=bz2
extension=curl
extension=fileinfo
extension=gd2
extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=interbase
extension=php_ldap.dll
Smoke Testing
Smoke testing is a wide approach where all areas of the software application are tested without getting into too deep
The test cases for smoke testing of the software can be either manual or automated
Smoke testing is done to ensure whether the main functions of the software application are working or not. During smoke testing of the software, we do not go into finer details.
Smoke testing of the software application is done to check whether the build can be accepted for through software testing
This testing is performed by the developers or testers
Smoke testing exercises the entire system from end to end
Smoke testing is like General Health Check Up
Smoke testing is usually documented or scripted
Santy Testing
Sanity software testing is a narrow regression testing with a focus on one or a small set of areas of functionality of the software application.
Sanity test is generally without test scripts or test cases.
Sanity testing is a cursory software testing type. It is done whenever a quick round of software testing can prove that the software application is functioning according to business / functional requirements.
Sanity testing of the software is to ensure whether the requirements are met or not.
Sanity testing is usually performed by testers
Sanity testing exercises only the particular component of the entire system
Sanity Testing is like specialized health check up
Sanity testing is usually not documented and is unscripted
For more visit Link
Create bitmap from file path:
File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap
function.
I think you are giving the wrong file path. :) Hope this helps.
This is an issue distinct to Chrome, but there are two paths you can take to fix it.
I noticed the error once I added this specific header to my PHP script.
header('Content-Type: application/json');
The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).
Some languages have combining diacritics as language letters and accent diacritics to specify accent.
I think it is more safe to specify explicitly what diactrics you want to strip:
def strip_accents(string, accents=('COMBINING ACUTE ACCENT', 'COMBINING GRAVE ACCENT', 'COMBINING TILDE')):
accents = set(map(unicodedata.lookup, accents))
chars = [c for c in unicodedata.normalize('NFD', string) if c not in accents]
return unicodedata.normalize('NFC', ''.join(chars))
If you are like me and you add old .ASPX files to a more recent project. You are probably going to forget some of the controls used on the page.
If so, first thing, if there are multiple files you are installing; Fix one at a time first.
When you compile, fix errors generated. They will probably be the same errors in all the files.
Next, if you have Designer files, delete all of the inserted - designer files. Next, make sure there are not any other errors when you compile, other than the designer files.
Finally right click your web project and click on Convert to Web Application. This will insert the designer files you need.
These are the absolute best steps to fix the issues.
If you mean any letters in any character encoding, then a good approach might be to delete non-letters like spaces \s
, digits \d
, and other special characters like:
[!@#\$%\^&\*\(\)\[\]:;'",\. ...more special chars... ]
Or use negation of above negation to directly describe any letters:
\S \D and [^ ..special chars..]
Pros:
Cons:
You can try this:
public enum Modes {
some-really-long-string,
mode1,
mode2,
mode3;
public String toString(){
switch(this) {
case some-really-long-string:
return "some-really-long-string";
case mode2:
return "mode2";
default: return "undefined";
}
}
}
In 2018, you can program the "usual" style using async
and await
in Node.js.
Below is an example, that wraps request callback in a promise and then uses await
to get the resolved value.
const request = require('request');
// wrap a request in an promise
function downloadPage(url) {
return new Promise((resolve, reject) => {
request(url, (error, response, body) => {
if (error) reject(error);
if (response.statusCode != 200) {
reject('Invalid status code <' + response.statusCode + '>');
}
resolve(body);
});
});
}
// now to program the "usual" way
// all you need to do is use async functions and await
// for functions returning promises
async function myBackEndLogic() {
try {
const html = await downloadPage('https://microsoft.com')
console.log('SHOULD WORK:');
console.log(html);
// try downloading an invalid url
await downloadPage('http:// .com')
} catch (error) {
console.error('ERROR:');
console.error(error);
}
}
// run your async function
myBackEndLogic();
The important thing about JSON is to keep data transfer encrypted for security reasons. No doubt that JSON is much much faster then XML. I have seen XML take 100ms where as JSON only took 60ms. JSON data is easy to manipulate.
In Xcode 8, all the derived data is automatically cleaned. If you want to do it by hand, go to Locations
tab from the Preferences
, locate project's derived data folder, and delete files related to the project.
In macOS 10.12 and later, Xcode cleans up stale derived data, precompiled headers, and module caches. (23282174)
Credits to @charmingToad
But from what I observed, the same behaviour is typical when using Xcode 8 on OS X 10.11.5/6
For anyone reading this post in the future, you don't need to cd to the directory where the jar is present. Here is what you need to do -
Go to your project folder from where you can run maven commands (When you do an ls -ltr in this folder, you should see pom.xml)
Do this -
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=<Path where the jar is, example downloads>/ojdbc6.jar -DgeneratePom=true
Once this is done, you can add the dependency in your pom.xml, something like this -
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
This should be your answer
<div align="center">
<img src="@Url.Content("~/images/image3.bmp")" alt="" align="right" style="float:right"/>
<img src="@Url.Content("~/images/image1.bmp")" alt="" align="left" style="float:left" />
<div id="content" align="center">
<img src="@Url.Content("~/images/image2.bmp")" alt="" align="center" />
</div>
</div>
$("myDiv").hide();
and $("myDiv").show();
does not work in Internet Explorer that well.
The way I got around this was to get the html content of myDiv
using .html()
.
I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content
to the HiddenField
then read that contents from the newly created div when I wanted to show the DIV.
After I used the .remove()
method to get rid of the DIV that was temporarily holding my DIVs html.
var Content = $('myDiv').html();
$('myDiv').empty();
var hiddenField = $("<input type='hidden' id='myDiv2'>");
$('body').append(hiddenField);
HiddenField.val(Content);
and then when I wanted to SHOW the content again.
var Content = $('myDiv');
Content.html($('#myDiv2').val());
$('#myDiv2').remove();
This was more reliable that the .hide()
& .show()
methods.
seems you need to link with the obj file that implements tolayer5()
Update: your function declaration doesn't match the implementation:
void tolayer5(int AorB, struct msg msgReceived)
void tolayer5(int, char data[])
So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().
Just in case anyone got to a desperate point where nothing works... It happened to us that the content assist somehow shrunk so no suggestion was shown, just the "Press Ctrl+Space for non-Java..." could be seen. So, it was just a matter of dragging the corner of the content assist to enlarge the pop-up.
I know, embarrassing. Hope it helps.
Note: this was an Ubuntu server with Xfce4 using Eclipse Oxygen.
In more current versions of MongoDB, I have 3.2.10, it is stored be default into
/var/lib/mongodb
Windows Solution:
https://sourceforge.net/projects/win32svn/
1.Download it, then add it to system path.
2.Go to work directory execute "svn clean" and "svn update" in cmd.
An easy way to parse (and validate) URL's is the urlparse
(py2, py3) module.
A regex is too much work.
There's no "validate" method because almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.
Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.
For example :::::
is a valid URL. The path is ":::::"
. A pretty stupid filename, but a valid filename.
Also, /////
is a valid URL. The netloc ("hostname") is ""
. The path is "///"
. Again, stupid. Also valid. This URL normalizes to "///"
which is the equivalent.
Something like "bad://///worse/////"
is perfectly valid. Dumb but valid.
Bottom Line. Parse it, and look at the pieces to see if they're displeasing in some way.
Do you want the scheme to always be "http"? Do you want the netloc to always be "www.somename.somedomain"? Do you want the path to look unix-like? Or windows-like? Do you want to remove the query string? Or preserve it?
These are not RFC-specified validations. These are validations unique to your application.
Just add them in one line command 2>> error 1>> output
However, note that >>
is for appending if the file already has data. Whereas, >
will overwrite any existing data in the file.
So, command 2> error 1> output
if you do not want to append.
Just for completion's sake, you can write 1>
as just >
since the default file descriptor is the output. so 1>
and >
is the same thing.
So, command 2> error 1> output
becomes, command 2> error > output
To list all of the packages in the active environment, use:
conda list
To list all of the packages in a deactivated environment, use:
conda list -n myenv
You module and class AthleteList
have the same name. Change:
import AthleteList
to:
from AthleteList import AthleteList
This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList
Here is a simple letter-range implementation:
Code
def letter_range(start, stop="{", step=1):
"""Yield a range of lowercase letters."""
for ord_ in range(ord(start.lower()), ord(stop.lower()), step):
yield chr(ord_)
Demo
list(letter_range("a", "f"))
# ['a', 'b', 'c', 'd', 'e']
list(letter_range("a", "f", step=2))
# ['a', 'c', 'e']
Use any()
.
if any(t < 0 for t in x):
# do something
You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".
For this case, I do something like this:
var obj = {};_x000D_
_x000D_
if(Object.keys(obj).length == 0){_x000D_
console.log("The obj is null")_x000D_
}
_x000D_
To upgrade Ruby with rbenv: Per the rbenv README
brew upgrade rbenv ruby-build
rbenv install -l
rbenv install <selected version>
Perhaps your hosting server and email server are located at same place and you don't need to go for smtp authentication. Just keep every thing default like:
$config = array(
'protocol' => '',
'smtp_host' => '',
'smtp_port' => '',
'smtp_user' => '[email protected]',
'smtp_pass' => '**********'
);
or
$config['protocol'] = '';
$config['smtp_host'] = '';
$config['smtp_port'] = ;
$config['smtp_user'] = '[email protected]';
$config['smtp_pass'] = 'password';
it works for me.
// CMakeLists.txt : release
set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)
// CMakeLists.txt : debug
set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)
I did not find any good solution after google search, just post my solution for other to reference. use priceToString to format money.
public static String priceWithDecimal (Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
return formatter.format(price);
}
public static String priceWithoutDecimal (Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.##");
return formatter.format(price);
}
public static String priceToString(Double price) {
String toShow = priceWithoutDecimal(price);
if (toShow.indexOf(".") > 0) {
return priceWithDecimal(price);
} else {
return priceWithoutDecimal(price);
}
}
According to the jQuery documentation for .keypress(), it does not catch non-printable characters, so backspace will not work on keypress, but it is caught in keydown and keyup:
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser. (https://api.jquery.com/keypress/)
In some instances keyup isn't desired or has other undesirable effects and keydown is sufficient, so one way to handle this is to use keydown
to catch all keystrokes then set a timeout of a short interval so that the key is entered, then do processing in there after.
jQuery(el).keydown( function() {
var that = this; setTimeout( function(){
/** Code that processes backspace, etc. **/
}, 100 );
} );
In the case of Maven project
Try right click on the project then select Maven -> Update Project...
then Ok
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement
With this code you can get the JVM arguments:
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
Concatenate them with the .
operator:
$result = $data1 . " " . $data2;
Or use string interpolation:
$result = "$data1 $data2";
All can be defined as in f:ajax
attiributes.
i.e.
<p:selectOneMenu id="employees" value="#{mymb.employeesList}" required="true">
<f:selectItems value="#{mymb.employeesList}" var="emp" itemLabel="#{emp.employeeName}" />
<f:ajax event="valueChange" listener="#{mymb.handleChange}" execute="@this" render="@all" />
</p:selectOneMenu>
event: it can be normal DOM Events like click
, or valueChange
execute: This is a space separated list of client ids of components that will participate in the "execute" portion of the Request Processing Lifecycle.
render: The clientIds of components that will participate in the "render" portion of the Request Processing Lifecycle. After action done, you can define which components should be refresh. Id, IdList or these keywords can be added: @this
, @form
, @all
, @none
.
You can reache the whole attribute list by following link: http://docs.oracle.com/javaee/6/javaserverfaces/2.1/docs/vdldocs/facelets/f/ajax.html
There are not a lot of clear answers on this because you are always assuming things.
This solution calculates between two dates the months between assuming you want to save the day of month for comparison, (meaning that the day of the month is considered in the calculation)
Example, if you have a date of 30 Jan 2012, 29 Feb 2012 will not be a month but 01 March 2013 will.
It's been tested pretty thoroughly, probably will clean it up later as we use it, but here:
private static int TotalMonthDifference(DateTime dtThis, DateTime dtOther)
{
int intReturn = 0;
bool sameMonth = false;
if (dtOther.Date < dtThis.Date) //used for an error catch in program, returns -1
intReturn--;
int dayOfMonth = dtThis.Day; //captures the month of day for when it adds a month and doesn't have that many days
int daysinMonth = 0; //used to caputre how many days are in the month
while (dtOther.Date > dtThis.Date) //while Other date is still under the other
{
dtThis = dtThis.AddMonths(1); //as we loop, we just keep adding a month for testing
daysinMonth = DateTime.DaysInMonth(dtThis.Year, dtThis.Month); //grabs the days in the current tested month
if (dtThis.Day != dayOfMonth) //Example 30 Jan 2013 will go to 28 Feb when a month is added, so when it goes to march it will be 28th and not 30th
{
if (daysinMonth < dayOfMonth) // uses day in month max if can't set back to day of month
dtThis.AddDays(daysinMonth - dtThis.Day);
else
dtThis.AddDays(dayOfMonth - dtThis.Day);
}
if (((dtOther.Year == dtThis.Year) && (dtOther.Month == dtThis.Month))) //If the loop puts it in the same month and year
{
if (dtOther.Day >= dayOfMonth) //check to see if it is the same day or later to add one to month
intReturn++;
sameMonth = true; //sets this to cancel out of the normal counting of month
}
if ((!sameMonth)&&(dtOther.Date > dtThis.Date))//so as long as it didn't reach the same month (or if i started in the same month, one month ahead, add a month)
intReturn++;
}
return intReturn; //return month
}
My trick is using an attribute selector. Attributes are easier to set up by javascript.
css
.class{ /*normal css... */}
.class[special]:after{ content: 'what you want'}
javascript
function setSpecial(id){ document.getElementById(id).setAttribute('special', '1'); }
html
<element id='x' onclick="setSpecial(this.id)"> ...
If you have a lot of untracked files, and don't want to "gitignore
" all of them, note that, since git 1.8.3 (April, 22d 2013), git status
will mention the --untracked-files=no
even if you didn't add that option in the first place!
"
git status
" suggests users to look into using--untracked=no
option when it takes too long.
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
lets say you have a model called Book and on it a field called 'cover_pic', in that case, you can do the following to compress the image:
from PIL import Image
b = Book.objects.get(title='Into the wild')
image = Image.open(b.cover_pic.path)
image.save(b.image.path,quality=20,optimize=True)
hope it helps to anyone stumbling upon it.
This is mostly covered already, but one addition as I ran into an issue with the previous code samples.
Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))