For traditional extending you can simply write superclass as constructor function, and then apply this constructor for your inherited class.
function AbstractClass() {
this.superclass_method = function(message) {
// do something
};
}
function Child() {
AbstractClass.apply(this);
// Now Child will have superclass_method()
}
Example on angularjs:
http://plnkr.co/edit/eFixlsgF3nJ1LeWUJKsd?p=preview
app.service('noisyThing',
['notify',function(notify){
this._constructor = function() {
this.scream = function(message) {
message = message + " by " + this.get_mouth();
notify(message);
console.log(message);
};
this.get_mouth = function(){
return 'abstract mouth';
}
}
}])
.service('cat',
['noisyThing', function(noisyThing){
noisyThing._constructor.apply(this)
this.meow = function() {
this.scream('meooooow');
}
this.get_mouth = function(){
return 'fluffy mouth';
}
}])
.service('bird',
['noisyThing', function(noisyThing){
noisyThing._constructor.apply(this)
this.twit = function() {
this.scream('fuuuuuuck');
}
}])
I had the same issue in trying to start the server and followed the "checked" solution. But still had the problem. The issue was the my /etc/my.cnf file was not pointing to my designated datadir as defined when I executed the mysql_install_db with --datadir defined. Once I updated this, the server started correctly.
I have a much easier way than the above ones.
DECLARE @FirstId int, @SecondId int
SELECT TOP 1 @FirstId = TableId from MyDataTable ORDER BY TableId
SELECT TOP 1 @SecondId = TableId from MyDataTable WHERE TableId <> @FirstId ORDER BY TableId
SELECT @SecondId
I opened the file in Notepad++ and did a replacement in a few steps:
This puts all the breaks where they should be and removes those that are breaking up the file.
It worked for me.
The following returns the query as valid SQL, based on https://code.djangoproject.com/ticket/17741:
def str_query(qs):
"""
qs.query returns something that isn't valid SQL, this returns the actual
valid SQL that's executed: https://code.djangoproject.com/ticket/17741
"""
cursor = connections[qs.db].cursor()
query, params = qs.query.sql_with_params()
cursor.execute('EXPLAIN ' + query, params)
res = str(cursor.db.ops.last_executed_query(cursor, query, params))
assert res.startswith('EXPLAIN ')
return res[len('EXPLAIN '):]
Java 6, now support TLS 1.2, check out below
http://www.oracle.com/technetwork/java/javase/overview-156328.html#R160_121
In Get:
public IActionResult Create()
{
ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
return View();
}
In Post:
var selectedIds= Request.Form["Tags"];
In View :
<label>Tags</label>
<select asp-for="Tags" id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>
Per default collections in scala are immutable, so you have a + method which returns a new list with the element added to it. If you really need something like an add method you need a mutable collection, e.g. http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html which has a += method.
I had the same issue, but I found a good solution here: Stop caching for PHP 5.5.3 in MAMP
Basically find the php.ini file and comment out the OPCache lines. I hope this alternative answer helps others else out as well.
HTTP_REFERER - sent by the browser, stating the last page the browser viewed!
If you trusting [HTTP_REFERER] for any reason that is important, you should not, since it can be faked easily:
Try this firefox extension, you'll be able to set any headers you want:
@Master of Celebration:
Firefox:
extensions: refspoof, refontrol, modify headers, no-referer
Completely disable: the option is available in about:config under "network.http.sendRefererHeader" and you want to set this to 0 to disable referer passing.
Google chrome / Chromium:
extensions: noref, spoofy, external noreferrer
Completely disable: Chnage ~/.config/google-chrome/Default/Preferences or ~/.config/chromium/Default/Preferences and set this:
{
...
"enable_referrers": false,
...
}
Or simply add --no-referrers to shortcut or in cli:
google-chrome --no-referrers
Opera:
Completely disable: Settings > Preferences > Advanced > Network, and uncheck "Send referrer information"
Spoofing web service:
Standalone filtering proxy (spoof any header):
Spoofing http_referer when using wget
‘--referer=url’
Spoofing http_referer when using curl
-e, --referer
Spoofing http_referer wth telnet
telnet www.yoursite.com 80 (press return)
GET /index.html HTTP/1.0 (press return)
Referer: http://www.hah-hah.com (press return)
(press return again)
When the toastr message poped up on the screen of firefox. the below tag was displayed in fire bug.
<div class="toast-message">Invalid Credentials, Please check Password</div>.
I took the screenshot at that time. And did the below changes in selenium java code.
String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("toast-message")));
WebElement toast1 = driver.findElement(By.className("toast-message"));
alertText = toast1.getText();
System.out.println( alertText);
And my issue of toastr popup got resolved.
with this code, the id will not appear on the link
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Along with the above answers Try this for min and max length:
In Model
[StringLength(13, MinimumLength=10)]
public string MobileNo { get; set; }
In view
<div class="col-md-8">
@Html.TextBoxFor(m => m.MobileNo, new { @class = "form-control" , type="phone"})
@Html.ValidationMessageFor(m => m.MobileNo,"Invalid Number")
@Html.CheckBoxFor(m => m.IsAgreeTerms, new {@checked="checked",style="display:none" })
</div>
There are different methods to open or close winform. Form.Close() is one method in closing a winform.
When 'Form.Close()' execute , all resources created in that form are destroyed. Resources means control and all its child controls (labels , buttons) , forms etc.
Some other methods to close winform
Some methods to Open/Start a form
All of them act differently , Explore them !
I stored a variable at the top to keep track of which info window is currently open, see below.
var currentInfoWin = null;
google.maps.event.addListener(markers[counter], 'click', function() {
if (currentInfoWin !== null) {
currentInfoWin.close(map, this);
}
this.infoWin.open(map, this);
currentInfoWin = this.infoWin;
});
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
You are trying to cast int[] to Integer[], this is not possible.
You can use commons-lang's ArrayUtils to convert the ints to Integers before getting the List from the array:
public int getTheNumber(int[] factors) {
Integer[] integers = ArrayUtils.toObject(factors);
ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(integers));
Collections.sort(f);
return f.get(0)*f.get(f.size()-1);
}
The Python read functions will return an empty string if they reach EOF
You can combine both in the same date function call
date("d-m-Y H:i:s");
I think you're looking for the intersect function
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect()
returns an array containing all values of array1 that are
present in all the arguments. Note that keys are preserved.
Use Apache Common IO's FileUtils
:
import org.apache.commons.io.FileUtils
FileUtils.copyURLToFile(url, f);
The method downloads the content of url
and saves it to f
.
I had a similar problem and the solution was to do this:
#cloud-container{
position:absolute;
top:0;
bottom:0;
}
I wanted a page-centered div with height 100% of page height, so my total solution was:
#cloud-container{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
width: XXXpx; /*otherwise div defaults to page width*/
margin: 0 auto; /*horizontally centers div*/
}
You might need to make a parent element (or simply 'body') have position: relative;
Its hard to give you a good answer, without seeing the html that you are actually using.
Are you outputting a doctype / using standards mode rendering? Without actually being able to look into a html repro, that would be my first guess for a html interpretation difference between firefox and internet explorer.
import java.io.*;
import java.net.*;
public class ConvertURLToFileName{
public static void main(String[] args)throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the URL : ");
String str = in.readLine();
try{
URL url = new URL(str);
System.out.println("File : "+ url.getFile());
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
I hope this will help you.
Here is a very simple class NumberInWords.java that can have the job done very easily:
String numberInWords = NumberInWords.convertNumberToWords(27546); //twenty seven thousand and five hundred forty six
It's important to know that this class is only capable of converting int datatype.
Try it the other way:
var start_date = $("#fit_start_time").val(); //05-09-2013
var end_date = $("#fit_end_time").val(); //10-09-2013
var format='dd-MM-y';
var result= compareDates(start_date,format,end_date,format);
if(result==1)/// end date is less than start date
{
alert('End date should be greater than Start date');
}
OR:
if(new Date(start_date) >= new Date(end_date))
{
alert('End date should be greater than Start date');
}
The simple answer (swift 3):
Calendar.current.component(.weekday, from: Date())
Using Date object guarantees that. For eg if you try to create April 31st
:
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is
0
, Feb. is1
etc.
For Swift-3 and above:
extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = URL(string: urlString) {
let request = URLRequest(url: url)
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: .main, completionHandler: { (response, data, error) in
if let imageData = data as NSData? {
self.image = UIImage(data: imageData as Data)
}
})
}
}
}
If you're using django, you can use urlquote:
>>> from django.utils.http import urlquote
>>> urlquote(u"Müller")
u'M%C3%BCller'
Note that changes to Python since this answer was published mean that this is now a legacy wrapper. From the Django 2.1 source code for django.utils.http:
A legacy compatibility wrapper to Python's urllib.parse.quote() function.
(was used for unicode handling on Python 2)
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
You can make your ImageButton widget as I did. In my case, I needed a widget with a fixed icon size. Let's start from custom attributes:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ImageButtonFixedIconSize">
<attr name="imageButton_icon" format="reference" />
<attr name="imageButton_iconWidth" format="dimension" />
<attr name="imageButton_iconHeight" format="dimension" />
</declare-styleable>
</resources>
Widget class is quite simple (the key point is padding calculations in onLayout method):
class ImageButtonFixedIconSize
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.imageButtonStyle
) : ImageButton(context, attrs, defStyleAttr) {
private lateinit var icon: Drawable
@Px
private var iconWidth: Int = 0
@Px
private var iconHeight: Int = 0
init {
scaleType = ScaleType.FIT_XY
attrs?.let { retrieveAttributes(it) }
}
/**
*
*/
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
val width = right - left
val height = bottom - top
val horizontalPadding = if(width > iconWidth) (width - iconWidth) / 2 else 0
val verticalPadding = if(height > iconHeight) (height - iconHeight) / 2 else 0
setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding)
setImageDrawable(icon)
super.onLayout(changed, left, top, right, bottom)
}
/**
*
*/
private fun retrieveAttributes(attrs: AttributeSet) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageButtonFixedIconSize)
icon = typedArray.getDrawable(R.styleable.ImageButtonFixedIconSize_imageButton_icon)!!
iconWidth = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconWidth, 0f).toInt()
iconHeight = typedArray.getDimension(R.styleable.ImageButtonFixedIconSize_imageButton_iconHeight, 0f).toInt()
typedArray.recycle()
}
}
And at last you should use your widget like this:
<com.syleiman.gingermoney.ui.common.controls.ImageButtonFixedIconSize
android:layout_width="90dp"
android:layout_height="63dp"
app:imageButton_icon="@drawable/ic_backspace"
app:imageButton_iconWidth="20dp"
app:imageButton_iconHeight="15dp"
android:id="@+id/backspaceButton"
tools:ignore="ContentDescription"
/>
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
In Ubuntu18.04, the most easist way to get a core file is inputing the command below to stop the apport service.
sudo service apport stop
Then rerun the application, you will get dump file in current directory.
I also had problems because my program interpreter was /lib/ld-linux.so.2 however it was on an embedded device, so I solved the problem by asking gcc to use ls-uClibc instead as follows:
-Wl,--dynamic-linker=/lib/ld-uClibc.so.0
There is often the tip to use 'echo.'
But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.
You could use echo(
. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.
More about the different ECHO:/\
variants is at DOS tips: ECHO. FAILS to give text or blank line.
One way would be to use a nested query:
SELECT count(*)
FROM (
SELECT COUNT(Genre) AS count
FROM movies
GROUP BY ID
HAVING (count = 4)
) AS x
The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.
File.AppendAllText
does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText
will fail, throwing the exception you see.
I suggest you used str.Write
or str.WriteLine
instead, as you already do elsewhere in your code.
Your file is created but contains nothing because the exception is thrown before str.Flush()
and str.Close()
are called.
In current versions of Mocha, the timeout can be changed globally like this:
mocha.timeout(5000);
Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.
In older versions, and only in a browser, you could change the global configuration using mocha.setup
.
mocha.setup({ timeout: 5000 });
The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.
are you parsing output of ls -l
?
If you are, and you just want to get the file name
find . -iname "*[0-9]"
If you have no choice because usrLog.txt is created by something/someone else and you absolutely must use this file, other options include
awk '/^[-d].*[0-9]$/' file
Ruby(1.9+)
ruby -ne 'print if /^[-d].*[0-9]$/' file
Bash
while read -r line ; do case $line in [-d]*[0-9] ) echo $line; esac; done < file
Use Glide library instead of directly loading into imageview
Glide : https://github.com/bumptech/glide
Glide.with(this).load(Uri.parse(filelocation))).into(img_selectPassportPic);
"Select your text, right click, then choose
Style Token
and then using 1st style (2nd style, etc …). At the moment is not possible to save the style tokens but there is an idea pending on Idea torrent you may vote for if your are interested in that."
It should be default, but it might be hidden.
"It might be that something happened to your
contextMenu.xml
so that you only get the basic standard. Have a look in NPPs config folder (%appdata%\Notepad++\
) if thecontextMenu.xml
is there. If no: that would be the answer; if yes: it might be defect. Anyway you can grab the original standart contextMenu.xml from here and place it into the config folder (or replace the existing xml). Start NPP and you should have quite a long context menu. Tip: have a look at thecontextmenu.xml
itself - because you're allowed to change it to your own needs."
See this for more information
The operators delete
and delete []
are used respectively to destroy the objects created with new
and new[]
, returning to the allocated memory left available to the compiler's memory manager.
Objects created with new
must necessarily be destroyed with delete
, and that the arrays created with new[]
should be deleted with delete[]
.
It sounds like you are doing this on the main UI thread in the app. The UI thread is responsible for pumping windows messages as the arrive, and yet because yours is blocked in database calls it is unable to do so. This can cause problems with system wide messages.
You should look at spawning a background thread for the long running operation and putting up some kind of "I'm busy" dialog for the user while it happens.
FatJar can help you in this case.
In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects
This is useful if your final exported jar includes other external jars.
If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.
After Ganymede, you have:
For Windows 7 users:
Right-click on My Computer, select Properties; Advanced; System Settings; Advanced; Environment Variables. Then find PATH in the second box and set the variable like in the picture below.
Set Clickable as false and change the backgroung color as:
callButton.setClickable(false);
callButton.setBackgroundColor(Color.parseColor("#808080"));
It works great for me
SELECT report_id,computer_id,MAX(date_entered) FROM reports GROUP BY computer_id
I tried many methods including defined here. What I got is,
Make sure the name of repository is valid. The best way is to copy the link from repository site and paste in git bash.
Make sure you have commited the selected files.
git commit -m "Your commit here"
If both steps don't work, try
git push -u -f origin master
If $new_input
may contain more than just a 'name' element you may want to use array_merge
.
$new_input = array('name'=>array(), 'details'=>array());
$new_input['name'] = array('type'=>'text', 'label'=>'First name'...);
$options['inputs'] = array_merge($options['inputs'], $new_input);
If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:
function validate() {
if (document.myForm.name.value == "") {
alert("Enter a name");
document.myForm.name.focus();
return false;
}
if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
alert("Invalid characters");
document.myForm.name.focus();
return false;
}
}
In this function, n can be positive or negative.
def addmonth(d, n):
n += 1
dd = datetime.date(d.year + n/12, d.month + n%12, 1)-datetime.timedelta(1)
return datetime.date(dd.year, dd.month, min(d.day, dd.day))
In addition to all the previous answers, I would like to tell about the different behavior of gather()
and wait()
in case they are cancelled.
If gather()
is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.
If the wait()
task is cancelled, it simply throws an CancelledError
and the waited tasks remain intact.
Simple example:
import asyncio
async def task(arg):
await asyncio.sleep(5)
return arg
async def cancel_waiting_task(work_task, waiting_task):
await asyncio.sleep(2)
waiting_task.cancel()
try:
await waiting_task
print("Waiting done")
except asyncio.CancelledError:
print("Waiting task cancelled")
try:
res = await work_task
print(f"Work result: {res}")
except asyncio.CancelledError:
print("Work task cancelled")
async def main():
work_task = asyncio.create_task(task("done"))
waiting = asyncio.create_task(asyncio.wait({work_task}))
await cancel_waiting_task(work_task, waiting)
work_task = asyncio.create_task(task("done"))
waiting = asyncio.gather(work_task)
await cancel_waiting_task(work_task, waiting)
asyncio.run(main())
Output:
asyncio.wait()
Waiting task cancelled
Work result: done
----------------
asyncio.gather()
Waiting task cancelled
Work task cancelled
Sometimes it becomes necessary to combine wait()
and gather()
functionality. For example, we want to wait for the completion of at least one task and cancel the rest pending tasks after that, and if the waiting
itself was canceled, then also cancel all pending tasks.
As real examples, let's say we have a disconnect event and a work task. And we want to wait for the results of the work task, but if the connection was lost, then cancel it. Or we will make several parallel requests, but upon completion of at least one response, cancel all others.
It could be done this way:
import asyncio
from typing import Optional, Tuple, Set
async def wait_any(
tasks: Set[asyncio.Future], *, timeout: Optional[int] = None,
) -> Tuple[Set[asyncio.Future], Set[asyncio.Future]]:
tasks_to_cancel: Set[asyncio.Future] = set()
try:
done, tasks_to_cancel = await asyncio.wait(
tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED
)
return done, tasks_to_cancel
except asyncio.CancelledError:
tasks_to_cancel = tasks
raise
finally:
for task in tasks_to_cancel:
task.cancel()
async def task():
await asyncio.sleep(5)
async def cancel_waiting_task(work_task, waiting_task):
await asyncio.sleep(2)
waiting_task.cancel()
try:
await waiting_task
print("Waiting done")
except asyncio.CancelledError:
print("Waiting task cancelled")
try:
res = await work_task
print(f"Work result: {res}")
except asyncio.CancelledError:
print("Work task cancelled")
async def check_tasks(waiting_task, working_task, waiting_conn_lost_task):
try:
await waiting_task
print("waiting is done")
except asyncio.CancelledError:
print("waiting is cancelled")
try:
await waiting_conn_lost_task
print("connection is lost")
except asyncio.CancelledError:
print("waiting connection lost is cancelled")
try:
await working_task
print("work is done")
except asyncio.CancelledError:
print("work is cancelled")
async def work_done_case():
working_task = asyncio.create_task(task())
connection_lost_event = asyncio.Event()
waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
async def conn_lost_case():
working_task = asyncio.create_task(task())
connection_lost_event = asyncio.Event()
waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
await asyncio.sleep(2)
connection_lost_event.set() # <---
await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
async def cancel_waiting_case():
working_task = asyncio.create_task(task())
connection_lost_event = asyncio.Event()
waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
await asyncio.sleep(2)
waiting_task.cancel() # <---
await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
async def main():
print("Work done")
print("-------------------")
await work_done_case()
print("\nConnection lost")
print("-------------------")
await conn_lost_case()
print("\nCancel waiting")
print("-------------------")
await cancel_waiting_case()
asyncio.run(main())
Output:
Work done
-------------------
waiting is done
waiting connection lost is cancelled
work is done
Connection lost
-------------------
waiting is done
connection is lost
work is cancelled
Cancel waiting
-------------------
waiting is cancelled
waiting connection lost is cancelled
work is cancelled
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
I've faced same problem and came across to this thread but my problem was with upstream
. Below git command worked for me.
git checkout {remoteName}/{branch} -- {../path/file.js}
git checkout upstream/develop -- public/js/index.js
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Of course, it's then up to you to do what you need to do on the client side.
I would be thinking something like this:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
Make sure the scp command is available on both sides - both on the client and on the server.
BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found
or something similar even though though you have it all configured locally.
Extending on what @vabhatia said, this is what you want in native JavaScript (without JQuery).
ParentNode.insertBefore(<your element>, ParentNode.firstChild);
Taking the knowledge from all the previous answers combined,
this is what I came up with as a solution:
function toFixedWithoutRounding(num, fractionDigits) {
if ((num > 0 && num < 0.000001) || (num < 0 && num > -0.000001)) {
// HACK: below this js starts to turn numbers into exponential form like 1e-7.
// This gives wrong results so we are just changing the original number to 0 here
// as we don't need such small numbers anyway.
num = 0;
}
const re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fractionDigits || -1) + '})?');
return Number(num.toString().match(re)[0]).toFixed(fractionDigits);
}
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
On Windows 10 this worked for me for VIM and VI using git bash
"Esc" + ":wq!"
or
"Esc" + ":q!"
This is an implementation of aforementioned StanLe's anwer, also fixing the case where his answer would produce no curve when using densities.
This replaces the existing but hidden hist.default()
function, to only add the normalcurve
parameter (which defaults to TRUE
).
The first three lines are to support roxygen2 for package building.
#' @noRd
#' @exportMethod hist.default
#' @export
hist.default <- function(x,
breaks = "Sturges",
freq = NULL,
include.lowest = TRUE,
normalcurve = TRUE,
right = TRUE,
density = NULL,
angle = 45,
col = NULL,
border = NULL,
main = paste("Histogram of", xname),
ylim = NULL,
xlab = xname,
ylab = NULL,
axes = TRUE,
plot = TRUE,
labels = FALSE,
warn.unused = TRUE,
...) {
# https://stackoverflow.com/a/20078645/4575331
xname <- paste(deparse(substitute(x), 500), collapse = "\n")
suppressWarnings(
h <- graphics::hist.default(
x = x,
breaks = breaks,
freq = freq,
include.lowest = include.lowest,
right = right,
density = density,
angle = angle,
col = col,
border = border,
main = main,
ylim = ylim,
xlab = xlab,
ylab = ylab,
axes = axes,
plot = plot,
labels = labels,
warn.unused = warn.unused,
...
)
)
if (normalcurve == TRUE & plot == TRUE) {
x <- x[!is.na(x)]
xfit <- seq(min(x), max(x), length = 40)
yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
yfit <- yfit * diff(h$mids[1:2]) * length(x)
}
lines(xfit, yfit, col = "black", lwd = 2)
}
if (plot == TRUE) {
invisible(h)
} else {
h
}
}
Quick example:
hist(g)
For dates it's bit different. For reference:
#' @noRd
#' @exportMethod hist.Date
#' @export
hist.Date <- function(x,
breaks = "months",
format = "%b",
normalcurve = TRUE,
xlab = xname,
plot = TRUE,
freq = NULL,
density = NULL,
start.on.monday = TRUE,
right = TRUE,
...) {
# https://stackoverflow.com/a/20078645/4575331
xname <- paste(deparse(substitute(x), 500), collapse = "\n")
suppressWarnings(
h <- graphics:::hist.Date(
x = x,
breaks = breaks,
format = format,
freq = freq,
density = density,
start.on.monday = start.on.monday,
right = right,
xlab = xlab,
plot = plot,
...
)
)
if (normalcurve == TRUE & plot == TRUE) {
x <- x[!is.na(x)]
xfit <- seq(min(x), max(x), length = 40)
yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
yfit <- as.double(yfit) * diff(h$mids[1:2]) * length(x)
}
lines(xfit, yfit, col = "black", lwd = 2)
}
if (plot == TRUE) {
invisible(h)
} else {
h
}
}
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
try your task using IN condition or OR condition and also this query is working on spark-1.6.x
SELECT patient, patient_id FROM `patient` WHERE patient IN ('User4', 'User3');
or
SELECT patient, patient_id FROM `patient` WHERE patient = 'User1' OR patient = 'User2';
Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.
this.Include(includes, () =>
{
_context.Cars.Include(<parameters>);
});
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .
https://github.com/scastillo/siesta
However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..
I had the same issue and I needed an algorithm using a config file. In This way you can use multiple fields define by a configuration file (simulate just by a List<String) config)
public static void test() {
// Associate your configName with your Comparator
Map<String, Comparator<DocumentDto>> map = new HashMap<>();
map.put("id", new IdSort());
map.put("createUser", new DocumentUserSort());
map.put("documentType", new DocumentTypeSort());
/**
In your config.yml file, you'll have something like
sortlist:
- documentType
- createUser
- id
*/
List<String> config = new ArrayList<>();
config.add("documentType");
config.add("createUser");
config.add("id");
List<Comparator<DocumentDto>> sorts = new ArrayList<>();
for (String comparator : config) {
sorts.add(map.get(comparator));
}
// Begin creation of the list
DocumentDto d1 = new DocumentDto();
d1.setDocumentType(new DocumentTypeDto());
d1.getDocumentType().setCode("A");
d1.setId(1);
d1.setCreateUser("Djory");
DocumentDto d2 = new DocumentDto();
d2.setDocumentType(new DocumentTypeDto());
d2.getDocumentType().setCode("A");
d2.setId(2);
d2.setCreateUser("Alex");
DocumentDto d3 = new DocumentDto();
d3.setDocumentType(new DocumentTypeDto());
d3.getDocumentType().setCode("A");
d3.setId(3);
d3.setCreateUser("Djory");
DocumentDto d4 = new DocumentDto();
d4.setDocumentType(new DocumentTypeDto());
d4.getDocumentType().setCode("A");
d4.setId(4);
d4.setCreateUser("Alex");
DocumentDto d5 = new DocumentDto();
d5.setDocumentType(new DocumentTypeDto());
d5.getDocumentType().setCode("D");
d5.setId(5);
d5.setCreateUser("Djory");
DocumentDto d6 = new DocumentDto();
d6.setDocumentType(new DocumentTypeDto());
d6.getDocumentType().setCode("B");
d6.setId(6);
d6.setCreateUser("Alex");
DocumentDto d7 = new DocumentDto();
d7.setDocumentType(new DocumentTypeDto());
d7.getDocumentType().setCode("B");
d7.setId(7);
d7.setCreateUser("Alex");
List<DocumentDto> documents = new ArrayList<>();
documents.add(d1);
documents.add(d2);
documents.add(d3);
documents.add(d4);
documents.add(d5);
documents.add(d6);
documents.add(d7);
// End creation of the list
// The Sort
Stream<DocumentDto> docStream = documents.stream();
// we need to reverse this list in order to sort by documentType first because stream are pull-based, last sorted() will have the priority
Collections.reverse(sorts);
for(Comparator<DocumentDto> entitySort : sorts){
docStream = docStream.sorted(entitySort);
}
documents = docStream.collect(Collectors.toList());
// documents has been sorted has you configured
// in case of equality second sort will be used.
System.out.println(documents);
}
Comparator objects are really simple.
public class IdSort implements Comparator<DocumentDto> {
@Override
public int compare(DocumentDto o1, DocumentDto o2) {
return o1.getId().compareTo(o2.getId());
}
}
public class DocumentUserSort implements Comparator<DocumentDto> {
@Override
public int compare(DocumentDto o1, DocumentDto o2) {
return o1.getCreateUser().compareTo(o2.getCreateUser());
}
}
public class DocumentTypeSort implements Comparator<DocumentDto> {
@Override
public int compare(DocumentDto o1, DocumentDto o2) {
return o1.getDocumentType().getCode().compareTo(o2.getDocumentType().getCode());
}
}
Conclusion : this method isn't has efficient but you can create generic sort using a file configuration in this way.
Check if the scrollable element is already scrolled to the top when trying to scroll up or to the bottom when trying to scroll down and then preventing the default action to stop the entire page from moving.
var touchStartEvent;
$('.scrollable').on({
touchstart: function(e) {
touchStartEvent = e;
},
touchmove: function(e) {
if ((e.originalEvent.pageY > touchStartEvent.originalEvent.pageY && this.scrollTop == 0) ||
(e.originalEvent.pageY < touchStartEvent.originalEvent.pageY && this.scrollTop + this.offsetHeight >= this.scrollHeight))
e.preventDefault();
}
});
For basic searching:
Some variables you might want to set:
The preprocessor inserts the contents of the files A.h
and B.h
exactly where the include
statement occurs (this is really just copy/paste). When the compiler then parses A.cpp
, it finds the declaration of class A
before it knows about class B
. This causes the error you see. There are two ways to solve this:
B.h
in A.h
. It is generally a good idea to include header files in the files where they are needed. If you rely on indirect inclusion though another header, or a special order of includes in the compilation unit (cpp-file), this will only confuse you and others as the project gets bigger.If you use member variable of type B
in class A
, the compiler needs to know the exact and complete declaration of B
, because it needs to create the memory-layout for A
. If, on the other hand, you were using a pointer or reference to B
, then a forward declaration would suffice, because the memory the compiler needs to reserve for a pointer or reference is independent of the class definition. This would look like this:
class B; // forward declaration
class A {
public:
A(int id);
private:
int _id;
B & _b;
};
This is very useful to avoid circular dependencies among headers.
I hope this helps.
This is my solution in java 8:
public static Boolean isValidCity(String cityCode) {
return Arrays.stream(CITY_ENUM.values())
.map(CITY_ENUM::getCityCode)
.anyMatch(cityCode::equals);
}
I'm using macOS/Linux, the solution that works for me is
npx nodemon index.js
I have tried every possibility, like uninstalling and installing nodemon, installing nodemon globally. restart the terminal, but it won't work.
don't try such things to waste your time.
public static LinkedList reverseLinkedList(LinkedList node) {
if (node == null || node.getNext() == null) {
return node;
}
LinkedList remaining = reverseLinkedList(node.getNext());
node.getNext().setNext(node);
node.setNext(null);
return remaining;
}
The problem lays here:
--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example
union all
--This result set has 1 columns
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id
In order to use union
or union all
number of columns and their types should be identical cross all result sets.
I guess you should just add the column LOC_deelVan_LOC_id
to your second result set
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
.
It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test
.
If you use ((
…))
, you are testing arithmetic equality with ==
as in C:
$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1
(Note: 0
means true
in the Unix sense and a failed test results in a non-zero number.)
Using -eq
inside of double parentheses is a syntax error.
If you are using [
…]
(or single brackets) or [[
…]]
(or double brackets), or test
you can use one of -eq
, -ne
, -lt
, -le
, -gt
, or -ge
as an arithmetic comparison.
$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0
The ==
inside of single or double brackets (or the test
command) is one of the string comparison operators:
$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1
As a string operator, =
is equivalent to ==
. Also, note the whitespace around =
or ==
: it’s required.
While you can do [[ 1 == 1 ]]
or [[ $(( 1+1 )) == 2 ]]
it is testing the string equality — not the arithmetic equality.
So -eq
produces the result probably expected that the integer value of 1+1
is equal to 2
even though the right-hand side is a string and has a trailing space:
$ [[ $(( 1+1 )) -eq "2 " ]]; echo $?
0
While a string comparison of the same picks up the trailing space and therefore the string comparison fails:
$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1
And a mistaken string comparison can produce a completely wrong answer. 10
is lexicographically less than 2
, so a string comparison returns true
or 0
. So many are bitten by this bug:
$ [[ 10 < 2 ]]; echo $?
0
The correct test for 10
being arithmetically less than 2
is this:
$ [[ 10 -lt 2 ]]; echo $?
1
In comments, there is a question about the technical reason why using the integer -eq
on strings returns true for strings that are not the same:
$ [[ "yes" -eq "no" ]]; echo $?
0
The reason is that Bash is untyped. The -eq
causes the strings to be interpreted as integers if possible including base conversion:
$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0
And 0
if Bash thinks it is just a string:
$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1
So [[ "yes" -eq "no" ]]
is equivalent to [[ 0 -eq 0 ]]
Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]]
and ((...))
or ==
.
to get the immediate next sibling ,use this
event.source._elementRef.nativeElement.nextElementSibling
I've seen this happen in a piece of code where the often recurring check for null values was performed:
if(( A==null ) && ( B==null )
return +1;//WRONG: two null values should return 0!!!
Here is a different approach using mix-blend-mode: difference
, that will actually invert whatever the background is, not just a single colour:
div {_x000D_
background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
color: white;_x000D_
mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
A string can be checked with the below function:
function either_String_existor_not($str, $character) {
if (strpos($str, $character) !== false) {
return true;
}
return false;
}
Another option is to run the package in 32 bit mode. Click on the solution => properties =? Debugging => Set run in 64 bit to false.
This is how it works fine to me:
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
ContentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Controller/action',
data: { "things": things },
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
error: function (response) {
$('#result').html(response);
}
});
With "ContentType" in capital "C".
Spring annotations will work fine if you remove enctype="multipart/form-data"
.
@RequestParam(value="txtEmail", required=false)
You can even get the parameters from the request
object .
request.getParameter(paramName);
Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.
Configure the Multi-part resolver if you want to receive enctype="multipart/form-data"
.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
Refer the Spring documentation.
From a Microsoft's script:
DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'
IF (EXISTS (SELECT name
FROM master.dbo.sysdatabases
WHERE ('[' + name + ']' = @dbname
OR name = @dbname)))
-- code mine :)
PRINT 'db exists'
Do not do this object.hasOwnProperty(key))
. It's really bad because these methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false }
- or, the object may be a null object (Object.create(null))
.
The best way is to do Object.prototype.hasOwnProperty.call(object, key)
or:
const has = Object.prototype.hasOwnProperty; // Cache the lookup once, in module scope.
/* Or */
import has from 'has'; // https://www.npmjs.com/package/has
// ...
console.log(has.call(object, key));
try the below code, it will help you get the GET parameters from url . for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
A little modification to typescript:
public encodeData(data: any): string {
return Object.keys(data).map((key) => {
return [key, data[key]].map(encodeURIComponent).join("=");
}).join("&");
}
You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
var list = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}
];
var findProp = p => {
var index = -1;
$.each(list, (i, o) => {
if(o.prop2 == p) {
index = i;
return false; // break
}
});
return index; // -1 == not found, else == index
}
I had the same issue on submission process and solved by Selecting Appstore provision instead of AdHoc. Simple!!
Hope this helps. All the best :)
If you want to ignore seconds for example you can use
func isDate(Date, equalTo: Date, toUnitGranularity: NSCalendar.Unit) -> Bool
Example compare if it's the same day:
Calendar.current.isDate(date1, equalTo: date2, toGranularity: .day)
If you're using the PageFactory pattern or already have a reference to your WebElement, then you probably want to set the attribute, using your existing reference to the WebElement. (Rather than doing a document.getElementById(...)
in your javascript)
The following sample allows you to set the attribute, using your existing WebElement reference.
Code Snippet
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
public class QuickTest {
RemoteWebDriver driver;
@FindBy(id = "foo")
private WebElement username;
public void exampleUsage(RemoteWebDriver driver) {
setAttribute(username, "attr", "10");
setAttribute(username, "value", "bar");
}
public void setAttribute(WebElement element, String attName, String attValue) {
driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
element, attName, attValue);
}
}
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
I had the same problem, and using this solved it.
var w = window.innerWidth;
var h = window.innerHeight;
ogdate
is itself a string, why are you trying to access it's value
property that it doesn't have ?
console.log(og_date.split('-'));
Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
SELECT * FROM table
group by `Group`
ORDER BY COUNT(Group)
People use npm on production to do wicked cool stuff, Node.js is an example of this, so you don't want all your dev tools being run.
If you are using gulp (or similar) to create build files to put on your server then it doesn't really matter.
In the html form, you need to supply additional viewstate variable and disable ViewState in a server page. This requires some control on both sides , though.
Form HTML:
<html><body> <form id='postForm' action='WebForm.aspx' method='POST'>
<input type='text' name='postData' value='base-64-encoded-value' />
<input type='hidden' name='__VIEWSTATE' value='' /> <!-- still need __VIEWSTATE, even empty one -->
</form>
</body></html>
Note empty __VIEWSTATE.
WebForm.aspx:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm.aspx.cs" Inherits="WebForm"
EnableEventValidation="False" EnableViewState="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="postForm" runat="server">
<asp:TextBox ID="postData" runat="server"></asp:TextBox>
<div>
</div>
</form>
</body>
</html>
Note EnableEventValidation="False", EnableViewState="false"
to prevent validation error for empty view state.
Code Behind/Inherits values are not precise.
WebForm.cs:
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string value = Encoding.Unicode.GetString(Convert.FromBase64String(this.postData.Text));
}
}
I'd install Tortoise Hg (a free GUI for Mercurial) and use that. You can then just right-click on a revision you might want to return to - with all the commit messages there in front of your eyes - and 'Revert all files'. Makes it intuitive and easy to roll backwards and forwards between versions of a fileset, which can be really useful if you are looking to establish when a problem first appeared.
Assuming you want to use numpy
, you can numerically compute the derivative of a function at any point using the Rigorous definition:
def d_fun(x):
h = 1e-5 #in theory h is an infinitesimal
return (fun(x+h)-fun(x))/h
You can also use the Symmetric derivative for better results:
def d_fun(x):
h = 1e-5
return (fun(x+h)-fun(x-h))/(2*h)
Using your example, the full code should look something like:
def fun(x):
return x**2 + 1
def d_fun(x):
h = 1e-5
return (fun(x+h)-fun(x-h))/(2*h)
Now, you can numerically find the derivative at x=5
:
In [1]: d_fun(5)
Out[1]: 9.999999999621423
I accomplished this by calling/overriding viewWillDisappear
and then accessing the stack of the navigationController
like this:
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
let stack = self.navigationController?.viewControllers.count
if stack >= 2 {
// for whatever reason, the last item on the stack is the TaskBuilderViewController (not self), so we only use -1 to access it
if let lastitem = self.navigationController?.viewControllers[stack! - 1] as? theViewControllerYoureTryingToAccess {
// hand over the data via public property or call a public method of theViewControllerYoureTryingToAccess, like
lastitem.emptyArray()
lastitem.value = 5
}
}
}
I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:
ProjectNamespace.Properties.Resources.file
Use the IDE's resource manager to add resources.
Tomcat can tell you in several ways. Here's the easiest:
$ /path/to/catalina.sh version
Using CATALINA_BASE: /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME: /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME: /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH: /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built: Jul 3 2012 11:31:52
Server number: 7.0.29.0
OS Name: Mac OS X
OS Version: 10.7.4
Architecture: x86_64
JVM Version: 1.6.0_33-b03-424-11M3720
JVM Vendor: Apple Inc.
If you don't know where catalina.sh
is (or it never gets called), you can usually find it via ps
:
$ ps aux | grep catalina
chris 930 0.0 3.1 2987336 258328 s000 S Wed01PM 2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start
From the ps
output, you can see both catalina.home
and catalina.base
. catalina.home
is where the Tomcat base files are installed, and catalina.base
is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.
You can also interrogate the JVM directly if you can't find it in a ps
listing:
$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29
If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home
and catalina.base
.
Sorry, afaik, you cannot do that. To update attributes in two different tables, you will need to execute two separate statements. But they can be in a batch ( a set of SQL sent to the server in one round trip)
For me shutil.copy is the best:
import shutil
#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)
You can change the path of the files as you want.
change drop down to start file your project
just to save my own deductions from all this is (for saving DBMS_OUTPUT output on the client, using sqlplus):
After lots of toil and fiddling with the Uri class, and other solutions, here're my string extension methods to solve my problems.
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
public static class StringExtensions
{
public static string AddToQueryString(this string url, params object[] keysAndValues)
{
return UpdateQueryString(url, q =>
{
for (var i = 0; i < keysAndValues.Length; i += 2)
{
q.Set(keysAndValues[i].ToString(), keysAndValues[i + 1].ToString());
}
});
}
public static string RemoveFromQueryString(this string url, params string[] keys)
{
return UpdateQueryString(url, q =>
{
foreach (var key in keys)
{
q.Remove(key);
}
});
}
public static string UpdateQueryString(string url, Action<NameValueCollection> func)
{
var urlWithoutQueryString = url.Contains('?') ? url.Substring(0, url.IndexOf('?')) : url;
var queryString = url.Contains('?') ? url.Substring(url.IndexOf('?')) : null;
var query = HttpUtility.ParseQueryString(queryString ?? string.Empty);
func(query);
return urlWithoutQueryString + (query.Count > 0 ? "?" : string.Empty) + query;
}
}
Here's a short PowerShell script to do what you probably expect:
$sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
$targetNugetExe = "$rootPath\nuget.exe"
Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe
Set-Alias nuget $targetNugetExe -Scope Global -Verbose
Note that Invoke-WebRequest
cmdlet arrived with PowerShell v3.0. This article gives the idea.
You can create .war file back from your existing folder.
Using this command
cd /to/your/folder/location
jar -cvf my_web_app.war *
You need to tell MySQL which database to use:
USE database_name;
before you create a table.
In case the database does not exist, you need to create it as:
CREATE DATABASE database_name;
followed by:
USE database_name;
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
break
else:
...block1...
Break
will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).
The magic you have been looking for has been added in Rails 6
Now you can upsert (update or insert).
For single record use:
Model.upsert(column_name: value)
For multiple records use upsert_all :
Model.upsert_all(column_name: value, unique_by: :column_name)
Note:
<?php
$j=1;
array_reverse($skills_nav);
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).
FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.
(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:
GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \
git clone myuser@myGitRemoteServer:/my/remote/git_repo/path
This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).
Simply add class="img-responsive" to the video tag. I'm doing this on a current project, and it works. It doesn't need to be wrapped in anything.
<video class="img-responsive" src="file.mp4" autoplay loop/>
The problem here is that the length of your array is undefined, and this confuses VBA if the array is explicitly defined as a string. Variants, however, seem to be able to resize as needed (because they hog a bunch of memory, and people generally avoid them for a bunch of reasons).
The following code works just fine, but it's a bit manual compared to some of the other languages out there:
Dim SomeArray(3) As String
SomeArray(0) = "Zero"
SomeArray(1) = "One"
SomeArray(2) = "Two"
SomeArray(3) = "Three"
I saw an article yesterday that mentions an Object.__noSuchMethod__
property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?
Ok, i had a few problems because i was inside a
$('.my-dropdown').live('click', function(){
});
I had multiples inside my page that's why i used a class.
My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)
so...
I had to do:
$('.my-dropdown').live('click', function(){
total_tems = $(this).find('option').length;
});
What is this for and why would I use @":\" instead of ":\"?
Because when you have a long string with many \
you don't need to escape them all and the \n
, \r
and \f
won't work too.
Try this:
string searchValue = textBox3.Text;
int rowIndex = -1;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["peseneli"].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
first, you need to load URL helper like this type or you can upload within autoload.php file:
$this->load->helper('url');
if (!$user_logged_in)
{
redirect('/account/login', 'refresh');
}
If you're not set on rolling your own solution, check out this jQuery plugin:
malsup.com/jquery/form/
It will do that and more for you. It's highly recommended.
This question is tagged python-2.x
so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.
It's now necessary to decode urlopen
's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:
import csv, urllib.request
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)
for row in cr:
print(row)
Note the extra line beginning with lines =
, the fact that urlopen
is now in the urllib.request
module, and print
of course requires parentheses.
It's hardly advertised, but yes, csv.reader
can read from a list of strings.
And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:
python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'
(Yes, it's three lines, but you can copy-paste it as one command. ;)
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
I had to use [\\]
or [/]
to be able to make this work, FYI.
awk '!/[\\]/' file > temp && mv temp file
and
awk '!/[/]/' file > temp && mv temp file
I was using awk to remove backlashes and forward slashes from a list.
Remember that with the binding redirection
oldVersion="0.0.0.0-6.0.0.0"
You are saying that the old versions of the dll are between version 0.0.0.0 and version 6.0.0.0.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
Simple solution
setcookie("NAME", "VALUE", time()+3600, '/', EXAMPLE.COM);
Setcookie's 5th parameter determines the (sub)domains that the cookie is available to. Setting it to (EXAMPLE.COM) makes it available to any subdomain (eg: SUBDOMAIN.EXAMPLE.COM )
a = 1400
a1 = 5
a2 = 3
b= str(a/a1)
b1 = str(a/a2)
c =b[(len(b)-2):len(b)]
c1 =b[(len(b1)-2):len(b1)]
if c == ".0":
print("yeah for 5!")
if c1 == ".0":
print("yeah for 3!")
send requtest and get response with kibana,kibana is can autocomplete elastic query builder and have more tools
GET /_cat/indices
kibana dev tools
http://localhost:5601/app/kibana#/dev_tools/console
"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.
use for loop if you have to stop the loop execution based on some condition and remain in to the same function.
Performance is based on the amount of data you are executing on...
If it is less data around 20k. JOIN works better.
If the data is more like 100k+ then IN works better.
If you do not need the data from the other table, IN is good, But it is alwys better to go for EXISTS.
All these criterias I tested and the tables have proper indexes.
If you have password for your dB then
mysql -u <username> -p <DBName> < yourfile.sql
It mostly depends on the (other) activity in the database. Operations like this effectively freeze the entire database for other sessions. Another consideration is the datamodel and the presence of constraints,triggers, etc.
My first approach is always: create a (temp) table with a structure similar to the target table (create table tmp AS select * from target where 1=0), and start by reading the file into the temp table. Then I check what can be checked: duplicates, keys that already exist in the target, etc.
Then I just do a "do insert into target select * from tmp" or similar.
If this fails, or takes too long, I abort it and consider other methods (temporarily dropping indexes/constraints, etc)
Try this sed
version:
ls -l | sed '2 ! d'
It says "delete all the lines that aren't the second one".
I'm not a regex guru by any means. But try:
<[A-Z0-9][A-Z0-9]+>
< start of word
[A-Z0-9] one character
[A-Z0-9]+ and one or more of them
> end of word
I won't try for the bonus points of the whole upper case sentence. hehe
running brew update
and then brew install postgresql
worked for me, I was able to run the pg
gem file no problem after that.
I think it's from gradle-wrapper.properties
file :
make distribution url distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
and do not upgarde to : distributionUrl=https\://services.gradle.org/distributions/gradle-4 ....
The easiest way would probably be to put your web resources into the assets folder then call:
webView.loadUrl("file:///android_asset/filename.html");
For Complete Communication between Java and Webview See This
Update: The assets folder is usually the following folder:
<project>/src/main/assets
This can be changed in the asset folder configuration setting in your <app>.iml
file as:
<option name=”ASSETS_FOLDER_RELATIVE_PATH” value=”/src/main/assets” />
See Article Where to place the assets folder in Android Studio
This whole answer is in the context of spec compliance, not what any engine does at a particular moment or historically.
The actual question is very vague.
will the properties be in the same order that I added them
In what context?
The answer is: it depends on a number of factors. In general, no.
Here is where you can count on property key order for plain Objects
:
Object.getOwnPropertyNames()
, Reflect.ownKeys()
, Object.getOwnPropertySymbols(O)
In all cases these methods include non-enumerable property keys and order keys as specified by [[OwnPropertyKeys]]
(see below). They differ in the type of key values they include (String
and / or Symbol
). In this context String
includes integer values.
Object.getOwnPropertyNames(O)
Returns O
's own String
-keyed properties (property names).
Reflect.ownKeys(O)
Returns O
's own String
- and Symbol
-keyed properties.
Object.getOwnPropertySymbols(O)
Returns O
's own Symbol
-keyed properties.
[[OwnPropertyKeys]]
The order is essentially: integer-like Strings
in ascending order, non-integer-like Strings
in creation order, Symbols in creation order. Depending which function invokes this, some of these types may not be included.
The specific language is that keys are returned in the following order:
... each own property key
P
ofO
[the object being iterated] that is an integer index, in ascending numeric index order... each own property key
P
ofO
that is a String but is not an integer index, in property creation order... each own property key
P
ofO
that is a Symbol, in property creation order
Map
If you're interested in ordered maps you should consider using the Map
type introduced in ES2015 instead of plain Objects
.
If you're using setup.cfg
files, add this before the install_require
part:
setup_requires =
wheel
Example of setup.cfg project :
# setup.py
from setuptools import setup
setup()
# setup.cfg
[metadata]
name = name
version = 0.0.1
description = desc
long_description = file: README.md
long_description_content_type = text/markdown
url = url
author = author
classifiers =
Programming Language :: Python
Programming Language :: Python :: 3
[options]
include_package_data = true
packages = find:
setup_requires =
wheel
install_requires =
packages
packages
packages
Just follows these steps:
Now, you can Start HAXM installation without any error.
If the schema of id is not of type ObjectId you cannot operate with function : findbyId()
Use $('textarea').val('')
.
The problem with using
$('textarea').text('')
, or
$('textarea').html('')
for that matter is that it will only erase what was in the original DOM sent by the server. If a user clears it and then enters new input, the clear button will no longer work. Using .val('')
handles the user input case properly.
If you're using anaconda distribution of Python,
$ conda list | grep tensorflow
tensorflow 1.0.0 py35_0 conda-forge
To check it using Jupyter Notebook (IPython Notebook)
In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'
I found this plugin to be doing what I was expecting: gulp-using
Simple usage example: Search all files in project with .jsx extension
gulp.task('reactify', function(){
gulp.src(['../**/*.jsx'])
.pipe(using({}));
....
});
Output:
[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx
I'd recommend Replace in lieu of Substring to avoid string length issues:
REPLACE(CONVERT(varchar(20), (CAST(SUM(table.value) AS money)), 1), '.00', '')
You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:
In [27]:
df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
a b s1 s2
0 1 3 5 6
1 2 4 5 6
EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:
df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)
This assumes that the indices match the length.
#!/bin/bash
read -p "Enter a directory: " BASEPATH
SUBFOLD1=${BASEPATH%%/}/subFold1
SUBFOLD2=${BASEPATH%%/}/subFold2
echo "I will create $SUBFOLD1 and $SUBFOLD2"
# mkdir -p $SUBFOLD1
# mkdir -p $SUBFOLD2
And if you want to use readline so you get completion and all that, add a -e
to the call to read
:
read -e -p "Enter a directory: " BASEPATH
The most efficient selector you can use is an attribute selector.
input[name="btnPage"]:hover {/*your css here*/}
Here's a live demo: http://tinkerbin.com/3G6B93Cb
I realize this is an old question. I found it several months ago when I was trying to do the same thing, and was underwhelmed by the answers given. They all seemed to deal with importing from Bitbucket to GitHub one repository at a time, either via commands issued à la carte, or via the GitHub importer.
I grabulated the code from a GitHub project called gitter and modified it to suite my needs.
You can fork the gist, or take the code from here:
#!/usr/bin/env ruby
require 'fileutils'
# Originally -- Dave Deriso -- [email protected]
# Contributor -- G. Richard Bellamy -- [email protected]
# If you contribute, put your name here!
# To get your team ID:
# 1. Go to your GitHub profile, select 'Personal Access Tokens', and create an Access token
# 2. curl -H "Authorization: token <very-long-access-token>" https://api.github.com/orgs/<org-name>/teams
# 3. Find the team name, and grabulate the Team ID
# 4. PROFIT!
#----------------------------------------------------------------------
#your particulars
@access_token = ''
@team_id = ''
@org = ''
#----------------------------------------------------------------------
#the verison of this app
@version = "0.2"
#----------------------------------------------------------------------
#some global params
@create = false
@add = false
@migrate = false
@debug = false
@done = false
@error = false
#----------------------------------------------------------------------
#fancy schmancy color scheme
class String; def c(cc); "\e[#{cc}m#{self}\e[0m" end end
#200.to_i.times{ |i| print i.to_s.c(i) + " " }; puts
@sep = "-".c(90)*95
@sep_pref = ".".c(90)*95
@sep_thick = "+".c(90)*95
#----------------------------------------------------------------------
# greetings
def hello
puts @sep
puts "BitBucket to GitHub migrator -- v.#{@version}".c(95)
#puts @sep_thick
end
def goodbye
puts @sep
puts "done!".c(95)
puts @sep
exit
end
def puts_title(text)
puts @sep, "#{text}".c(36), @sep
end
#----------------------------------------------------------------------
# helper methods
def get_options
require 'optparse'
n_options = 0
show_options = false
OptionParser.new do |opts|
opts.banner = @sep +"\nUsage: gitter [options]\n".c(36)
opts.version = @version
opts.on('-n', '--name [name]', String, 'Set the name of the new repo') { |value| @repo_name = value; n_options+=1 }
opts.on('-c', '--create', String, 'Create new repo') { @create = true; n_options+=1 }
opts.on('-m', '--migrate', String, 'Migrate the repo') { @migrate = true; n_options+=1 }
opts.on('-a', '--add', String, 'Add repo to team') { @add = true; n_options+=1 }
opts.on('-l', '--language [language]', String, 'Set language of the new repo') { |value| @language = value.strip.downcase; n_options+=1 }
opts.on('-d', '--debug', 'Print commands for inspection, doesn\'t actually run them') { @debug = true; n_options+=1 }
opts.on_tail('-h', '--help', 'Prints this little guide') { show_options = true; n_options+=1 }
@opts = opts
end.parse!
if show_options || n_options == 0
puts @opts
puts "\nExamples:".c(36)
puts 'create new repo: ' + "\t\tgitter -c -l javascript -n node_app".c(93)
puts 'migrate existing to GitHub: ' + "\tgitter -m -n node_app".c(93)
puts 'create repo and migrate to it: ' + "\tgitter -c -m -l javascript -n node_app".c(93)
puts 'create repo, migrate to it, and add it to a team: ' + "\tgitter -c -m -a -l javascript -n node_app".c(93)
puts "\nNotes:".c(36)
puts "Access Token for repo is #{@access_token} - change this on line 13"
puts "Team ID for repo is #{@team_id} - change this on line 14"
puts "Organization for repo is #{@org} - change this on line 15"
puts 'The assumption is that the person running the script has SSH access to BitBucket,'
puts 'and GitHub, and that if the current directory contains a directory with the same'
puts 'name as the repo to migrated, it will deleted and recreated, or created if it'
puts 'doesn\'t exist - the repo to migrate is mirrored locally, and then created on'
puts 'GitHub and pushed from that local clone.'
puts 'New repos are private by default'
puts "Doesn\'t like symbols for language (ex. use \'c\' instead of \'c++\')"
puts @sep
exit
end
end
#----------------------------------------------------------------------
# git helper methods
def gitter_create(repo)
if @language
%q[curl https://api.github.com/orgs/] + @org + %q[/repos -H "Authorization: token ] + @access_token + %q[" -d '{"name":"] + repo + %q[","private":true,"language":"] + @language + %q["}']
else
%q[curl https://api.github.com/orgs/] + @org + %q[/repos -H "Authorization: token ] + @access_token + %q[" -d '{"name":"] + repo + %q[","private":true}']
end
end
def gitter_add(repo)
if @language
%q[curl https://api.github.com/teams/] + @team_id + %q[/repos/] + @org + %q[/] + repo + %q[ -H "Accept: application/vnd.github.v3+json" -H "Authorization: token ] + @access_token + %q[" -d '{"permission":"pull","language":"] + @language + %q["}']
else
%q[curl https://api.github.com/teams/] + @team_id + %q[/repos/] + @org + %q[/] + repo + %q[ -H "Accept: application/vnd.github.v3+json" -H "Authorization: token ] + @access_token + %q[" -d '{"permission":"pull"}']
end
end
def git_clone_mirror(bitbucket_origin, path)
"git clone --mirror #{bitbucket_origin}"
end
def git_push_mirror(github_origin, path)
"(cd './#{path}' && git push --mirror #{github_origin} && cd ..)"
end
def show_pwd
if @debug
Dir.getwd()
end
end
def git_list_origin(path)
"(cd './#{path}' && git config remote.origin.url && cd ..)"
end
# error checks
def has_repo
File.exist?('.git')
end
def has_repo_or_error(show_error)
@repo_exists = has_repo
if !@repo_exists
puts 'Error: no .git folder in current directory'.c(91) if show_error
@error = true
end
"has repo: #{@repo_exists}"
end
def has_repo_name_or_error(show_error)
@repo_name_exists = !(defined?(@repo_name)).nil?
if !@repo_name_exists
puts 'Error: repo name missing (-n your_name_here)'.c(91) if show_error
@error = true
end
end
#----------------------------------------------------------------------
# main methods
def run(commands)
if @debug
commands.each { |x| puts(x) }
else
commands.each { |x| system(x) }
end
end
def set_globals
puts_title 'Parameters'
@git_bitbucket_origin = "[email protected]:#{@org}/#{@repo_name}.git"
@git_github_origin = "[email protected]:#{@org}/#{@repo_name}.git"
puts 'debug: ' + @debug.to_s.c(93)
puts 'working in: ' + Dir.pwd.c(93)
puts 'create: ' + @create.to_s.c(93)
puts 'migrate: ' + @migrate.to_s.c(93)
puts 'add: ' + @add.to_s.c(93)
puts 'language: ' + @language.to_s.c(93)
puts 'repo name: '+ @repo_name.to_s.c(93)
puts 'bitbucket: ' + @git_bitbucket_origin.to_s.c(93)
puts 'github: ' + @git_github_origin.to_s.c(93)
puts 'team_id: ' + @team_id.to_s.c(93)
puts 'org: ' + @org.to_s.c(93)
end
def create_repo
puts_title 'Creating'
#error checks
has_repo_name_or_error(true)
goodbye if @error
puts @sep
commands = [
gitter_create(@repo_name)
]
run commands
end
def add_repo
puts_title 'Adding repo to team'
#error checks
has_repo_name_or_error(true)
goodbye if @error
puts @sep
commands = [
gitter_add(@repo_name)
]
run commands
end
def migrate_repo
puts_title "Migrating Repo to #{@repo_provider}"
#error checks
has_repo_name_or_error(true)
goodbye if @error
if Dir.exists?("#{@repo_name}.git")
puts "#{@repo_name} already exists... recursively deleting."
FileUtils.rm_r("#{@repo_name}.git")
end
path = "#{@repo_name}.git"
commands = [
git_clone_mirror(@git_bitbucket_origin, path),
git_list_origin(path),
git_push_mirror(@git_github_origin, path)
]
run commands
end
#----------------------------------------------------------------------
#sequence control
hello
get_options
#do stuff
set_globals
create_repo if @create
migrate_repo if @migrate
add_repo if @add
#peace out
goodbye
Then, to use the script:
# create a list of repos
foo
bar
baz
# execute the script, iterating over your list
while read p; do ./bitbucket-to-github.rb -a -n $p; done<repos
# good nuff
Delete all files from these folders .
C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files
If you don't care about the columns where the missing files are, considering that the dataframe has the name New
and one wants to assign the new dataframe to the same variable, simply run
New = New.drop_duplicates()
If you specifically want to remove the rows for the empty values in the column Tenant
this will do the work
New = New[New.Tenant != '']
This may also be used for removing rows with a specific value - just change the string to the value that one wants.
Note: If instead of an empty string one has NaN
, then
New = New.dropna(subset=['Tenant'])
For cleaning the pasted text and replacing the currently selected text with the pasted text the matter is pretty trivial:
<div id='div' contenteditable='true' onpaste='handlepaste(this, event)'>Paste</div>
JS:
function handlepaste(el, e) {
document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
e.preventDefault();
}
For those running in such issues right now, just try to put an alias for the table, this should the trick, e.g:
SELECT myvalue
INTO myvar
FROM mytable x
WHERE x.anothervalue = 1;
It worked for me.
Cheers.
you can take a look at GOBject. it's an OS library that give you a verbose way to do an object.
See the official documentation (http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330)
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics.
But in Oracle Databast 12c maybe 32767 (http://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020)
Variable-length character string having maximum length size bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. Maximum size is: 32767 bytes or characters if MAX_STRING_SIZE = EXTENDED 4000 bytes or characters if MAX_STRING_SIZE = STANDARD
Yes obviously.
That’s because a locally installed composer will give first preference to composer.lock file over composer.json.
If lock file is not available in vcs the composer will point to composer.json file to install latest dependencies or versions.
The file composer.lock maintains dependency in more depth i.e it points to the actual commit of the version of the package we include in our software, hence this is one of the most important files which handles the dependency more finely.
Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.
I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).
Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.
(Still looking for a better way to do it)
package com.christianfries.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
public class UNCPathTest {
public static void main(String[] args) throws MalformedURLException, URISyntaxException {
UNCPathTest upt = new UNCPathTest();
upt.testURL("file://server/dir/file.txt"); // Windows UNC Path
upt.testURL("file:///Z:/dir/file.txt"); // Windows drive letter path
upt.testURL("file:///dir/file.txt"); // Unix (absolute) path
}
private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
URL url = new URL(urlString);
System.out.println("URL is: " + url.toString());
URI uri = url.toURI();
System.out.println("URI is: " + uri.toString());
if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
// Hack for UNC Path
uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
}
File file = new File(uri);
System.out.println("File is: " + file.toString());
String parent = file.getParent();
System.out.println("Parent is: " + parent);
System.out.println("____________________________________________________________");
}
}
It's often clearer to separate the two actions git pull
does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch
. The second is that it then merges in changes, which can of course be done with git merge
, though other options such as git rebase
are occasionally useful.
Don't over complicate the problem.
string osVer = System.Environment.OSVersion.Version.ToString();
if (osVer.StartsWith("5")) // windows 2000, xp win2k3
{
MessageBox.Show("xp!");
}
else // windows vista and windows 7 start with 6 in the version #
{
MessageBox.Show("Win7!");
}
You can use the DataGridViewColumn.Width property to do it:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.width.aspx
I did this simple code!:)
<html>
<head>
<title> Download-Button </title>
</head>
<body>
<p> Click the image ! You can download! </p>
<a download="logo.png" href="http://localhost/folder/img/logo.png" title="Logo title">
<img alt="logo" src="http://localhost/folder/img/logo.png">
</a>
</body>
</html>
This will do it to every line in the file:
:%s/$/,/
If you want to do a subset of lines instead of the whole file, you can specify them in place of the %
.
One way is to do a visual select and then type the :
. It will fill in :'<,'>
for you, then you type the rest of it (Notice you only need to add s/$/,/
)
:'<,'>s/$/,/
I know it's been a while this has been posted, but with iOS 7.1, a few things have changed.
So far, if you are developing an App, you MUST have a valid SSL certificate recognized by Apple, otherwise you will get an error message on you iDevice. No more self-signed certificates. See here a list:
http://support.apple.com/kb/ht5012
Additionally, if you are here, it means that you are trying to make you iDevice resolve a name (to your https server), on a test or development environment.
Instead of using squid, which is a great application, you could simply run a very basic DNS server like dnsmasq. It will use your hosts file as a first line of name resolution, so, you can basically fool your iDevice there, saying that www.blah.com is 192.168.10.10.
The configuration file is as simple as 3 to 4 lines, and you can even configure its internal DHCP server if you want.
Here is mine:
listen-address=192.168.10.35
domain-needed
bogus-priv
no-dhcp-interface=eth0
local=/localnet/
Of course you have to configure networking on your iDevice to use that DNS (192.168.10.35 in my case), or just start using DHCP from that server anyway, after properly configured.
Additionally, if dnsmasq cannot resolve the name internally, it uses your regular DNS server (like 8.8.8.8) to resolve it for you. VERY simple, elegant, and solved my problems with iDevice App installation in-house.
By the way, solves many name resolution problems with regular macs (OS X) as well.
Now, my rant: bloody Apple. Making a device safe should not include castrating the operating system or the developers.
First of all: officially, the correct question would be
web services + WSDL + SOAP
vsREST
.Because, although the web service, is used in the loose sense, when using the HTTP protocol to transfer data instead of web pages, officially it is a very specific form of that idea. According to the definition, REST is not "web service".
In practice however, everyone ignores that, so let's ignore it too
There are already technical answers, so I'll try to provide some intuition.
Let's say you want to call a function in a remote computer, implemented in some other programming language (this is often called remote procedure call/RPC). Assume that function can be found at a specific URL, provided by the person who wrote it. You have to (somehow) send it a message, and get some response. So, there are two main questions to consider.
For the first question, the official definition is WSDL. This is an XML file which describes, in detailed and strict format, what are the parameters, what are their types, names, default values, the name of the function to be called, etc. An example WSDL here shows that the file is human-readable (but not easily).
For the second question, there are various answers. However, the only one used in practice is SOAP. Its main idea is: wrap the previous XML (the actual message) into yet another XML (containing encoding info and other helpful stuff), and send it over HTTP. The POST method of the HTTP is used to send the message, since there is always a body.
The main idea of this whole approach is that you map a URL to a function, that is, to an action. So, if you have a list of customers in some server, and you want to view/update/delete one, you must have 3 URLS:
myapp/read-customer
and in the body of the message, pass the id of the customer to be read.myapp/update-customer
and in the body, pass the id of the customer, as well as the new datamyapp/delete-customer
and the id in the bodyThe REST approach sees things differently. A URL should not represent an action, but a thing (called resource in the REST lingo). Since the HTTP protocol (which we are already using) supports verbs, use those verbs to specify what actions to perform on the thing.
So, with the REST approach, customer number 12 would be found on URL myapp/customers/12
. To view the customer data, you hit the URL with a GET request. To delete it, the same URL, with a DELETE verb. To update it, again, the same URL with a POST verb, and the new content in the request body.
For more details about the requirements that a service has to fulfil to be considered truly RESTful, see the Richardson maturity model. The article gives examples, and, more importantly, explains why a (so-called) SOAP service, is a level-0 REST service (although, level-0 means low compliance to this model, it's not offensive, and it is still useful in many cases).
Here is a simple function which does exactly this :
#include <windows.h>
#include <string>
bool dirExists(const std::string& dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
With the --squash
flag it looks like two parallel branches with no relation:
Sorting commits related to date looks like:
Personally, i don't like --squash option, try this trick, maybe it fits your needs, i use it for small projects:
null commit for intentionally merge conflict, name it anything you prefer
You have to correctly override method equals() from class Object
Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.
Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.
For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().
But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.
There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.
Some of the collections that use hashCode()
Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily
This problem is solved in bootstrap-4-alpha-2.
Here is the link: http://blog.getbootstrap.com/2015/12/08/bootstrap-4-alpha-2/
Clone it on github: https://github.com/twbs/bootstrap/tree/v4.0.0-alpha.2
You can also install Git Credential Manager for Windows to save Git passwords in Windows credentials manager instead of _netrc
. This is a more secure way to store passwords.
This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.
This hinges on the fact that the Firebase REST API offers a shallow=true
parameter.
Assume you have a post
object and each one can have a number of comments
:
{
"posts": {
"$postKey": {
"comments": {
...
}
}
}
}
You obviously don't want to fetch all of the comments, just the number of comments.
Assuming you have the key for a post, you can send a GET
request to
https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true
.
This will return an object of key-value pairs, where each key is the key of a comment and its value is true
:
{
"comment1key": true,
"comment2key": true,
...,
"comment9999key": true
}
The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length
).
This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.
I believe the more modern and simpler way to do this now is hg uncommit
. Note this leaves behind an empty commit which can be useful if you want to reuse the commit message later. If you don't, use hg uncommit --no-keep
to not leave the empty commit.
hg uncommit [OPTION]... [FILE]...
uncommit part or all of a local changeset
This command undoes the effect of a local commit, returning the affected files to their uncommitted state. This means that files modified or deleted in the changeset will be left unchanged, and so will remain modified in the working directory. If no files are specified, the commit will be left empty, unless --no-keep
Sorry, I am not sure what the equivalent is TortoiseHg.
Call a static method from an instance:
function Clazz() {};
Clazz.staticMethod = function() {
alert('STATIC!!!');
};
Clazz.prototype.func = function() {
this.constructor.staticMethod();
}
var obj = new Clazz();
obj.func(); // <- Alert's "STATIC!!!"
Simple Javascript Class Project: https://github.com/reduardo7/sjsClass
One can also do this with a compact version of @TomAugspurger's answer, like so:
df = df1.merge(df2, how='left', on=['Year', 'Week', 'Colour']).merge(df3[['Week', 'Colour', 'Val3']], how='left', on=['Week', 'Colour'])
JavaScript running in a browser doesn't generally have access to the local file system. That's outside the sandbox. So I think the answer is no.
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
You can try with:
route -n get default
It is not the same as GNU/Linux's route -n
(or even ip route show
) but is useful for checking the default route information.
Also, you can check the route that packages will take to a particular host. E.g.
route -n get www.yahoo.com
The output would be similar to:
route to: 98.137.149.56
destination: default
mask: 128.0.0.0
gateway: 5.5.0.1
interface: tun0
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING>
recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire
0 0 0 0 0 0 1500 0
IMHO netstat -nr
is what you need. Even MacOSX's Network utility app(*) uses the output of netstat to show routing information.
I hope this helps :)
(*) You can start Network utility with open /Applications/Utilities/Network\ Utility.app
string.Format("{0:000}", myString);
If someone is looking to sub out more than a comma I'm a fan of:
"1,200".chars.grep(/\d/).join.to_i
dunno about performance but, it is more flexible than a gsub
, ie:
"1-200".chars.grep(/\d/).join.to_i
This should be more helpful for debug. Answer from @Juned Ahsan will not specify full URL and will not print multiple headers/parameters.
private String httpServletRequestToString(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
sb.append("Request Method = [" + request.getMethod() + "], ");
sb.append("Request URL Path = [" + request.getRequestURL() + "], ");
String headers =
Collections.list(request.getHeaderNames()).stream()
.map(headerName -> headerName + " : " + Collections.list(request.getHeaders(headerName)) )
.collect(Collectors.joining(", "));
if (headers.isEmpty()) {
sb.append("Request headers: NONE,");
} else {
sb.append("Request headers: ["+headers+"],");
}
String parameters =
Collections.list(request.getParameterNames()).stream()
.map(p -> p + " : " + Arrays.asList( request.getParameterValues(p)) )
.collect(Collectors.joining(", "));
if (parameters.isEmpty()) {
sb.append("Request parameters: NONE.");
} else {
sb.append("Request parameters: [" + parameters + "].");
}
return sb.toString();
}
I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth
cookie from JavaScript, as it is marked as HttpOnly
. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).
int number = Question.Role.GetHashCode();
number
should have the value 2
.
Assuming you've got a mapview set up and running:
MapView mapView = (MapView) findViewById(R.id.mapview);
final MyLocationOverlay myLocation = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocation);
myLocation.enableMyLocation();
myLocation.runOnFirstFix(new Runnable() {
public void run() {
GeoPoint pt = myLocation.getMyLocation();
}
});
You'll need the following permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
And to send mock coordinates to the emulator from Eclipse, Go to the "Window" menu, select "Show View" > "Other" > "Emulator control", and you can send coordinates from the emulator control pane that appears.