Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
^M
If you prefer to always see the Windows newlines in vim render as ^M
, you can add this line to your .vimrc
:
set ffs=unix
This will make vim interpret every file you open as a unix file. Since unix files have \n
as the newline character, a windows file with a newline character of \r\n
will still render properly (thanks to the \n
) but will have ^M
at the end of the file (which is how vim renders the \r
character).
If you'd prefer just to set it on a per-file basis, you can use :e ++ff=unix
when editing a given file.
unix
vs dos
)If you want the bottom line of vim to always display what filetype you're editing (and you didn't force set the filetype to unix) you can add to your statusline
with
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
.
My full statusline is provided below. Just add it to your .vimrc
.
" Make statusline stay, otherwise alerts will hide it
set laststatus=2
set statusline=
set statusline+=%#PmenuSel#
set statusline+=%#LineNr#
" This says 'show filename and parent dir'
set statusline+=%{expand('%:p:h:t')}/%t
" This says 'show filename as would be read from the cwd'
" set statusline+=\ %f
set statusline+=%m\
set statusline+=%=
set statusline+=%#CursorColumn#
set statusline+=\ %y
set statusline+=\ %{&fileencoding?&fileencoding:&encoding}
set statusline+=\[%{&fileformat}\]
set statusline+=\ %p%%
set statusline+=\ %l:%c
set statusline+=\
It'll render like
.vim/vimrc\ [vim] utf-8[unix] 77% 315:6
at the bottom of your file
unix
vs dos
)If you just want to see what type of file you have, you can use :set fileformat
(this will not work if you've force set the filetype). It will return unix
for unix files and dos
for Windows.
This function is called self-invoking function. A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked(Called) immediately after its definition. Read more here
What these functions do is that when the function is defined, The function is immediately called, which saves time and extra lines of code(as compared to calling it on a seperate line).
Here is an example:
(function() {_x000D_
var x = 5 + 4;_x000D_
console.log(x);_x000D_
})();
_x000D_
I found that when inserting, the null column values had to be specifically declared as NULL, otherwise I would get a constraint violation error (as opposed to an empty string).
You open the variable "file" as a read only then attempt to write to it:
file = open('ValidEmails.txt','r')
Instead, use the 'w' flag.
file = open('ValidEmails.txt','w')
...
file.write(email)
I like using a background image. I find it easier and more flexible:
CSS:
#menu {
max-width: 1200px;
text-align: center;
margin: auto;
}
.zoomimg {
display: inline-block;
width: 250px;
height: 375px;
padding: 0px 5px 0px 5px;
background-size: 100% 100%;
background-repeat: no-repeat;
background-position: center center;
transition: all .5s ease;
}
.zoomimg:hover {
cursor: pointer;
background-size: 150% 150%;
}
.blog {
background-image: url(http://s18.postimg.org/il7hbk7i1/image.png);
}
.music {
background-image: url(http://s18.postimg.org/4st2fxgqh/image.png);
}
.projects {
background-image: url(http://s18.postimg.org/sxtrxn115/image.png);
}
.bio {
background-image: url(http://s18.postimg.org/5xn4lb37d/image.png);
}
HTML:
<div id="menu">
<div class="blog zoomimg"></div>
<div class="music zoomimg"></div>
<div class="projects zoomimg"></div>
<div class="bio zoomimg"></div>
</div>
<script type="text/javascript">
function MyFunction() {
var FNumber = Number(document.getElementById('txtFirstNumber').value);
var SNumber = Number(document.getElementById("txtSecondNumber").value);
var Sum = FNumber + SNumber;
alert(Sum);
}
</script>
<table class="auto-style1">
<tr>
<td>FirstNaumber</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>SecondNumber</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:TextBox ID="txtSum" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" OnClientClick="MyFunction()" />
</td>
</tr>
</table>
</div>
</form>
Django provides it. You can use either:
{{ forloop.counter }}
index starts at 1.{{ forloop.counter0 }}
index starts at 0.In template, you can do:
{% for item in item_list %}
{{ forloop.counter }} # starting index 1
{{ forloop.counter0 }} # starting index 0
# do your stuff
{% endfor %}
More info at: for | Built-in template tags and filters | Django documentation
That is the function that I used for my project, and it works as expected.
function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
header( 'Content-Type: application/csv' );
header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
// clean output buffer
ob_end_clean();
$handle = fopen( 'php://output', 'w' );
// use keys as column titles
fputcsv( $handle, array_keys( $array['0'] ) );
foreach ( $array as $value ) {
fputcsv( $handle, $value , $delimiter );
}
fclose( $handle );
// flush buffer
ob_flush();
// use exit to get rid of unexpected output afterward
exit();
}
You want to use os.path.expanduser.
This will ensure it works on all platforms:
from os.path import expanduser
home = expanduser("~")
If you're on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Path
home = str(Path.home())
For fromating output date use format
. Second moment argument is for parsing - however if you omit it then you testDate
will cause deprecation warning
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format...
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"_x000D_
_x000D_
let s= moment(testDate).format('MM/DD/YYYY');_x000D_
_x000D_
msg.innerText= s;
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>_x000D_
_x000D_
<div id="msg"></div>
_x000D_
to omit this warning you should provide parsing format
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"_x000D_
_x000D_
let s= moment(testDate, 'ddd MMM D YYYY HH:mm:ss ZZ').format('MM/DD/YYYY');_x000D_
_x000D_
console.log(s);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
&
is used for bit-wise comparison. use and
instead. and btw, you don't need semicolon at the end of print statement.
None of the answers worked for me. The simplest way would be to add <td>
s in between with width = 5px
and background='white'
or whatever the background color of the page is.
Again this will fail in case you have a list of <th>
s representing table headers.
You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 LIMIT 1001, 1000
This query is not correct (or at least i don't know a possible way to use limit in UPDATE queries), you should put a where
condition on you primary key (this assumes you have an auto_increment column as your primary key, if not provide more details):
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE primary_key BETWEEN 1001 AND 2000
For the second query you must use IS
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE panel_id is null
EDIT - if your primary_key is a column named MAX+1 you query should be (with backticks as stated correctly in the comment):
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE `MAX+1` BETWEEN 1001 AND 2000
To update the rows with MAX+1 from 1001 TO 2000 (including 1001 and 2000)
You do not need to interact with managed code, as you can use LIKE:
CREATE TABLE #Sample(Field varchar(50), Result varchar(50))
GO
INSERT INTO #Sample (Field, Result) VALUES ('ABC123 ', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123.', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123&', 'Match')
SELECT * FROM #Sample WHERE Field LIKE '%[^a-z0-9 .]%'
GO
DROP TABLE #Sample
As your expression ends with +
you can go with '%[^a-z0-9 .][^a-z0-9 .]%'
EDIT:
To make it clear: SQL Server doesn't support regular expressions without managed code. Depending on the situation, the LIKE
operator can be an option, but it lacks the flexibility that regular expressions provides.
you can do like this :
<?php
$file = 'your_images.jpg';
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($file));
echo file_get_contents($file);
?>
If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.
This is directly from the MSDN docs:
// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
Response.AppendCookie(myHttpCookie);
// Show the name of the cookie.
Response.Write(myHttpCookie.Name);
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
Response.AppendCookie(myHttpOnlyCookie);
// Show the name of the HttpOnly cookie.
Response.Write(myHttpOnlyCookie.Name);
Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.
Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.
Source : http://git-scm.com/book/en/Git-Basics-Undoing-Things
git checkout -- modifiedfile.java
1)$ git status
you will see the modified file
2)$git checkout -- modifiedfile.java
3)$git status
Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.
Change your class to make an observable, that will emit results of new requests:
export class RecentDetectionComponent implements OnInit {
recentDetections$: Observable<Array<RecentDetection>>;
constructor(private recentDetectionService: RecentDetectionService) {
}
ngOnInit() {
this.recentDetections$ = Observable.interval(5000)
.exhaustMap(() => this.recentDetectionService.getJsonFromApi())
.do(recent => console.log(recent[0].macAddress));
}
}
And update your view to use AsyncPipe:
<tr *ngFor="let detected of recentDetections$ | async">
...
</tr>
Want to add, that it's better to make a service with a method that will take interval
argument, and:
exhaustMap
like in code above);var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
If you are using PHP 5 you can try this:
function a() {
$trace = debug_backtrace();
echo $trace[0]["function"];
}
Thanks for your feed back got it to work I used the sshpass tool.
sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/
How do I have to do in Python for calling an static method from another static method of the same class?
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_method(cls) :
cls.static_method_to_call()
PowerShell features a Restart-Service
cmdlet, which either starts or restarts the service as appropriate.
The
Restart-Service
cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error.You can specify the services by their service names or display names, or you can use the
InputObject
parameter to pass an object that represents each service that you want to restart.
It is a little more foolproof than running two separate commands.
The easiest way to use it just pass either the service name or the display name directly:
Restart-Service 'Service Name'
It can be used directly from the standard cmd prompt with a command like:
powershell -command "Restart-Service 'Service Name'"
Since you mentioned that you're working on a NFS system, do you have access to those semaphores and shared memory? I think you misunderstood what they are, they are an API code that enables processes to communicate with each other, semaphores are a solution for preventing race conditions and for threads to communicate with each other, in simple answer, they do not leave any residue on any filesystem.
Unless you are using an socket or a pipe? Do you have the necessary permissions to remove them, why are they on an NFS system?
Hope this helps, Best regards, Tom.
You are running the Command Prompt as an admin. You have only defined PYTHON for your user. You need to define it in the bottom "System variables" section.
Also, you should only point the variable to the folder, not directly to the executable.
Quite simply:
git rm --cached <file>
makes git stop tracking the file completely (leaving it in the filesystem, unlike plain git rm
*)git reset HEAD <file>
unstages any modifications made to the file since the last commit (but doesn't revert them in the filesystem, contrary to what the command name might suggest**). The file remains under revision control.If the file wasn't in revision control before (i.e. you're unstaging a file that you had just git add
ed for the first time), then the two commands have the same effect, hence the appearance of these being "two ways of doing something".
* Keep in mind the caveat @DrewT mentions in his answer, regarding git rm --cached
of a file that was previously committed to the repository. In the context of this question, of a file just added and not committed yet, there's nothing to worry about.
** I was scared for an embarrassingly long time to use the git reset command because of its name -- and still today I often look up the syntax to make sure I don't screw up. (update: I finally took the time to summarize the usage of git reset
in a tldr page, so now I have a better mental model of how it works, and a quick reference for when I forget some detail.)
Late to the party, but... why not just this.hasAttribute("name")
?
Refer This
You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):
function is_decimal( $val )
{
return is_numeric( $val ) && floor( $val ) != $val;
}
Make sure your eclipse.ini
file includes the following lines.
-vm
C:\path\to\64bit\java\bin\javaw.exe
My eclipse.ini
for example:
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.2.R36x_v20101222
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
-vm
C:\Program Files\Java\jdk1.6.0_32\bin\javaw.exe
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
Use OS and Eclipse both 64 bit or both 32 bit keep same and config eclipse.ini
.
Your eclipse.ini
file can be found in your eclipse folder.
You should have a table with the list of emails to check. Then do this query:
SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email
swift 4
there is one of way to change text in backButton programmatically from current viewController:
navigationController?.navigationBar.items![0].title = "some new text"
Without a subplots
, you can universally remove the ticks like this:
plt.xticks([])
plt.yticks([])
Run
pip freeze
It works the same as above.
pip show pandas
Displays information about a specific package.
For more information, check out pip help
This solution will only add the border, the body of the LinearLayout will be transparent.
First, Create this border drawable in the drawable folder, border.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android= "http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="2dp" android:color="#ec0606"/>
<corners android:radius="10dp"/>
</shape>
Then, in your LinearLayout View, add the border.xml as the background like this
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/border">
Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS
https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en
Java has primitive types, objects and arrays and that's it. No typedefs.
//JAVA
public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
final int RADIUS_EARTH = 6371;
double dLat = getRad(latitude2 - latitude1);
double dLong = getRad(longitude2 - longitude1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (RADIUS_EARTH * c) * 1000;
}
private Double getRad(Double x) {
return x * Math.PI / 180;
}
Php 7 compatible proper usage:
$fileName = 'long.file.name.jpg';
$tmp = explode('.', $fileName);
$fileExtension = end($tmp);
echo $fileExtension;
// jpg
Maybe combining some javascript and PHP could achieve the trick
<?php
$string = '<script>';
$string .= 'if ( /Opera|OPR\/|Puffin|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { ';
$string .= ' alert("CELL")';
$string .= ' } else {';
$string .= ' alert("NON CELL")';
$string .= ' } ';
$string .= '</script>';
echo $string;
?>
I used that with plain javascript also instead
This code snippet can be used for displaying time in seconds,milliseconds and microseconds:
#include <sys/time.h>
struct timeval start, stop;
double secs = 0;
gettimeofday(&start, NULL);
// Do stuff here
gettimeofday(&stop, NULL);
secs = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec - start.tv_sec);
printf("time taken %f\n",secs);
map (lambda x:(x[1]),elements)
Like with every bad software the treatment for this wrong behaivier does not exist. What is good for one does not work for others.
I let the debuger to stop on a brakepoint once, then again second time and on the third time the beast has shown the Variable View with all data in it.
Many people answered with jQuery
parent, but just to add on to that I wanted to share a quick snippet of code that I use for adding classes to my navs so I can add styling to li
's that only have sub-menus and not li
's that don't.
$("li ul").parent().addClass('has-sub');
From the documentation I get the impression that in your example it would be intended to use:
@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)
Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:
BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types
When you add TestNG to your Maven dependencies , Change scope from test to compile.Hope this would solve your issue..
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement
Example :
CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;
I solved the problem by doing the following (none of the other solutions above helped):
From the pulldown menu associated with "Main Interface" select another entry and then reselect "MainWindow" then rebuild.
If the database in question is local, the following is probably the most robust way to export a query result to a CSV file (that is, giving you the most control).
After going through this process exhaustively, I found the following to be the best option
PowerShell Script
$dbname = "**YOUR_DB_NAME_WITHOUT_STARS**"
$AttachmentPath = "c:\\export.csv"
$QueryFmt= @"
**YOUR_QUERY_WITHOUT_STARS**
"@
Invoke-Sqlcmd -ServerInstance **SERVER_NAME_WITHOUT_STARS** -Database $dbname -Query $QueryFmt | Export-CSV $AttachmentPath -NoTypeInformation
Run PowerShell as Admin
& "c:\path_to_your_ps1_file.ps1"
HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)
XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).
Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.
It really depends on how the server on the other side is configured and with what modules for how it handles a blob post. You can try putting the desired name in the path for your post.
request.open(
"POST",
"/upload/myname.bmp",
true
);
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax :-string.includes(searchString[, position])
searchString:-A string to be searched for within this string.
position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.
string = 'LOL';
console.log(string.includes('lol')); // returns false
console.log(string.includes('LOL')); // returns true
You can use Multiline Search and Replace in Visual Studio macro which provides nice GUI for the task.
This isn't semantic but I just use the existing a
element, set a background image, then create multiple variations for @2x resolution, smaller screen sizes, etc.
Then, you can use the .text-hide
class to get some text on the page the ol' fashion way. Simple and effective though not proper use of an image.
Here's a link to the helper class for text-replacement:
You have to be carefull when using Boolean.valueOf(string) or Boolean.parseBoolean(string). The reason for this is that the methods will always return false if the String is not equal to "true" (the case is ignored).
For example:
Boolean.valueOf("YES") -> false
Because of that behaviour I would recommend to add some mechanism to ensure that the string which should be translated to a Boolean follows a specified format.
For instance:
if (string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false")) {
Boolean.valueOf(string)
// do something
} else {
// throw some exception
}
<script src="~/fileupload/fileinput.min.js"></script>
<link href="~/fileupload/fileinput.min.css" rel="stylesheet" />
Download above files named fileinput add the path i your index page.
<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"
`enter code here`accept=".pdf" multiple>
</div>
<script>
$("#uploadFile1").fileinput({
autoReplace: true,
maxFileCount: 5
});
</script>
If you are running out of connections like this, chances are excellent that you are not closing the connections that you have open.
Review code that opens connections and ensure the connections are closed as soon as practical. Typically you want to make use of the using keyword around anything that implements IDisposable (including database connections) to ensure that such objects are disposed as soon as they leave the scope where they are needed.
You can check the current number of active connections with this query:
show processlist
If start time is a datetime type then you can use something like
SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000'
AND StartTime <= '2012-03-08 01:00:00.000'
Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.
You can use the GETDATE() function to get todays current date.
Note to the above solution (from A Paul): The solution doesn't work, cause it doesn't reconstructs back a HashMap< String, Object > - instead it creates a HashMap< String, LinkedHashMap >.
Reason why is because during demarshalling, each Object (JSON marshalled as a LinkedHashMap) is used as-is, it takes 1-on-1 the LinkedHashMap (instead of converting the LinkedHashMap back to its proper Object).
If you had a HashMap< String, MyOwnObject > then proper demarshalling was possible - see following example:
ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, MyOwnObject.class);
HashMap<String, MyOwnObject> map = mapper.readValue(new StringReader(hashTable.toString()), mapType);
String[] errorSoon = { "foo", "bar" };
-- or --
String[] errorSoon = new String[2];
errorSoon[0] = "foo";
errorSoon[1] = "bar";
Hiding an <option>
element is not in the spec. But you can disable
them, which should work cross-browser.
$('option.hide').prop('disabled', true);
For React 16.8, you can do this with a functional component using useEffect.
For Example:
useEffect(() => {
document.title = "new title"
}, []);
Having the second argument as an array calls useEffect only once, making it similar to componentDidMount
.
It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Use the traceback module:
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
print('An error occurred on line {} in statement {}'.format(line, text))
exit(1)
If you want to put multiple conditions in filter
, you can use &&
and ||
operator.
var product= Object.values(arr_products).filter(x => x.Status==status && x.email==user)
Go To AVD Manager, Click On The "Down Arrow" Next to The AVD Device that is showing this error, Click on "Show on Disk". Now Delete These Two Files "Cache.img" & "cache.img.qcow2" ..
Works Perfectly Fine For me.
There's another layout manager that may be of interest here: Overlay Layout Here's a simple tutorial: OverlayLayout: for layout management of components that lie on top of one another. Overlay Layout allows you to position panels on top of one another, and set a layout inside each panel. You are also able to set size and position of each panel separately.
(The reason I'm answering this question from years ago is because I have stumbled upon the same problem, and I have seen very few mentions of the Overlay Layout on StackOverflow, while it seems to be pretty well documented. Hopefully this may help someone else who keeps searching for it.)
This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback
function getData(callbackData){
var http = require('http');
var str = '';
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
callbackData(str);
});
//return str;
}
var req = http.request(options, callback).end();
// These just return undefined and empty
console.log(req.data);
console.log(str);
}
somewhere else
getData(function(data){
// YOUR CODE HERE!!!
})
here is an easy way to do it:
but first you have to add ( Privacy - Photo Library Usage Description ) in the info.plist, and you should have a button and a UIImageView in your viewController.
then create an outlet of the UIImageView ( in this code the outlet is called myImage), and an action of the button ( I called the action importing in my code )
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var myImage: UIImageView!
@IBAction func importing(_ sender: Any) {
let Picker = UIImagePickerController()
Picker.delegate = self
Picker.sourceType = .photoLibrary
self.present(Picker, animated: true, completion: nil)
Picker.allowsEditing = true
Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
}
func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
{
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
myImage.contentMode = .scaleAspectFit //2
myImage.image = chosenImage //3
dismiss(animated:true, completion: nil) //4
}
}
Just incase if anyone is looking for how to do it in typescript here is the solution
@Watch('$route', { immediate: true, deep: true })
onUrlChange(newVal: Route) {
// Some action
}
And yes as mentioned by @Coops below, please do not forget to include
import { Watch } from 'vue-property-decorator';
Edit: Alcalyn made a very good point of using Route type instead of using any
import { Watch } from 'vue-property-decorator';
import { Route } from 'vue-router';
You can also do the following:
txt = "Hello World!"
print (*txt, sep='\n')
This does not use loops but internally print statement takes care of it.
*
unpacks the string into a list and sends it to the print statement
sep='\n'
will ensure that the next char is printed on a new line
The output will be:
H
e
l
l
o
W
o
r
l
d
!
If you do need a loop statement, then as others have mentioned, you can use a for loop like this:
for x in txt: print (x)
May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.
mysqldump --routines=true -u <user> my_database > my_database.sql
I tried one of the previous answers in a web app (actually an Azure web role running locally) and it didn't quite work. However, this similar approach did work:
var map = new ExeConfigurationFileMap { ExeConfigFilename = "MyComponent.dll.config" };
var path = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None).FilePath;
The config file turned out to be in C:\Program Files\IIS Express\MyComponent.dll.config. Interesting place for it.
An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".
If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.
How about doing something like this? I've made it from scratch...
What I've done is used 2 tables, one for header, which will be static always, and the other table renders cells, which I've wrapped using a div
element with a fixed height, and to enable scroll, am using overflow-y: auto;
Also make sure you use table-layout: fixed;
with fixed width td
elements so that your table
doesn't break when a string without white space
is used, so inorder to break that string am using word-wrap: break-word;
.wrap {
width: 352px;
}
.wrap table {
width: 300px;
table-layout: fixed;
}
table tr td {
padding: 5px;
border: 1px solid #eee;
width: 100px;
word-wrap: break-word;
}
table.head tr td {
background: #eee;
}
.inner_table {
height: 100px;
overflow-y: auto;
}
<div class="wrap">
<table class="head">
<tr>
<td>Head 1</td>
<td>Head 1</td>
<td>Head 1</td>
</tr>
</table>
<div class="inner_table">
<table>
<tr>
<td>Body 1</td>
<td>Body 1</td>
<td>Body 1</td>
</tr>
<!-- Some more tr's -->
</table>
</div>
</div>
I ended up using this regex, as it successfully validates commas, comments, Unicode characters and IP(v4) domain addresses.
Valid addresses will be:
" "@example.org
(comment)[email protected]
test@[192.168.1.1]
public const string REGEX_EMAIL = @"^(((\([\w!#$%&'*+\/=?^_`{|}~-]*\))?[^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))(\([\w!#$%&'*+\/=?^_`{|}~-]*\))?@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies>
Refer This Link http://khurramitdeveloper.blogspot.in/2013/06/start-activity-or-service-on-boot.html Step by Step procedure to use boot on Service
You won't always want all items printed, especially for large arrays.
A simple way to show more items:
In [349]: ar
Out[349]: array([1, 1, 1, ..., 0, 0, 0])
In [350]: ar[:100]
Out[350]:
array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1,
1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])
It works fine when sliced array < 1000 by default.
There are several ways to do it:
n = L[0][0]
m = len(A)
found = False
for i in range(m):
if found:
break
for j in range(m):
if L[i][j] != n:
found = True
break
Pros: easy to understand Cons: additional conditional statement for every loop
n = L[0][0]
m = len(A)
try:
for x in range(3):
for z in range(3):
if L[i][j] != n:
raise StopIteration
except StopIteration:
pass
Pros: very straightforward Cons: you use Exception outside of their semantic
def is_different_value(l, elem, size):
for x in range(size):
for z in range(size):
if l[i][j] != elem:
return True
return False
if is_different_value(L, L[0][0], len(A)):
print "Doh"
pros: much cleaner and still efficient cons: yet feels like C
def is_different_value(iterable):
first = iterable[0][0]
for l in iterable:
for elem in l:
if elem != first:
return True
return False
if is_different_value(L):
print "Doh"
pros: still clean and efficient cons: you reinvdent the wheel
any()
:def is_different_value(iterable):
first = iterable[0][0]
return any(any((cell != first for cell in col)) for elem in iterable)):
if is_different_value(L):
print "Doh"
pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you
The code:
$qrystr = "SELECT * FROM mytablename WHERE id= " . $rowid;
$qryresult = $this->connection->query($qrystr);
$result = $qryresult->fetchAll(PDO::FETCH_ASSOC);
unset($result[0]['id']); //Remove ID from array
$qrystr = " INSERT INTO mytablename";
$qrystr .= " ( " .implode(", ",array_keys($result[0])).") ";
$qrystr .= " VALUES ('".implode("', '",array_values($result[0])). "')";
$result = $this->connection->query($qrystr);
return $result;
Of course you should use PDO:bindparam and check your variables against attack, etc but gives the example
additional info
If you have a problem with handling NULL
values, you can use following codes so that imploding
names and values only for whose value is not NULL
.
foreach ($result[0] as $index => $value) {
if ($value === null) unset($result[0][$index]);
}
Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ class
ses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
Array slicing like in Python (From the rebash library):
array_slice() {
local __doc__='
Returns a slice of an array (similar to Python).
From the Python documentation:
One way to remember how slices work is to think of the indices as pointing
between elements, with the left edge of the first character numbered 0.
Then the right edge of the last element of an array of length n has
index n, for example:
```
+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
```
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1:-2 "${a[@]}")
1 2 3
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0:1 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
empty
>>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
empty
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
>>> local a=(0 1 2 3 4 5)
>>> # from the beginning to position 2 (excluded)
>>> echo $(array.slice 0:2 "${a[@]}")
>>> echo $(array.slice :2 "${a[@]}")
0 1
0 1
>>> local a=(0 1 2 3 4 5)
>>> # from position 3 (included) to the end
>>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice 3: "${a[@]}")
3 4 5
3 4 5
>>> local a=(0 1 2 3 4 5)
>>> # from the second-last (included) to the end
>>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice -2: "${a[@]}")
4 5
4 5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -4:-2 "${a[@]}")
2 3
If no range is given, it works like normal array indices.
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -1 "${a[@]}")
5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -2 "${a[@]}")
4
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1 "${a[@]}")
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice 6 "${a[@]}"; echo $?
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice -7 "${a[@]}"; echo $?
1
'
local start end array_length length
if [[ $1 == *:* ]]; then
IFS=":"; read -r start end <<<"$1"
shift
array_length="$#"
# defaults
[ -z "$end" ] && end=$array_length
[ -z "$start" ] && start=0
(( start < 0 )) && let "start=(( array_length + start ))"
(( end < 0 )) && let "end=(( array_length + end ))"
else
start="$1"
shift
array_length="$#"
(( start < 0 )) && let "start=(( array_length + start ))"
let "end=(( start + 1 ))"
fi
let "length=(( end - start ))"
(( start < 0 )) && return 1
# check bounds
(( length < 0 )) && return 1
(( start < 0 )) && return 1
(( start >= array_length )) && return 1
# parameters start with $1, so add 1 to $start
let "start=(( start + 1 ))"
echo "${@: $start:$length}"
}
alias array.slice="array_slice"
The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql
No, just use the value directly:
begin
if (select count(*) from table) > 0 then
update table
end if;
end;
Note there is no need for an "else".
You can simply do it all within the update statement (ie no if
construct):
update table
set ...
where ...
and exists (select 'x' from table where ...)
Pure CSS solution, using calc
.modal-body {
max-height: calc(100vh - 200px);
overflow-y: auto;
}
200px may be adjusted in accordance to height of header & footer
It looks like you want to define Truck as a Class
with properties NumberOfAxles, AxleWeights & AxleSpacings.
This can be defined in a CLASS MODULE (here named clsTrucks)
Option Explicit
Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double
Public Property Get truckID() As String
truckID = tID
End Property
Public Property Let truckID(value As String)
tID = value
End Property
Public Property Get truckNumberOfAxles() As Double
truckNumberOfAxles = tNumberOfAxles
End Property
Public Property Let truckNumberOfAxles(value As Double)
tNumberOfAxles = value
End Property
Public Property Get truckAxleSpacings() As Double
truckAxleSpacings = tAxleSpacings
End Property
Public Property Let truckAxleSpacings(value As Double)
tAxleSpacings = value
End Property
then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.
Option Explicit
Public TruckCollection As New Collection
Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long
'Add 5 trucks
For i = 1 To 5
Set tempTruck = New clsTrucks
'Random data
tempTruck.truckID = "Truck" & i
tempTruck.truckAxleSpacings = 13.5 + i
tempTruck.truckNumberOfAxles = 20.5 + i
'tempTruck.truckID is the collection key
TruckCollection.Add tempTruck, tempTruck.truckID
Next i
'retrieve 5 trucks
For i = 1 To 5
'retrieve by collection index
Debug.Print TruckCollection(i).truckAxleSpacings
'retrieve by key
Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
Next i
End Sub
There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.
The container's IP address should be properly configured inside of its network namespace, so any of the standard linux tools can get it. For example, try ifconfig
, ip addr show
, hostname -I
, etc. from an attached shell within one of your containers to test it out.
Yes, just add multiple FileAppenders to your logger. For example:
<log4net>
<appender name="File1Appender" type="log4net.Appender.FileAppender">
<file value="log-file-1.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<appender name="File2Appender" type="log4net.Appender.FileAppender">
<file value="log-file-2.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="File1Appender" />
<appender-ref ref="File2Appender" />
</root>
</log4net>
In-Short Differences are
1) PCL is not going to have Full Access to .NET Framework , where as SharedProject has.
2) #ifdef for platform specific code - you can not write in PCL (#ifdef option isn’t available to you in a PCL because it’s compiled separately, as its own DLL, so at compile time (when the #ifdef is evaluated) it doesn’t know what platform it will be part of. ) where as Shared project you can.
3) Platform specific code is achieved using Inversion Of Control in PCL , where as using #ifdef statements you can achieve the same in Shared Project.
An excellent article which illustrates differences between PCL vs Shared Project can be found at the following link
http://hotkrossbits.com/2015/05/03/xamarin-forms-pcl-vs-shared-project/
I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like:
mySID, mySID.whereever.com =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = mySID.whereever.com)
(SID = mySID)
(SERVER = DEDICATED)
)
)
I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking.
This version is similar to chiborg's answer, but it eliminates the need for the external tty
and cat
. It uses date
, but could just as easily use gawk
. You can change the shebang and replace the double square brackets with single ones and this will also run in sh
.
#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
if [[ -p /dev/stdin ]] # input from a pipe
then
read -r p
else
echo "No timestamp given." >&2
exit
fi
else
p=$1
fi
date -d "@$p" +%c
I think it's worth answering the generic question "R - test if string contains string" here.
For that, use the grep function.
# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"
To know where Python is installed you can execute where python
in your cmd.exe.
Good example for Iterable to compute factorial
FactorialIterable fi = new FactorialIterable(10);
Iterator<Integer> iterator = fi.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
Short code for Java 1.8
new FactorialIterable(5).forEach(System.out::println);
Custom Iterable class
public class FactorialIterable implements Iterable<Integer> {
private final FactorialIterator factorialIterator;
public FactorialIterable(Integer value) {
factorialIterator = new FactorialIterator(value);
}
@Override
public Iterator<Integer> iterator() {
return factorialIterator;
}
@Override
public void forEach(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
Integer last = 0;
for (Integer t : this) {
last = t;
}
action.accept(last);
}
}
Custom Iterator class
public class FactorialIterator implements Iterator<Integer> {
private final Integer mNumber;
private Integer mPosition;
private Integer mFactorial;
public FactorialIterator(Integer number) {
this.mNumber = number;
this.mPosition = 1;
this.mFactorial = 1;
}
@Override
public boolean hasNext() {
return mPosition <= mNumber;
}
@Override
public Integer next() {
if (!hasNext())
return 0;
mFactorial = mFactorial * mPosition;
mPosition++;
return mFactorial;
}
}
Avoid the for loopfor XY in xy:
Instead read up how the numpy arrays are indexed and handled.
Also try and avoid .txt files if you are dealing with matrices. Try to use .csv or .npy files, and use Pandas dataframework to load them just for clarity.
If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.
Best and simple approach.
DECLARE @AccumulateKeywordCopy NVARCHAR(2000),@IDDupCopy NVARCHAR(50);
SET @AccumulateKeywordCopy ='';
SET @IDDupCopy ='';
SET @IDDup = (SELECT CONVERT(VARCHAR(MAX), <columnName>) FROM <tableName> WHERE <clause>)
SET @AccumulateKeywordCopy = ','+@AccumulateKeyword+',';
SET @IDDupCopy = ','+@IDDup +',';
SET @IDDupCheck = CHARINDEX(@IDDupCopy,@AccumulateKeywordCopy)
Swift 4.2 solution (taking 4.0 answer and updating for new enums to compile)
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}
public void breadthFirstSearch(Node root, Consumer<String> c) {
List<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.remove(0);
c.accept(n.value);
if (n.left != null)
queue.add(n.left);
if (n.right != null)
queue.add(n.right);
}
}
And the Node:
public static class Node {
String value;
Node left;
Node right;
public Node(final String value, final Node left, final Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
//Code to encrypt Data :
public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)
{
AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();
//Block size : Gets or sets the block size, in bits, of the cryptographic operation.
dataencrypt.BlockSize = 128;
//KeySize: Gets or sets the size, in bits, of the secret key
dataencrypt.KeySize = 128;
//Key: Gets or sets the symmetric key that is used for encryption and decryption.
dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
//IV : Gets or sets the initialization vector (IV) for the symmetric algorithm
dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
//Padding: Gets or sets the padding mode used in the symmetric algorithm
dataencrypt.Padding = PaddingMode.PKCS7;
//Mode: Gets or sets the mode for operation of the symmetric algorithm
dataencrypt.Mode = CipherMode.CBC;
//Creates a symmetric AES encryptor object using the current key and initialization vector (IV).
ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);
//TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.
//It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of
//information returned at the end might be larger than a single block when padding is added.
byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);
crypto1.Dispose();
//return the encrypted data
return encrypteddata;
}
//code to decrypt data
private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)
{
AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();
keydecrypt.BlockSize = 128;
keydecrypt.KeySize = 128;
keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);
keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);
keydecrypt.Padding = PaddingMode.PKCS7;
keydecrypt.Mode = CipherMode.CBC;
ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);
byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);
crypto1.Dispose();
return returnbytearray;
}
I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.
To make things quicker, you can use the flag "--table" like this:
php artisan make:migration add_paid_to_users --table="users"
This will add the up
and down
method content automatically:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
Similarily, you can use the --create["table_name"]
option when creating new migrations which will add more boilerplate to your migrations. Small point, but helpful when doing loads of them!
Should be:
curl --cert certificate_file.pem:password https://www.example.com/some_protected_page
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
This:
Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);
works fine for me.
Note that ConfigurationManager
is in the System.Configuration
namespace (so you'll likely want a using System.Configuration;
statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.
Also, be sure you set system.configuration.dll
as a reference in your project or build script.
There's also another way to do this-
select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;
Okay, since it already "leaked": You're missing zero, so the correct answer is 512
(511 is the greatest one, but it's 0 to 511, not 1 to 511).
By the way, an good followup exercise would be to generalize this:
How many different values can be represented in n binary digits (bits)?
After many years of success with the answers above, I have found this not to work again - but I did find a working solution for subplots at
https://jdhao.github.io/2017/06/03/change-aspect-ratio-in-mpl
With full credit of course to the author above (who can perhaps rather post here), the relevant lines are:
ratio = 1.0
xleft, xright = ax.get_xlim()
ybottom, ytop = ax.get_ylim()
ax.set_aspect(abs((xright-xleft)/(ybottom-ytop))*ratio)
The link also has a crystal clear explanation of the different coordinate systems used by matplotlib.
Thanks for all great answers received - especially @Yann's which will remain the winner.
If you don't like writing custom converter, you could use data triggers to solve this:
<Style.Triggers>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding YourBinaryOption}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.
To add the jar file to your project in Eclipse, do the following:
Simply You can use following methods.
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
// OR
client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
}
These methods are almost same as DownloadString(..) and DownloadStringAsync(...). They store the file in Directory rather than in C# string and no need of Format extension in URi
public void SaveImage(string filename, ImageFormat format)
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap; bitmap = new Bitmap(stream);
if (bitmap != null)
{
bitmap.Save(filename, format);
}
stream.Flush();
stream.Close();
client.Dispose();
}
try
{
SaveImage("--- Any Image Path ---", ImageFormat.Png)
}
catch(ExternalException)
{
// Something is wrong with Format -- Maybe required Format is not
// applicable here
}
catch(ArgumentNullException)
{
// Something wrong with Stream
}
You can use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:
// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
limit: 3,
layoutTemplate: '<ul class="inline">{entries}</ul>',
entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})
// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
document.querySelector("#your-div"),
"https://stackoverflow.com/feeds/question/10943544",
{
// options go here
}
);
rss.render().then(() => {
console.log('Everything is loaded and rendered');
});
See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.
Change the FragmentPagerAdapter
to FragmentStatePagerAdapter
.
Override getItemPosition()
method and return POSITION_NONE
.
Eventually, it will listen to the notifyDataSetChanged()
on view pager.
Code from Apache Commons Lang 3.4 (JavaDoc):
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
The difference with the other answers is that it uses autoFlush
on the PrintWriter
.
Edit: See cambunctious's answer, which is basically what I now prefer because it only uses the changes in the stash, rather than comparing them to your current state. This makes the operation additive, with much less chance of undoing work done since the stash was created.
To do it interactively, you would first do
git diff stash^! -- path/to/relevant/file/in/stash.ext perhaps/another/file.ext > my.patch
...then open the patch file in a text editor, alter as required, then do
git apply < my.patch
cambunctious's answer bypasses the interactivity by piping one command directly to the other, which is fine if you know you want all changes from the stash. You can edit the stash^!
to be any commit range that has the cumulative changes you want (but check over the output of the diff first).
If applying the patch/diff fails, you can change the last command to git apply --reject
which makes all the changes it can, and leaves .rej
files where there are conflicts it can;r resolve. The .rej
files can then be applied using wiggle
, like so:
wiggle --replace path/to/relevant/file/in/stash.ext path/to/relevant/file/in/stash.ext.rej
This will either resolve the conflict, or give you conflict markers that you'd get from a merge.
Previous solution: There is an easy way to get changes from any branch, including stashes:
$ git checkout --patch stash@{0} path/to/file
You may omit the file spec if you want to patch in many parts. Or omit patch (but not the path) to get all changes to a single file. Replace 0
with the stash number from git stash list
, if you have more than one. Note that this is like diff
, and offers to apply all differences between the branches. To get changes from only a single commit/stash, have a look at git cherry-pick --no-commit
.
I find out that, inside of your .css >if you set the display property of a div element to inline-block it fixes the problem. and margin will work as is expected.
var x = $(this).attr("name");
$("#" + x).hide();
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject]
or [JsonProperty]
.
There are predefined naming strategies like CamelCaseNamingStrategy
, but you can implement your own ones.
The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization
You can also use the FormData Objects; The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.
var formElement = document.getElementById("myform_id");
var formData = new FormData(formElement);
console.log(formData);
Note: ||= does not exist. (logical or) You can use
y= y || expr; // expr is NOT evaluated if y==true
or
y = expr ? true : y; // expr is always evaluated.
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType
(e.g., any List
), which is fromJson(JsonElement json, Type typeOfT)
.
In your case, you just need to get the Type
of a List<String>
and then parse the JSON array into that Type
, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
You may want to take a look at Gson API documentation.
The (very) short answer to your question is that paintComponent
is called "when it needs to be." Sometimes it's easier to think of the Java Swing GUI system as a "black-box," where much of the internals are handled without too much visibility.
There are a number of factors that determine when a component needs to be re-painted, ranging from moving, re-sizing, changing focus, being hidden by other frames, and so on and so forth. Many of these events are detected auto-magically, and paintComponent
is called internally when it is determined that that operation is necessary.
I've worked with Swing for many years, and I don't think I've ever called paintComponent
directly, or even seen it called directly from something else. The closest I've come is using the repaint()
methods to programmatically trigger a repaint of certain components (which I assume calls the correct paintComponent
methods downstream.
In my experience, paintComponent
is rarely directly overridden. I admit that there are custom rendering tasks that require such granularity, but Java Swing does offer a (fairly) robust set of JComponents and Layouts that can be used to do much of the heavy lifting without having to directly override paintComponent
. I guess my point here is to make sure that you can't do something with native JComponents and Layouts before you go off trying to roll your own custom-rendered components.
You can use (hidden) cells as variables. E.g., you could hide Column C, set C1 to
=20
and use it as
=c1*20
Alternatively you can write VBA Macros which set and read a global variable.
Edit: AKX renders my Answer partially incorrect. I had no idea you could name cells in Excel.
As mentioned in all other answers, the keyword continue
will skip to the end of the current iteration.
Additionally you can label your loop starts and then use continue [labelname];
or break [labelname];
to control what's going on in nested loops:
loop1: for (int i = 1; i < 10; i++) {
loop2: for (int j = 1; j < 10; j++) {
if (i + j == 10)
continue loop1;
System.out.print(j);
}
System.out.println();
}
document.getElementById('gadget_url').value = 'your value';
You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.
Just download the jar and import it into your classpath, or add it as a maven dependency:
<dependency>
<groupId>com.jtattoo</groupId>
<artifactId>JTattoo</artifactId>
<version>1.6.11</version>
</dependency>
Here is a list of some of the cool themes they have available:
Regards
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
In Android Studio, you can do like this:
For example, if you want to change com.example.app to iu.awesome.game, then:
Individually select each directory you want to rename, and:
Select Refactor
Click on Rename
In the Pop-up dialog, click on Rename Package instead of Rename Directory
Enter the new name and hit Refactor
Click Do Refactor in the bottom
Allow a minute to let Android Studio update all changes
Note: When renaming com in Android Studio, it might give a warning. In such case, select Rename All
Now open your Gradle Build File (build.gradle - Usually app or mobile). Update the applicationId in the defaultConfig to your new Package Name and Sync Gradle, if it hasn't already been updated automatically:
You may need to change the package= attribute in your manifest.
Clean and Rebuild.
Done! Anyway, Android Studio needs to make this process a little simpler.
Usually to use the library you need to install the dev version.
Try
sudo apt-get install libusb-1.0-0-dev
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);
[x for x in L if 'ab' in x]
Please find the below steps.
CMD + <
Run
option from left side.For more information please find the below GIF representation.
There are several ways to implement it:
For ASP.NET Standard CheckBox:
.tdInputCheckBox
{
position:relative;
top:-2px;
}
<table>
<tr>
<td class="tdInputCheckBox">
<asp:CheckBox ID="chkMale" runat="server" Text="Male" />
<asp:CheckBox ID="chkFemale" runat="server" Text="Female" />
</td>
</tr>
</table>
For DevExpress CheckBox:
<dx:ASPxCheckBox ID="chkAccept" runat="server" Text="Yes" Layout="Flow"/>
<dx:ASPxCheckBox ID="chkAccept" runat="server" Text="No" Layout="Flow"/>
For RadioButtonList:
<asp:RadioButtonList ID="rdoAccept" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
For Required Field Validators:
<asp:TextBox ID="txtEmailId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqEmailId" runat="server" ErrorMessage="Email id is required." Display="Dynamic" ControlToValidate="txtEmailId"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexEmailId" runat="server" ErrorMessage="Invalid Email Id." ControlToValidate="txtEmailId" Text="*"></asp:RegularExpressionValidator>`
#output a UTF-8 CSV in PHP that Excel will read properly.
//Use tab as field separator
$sep = "\t";
$eol = "\n";
$fputcsv = count($headings) ? '"'. implode('"'.$sep.'"', $headings).'"'.$eol : '';
I wrote this simple helper function:
#include <locale> // tolower
string to_lower(string s) {
for(char &c : s)
c = tolower(c);
return s;
}
Usage:
string s = "TEST";
cout << to_lower("HELLO WORLD"); // output: "hello word"
cout << to_lower(s); // won't change the original variable.
For those using the dict.get
technique for nested dictionaries, instead of explicitly checking for every level of the dictionary, or extending the dict
class, you can set the default return value to an empty dictionary except for the out-most level. Here's an example:
my_dict = {'level_1': {
'level_2': {
'level_3': 'more_data'
}
}
}
result = my_dict.get('level_1', {}).get('level_2', {}).get('level_3')
# result -> 'more_data'
none_result = my_dict.get('level_1', {}).get('what_level', {}).get('level_3')
# none_result -> None
WARNING: Please note that this technique only works if the expected key's value is a dictionary. If the key what_level
did exist in the dictionary but its value was a string or integer etc., then it would've raised an AttributeError
.
To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...
$(document).ready(function() {
$('#my-link').click(function(event){
alert('Hooray!');
event.preventDefault(); // Prevent link from following its href
});
});
Drive mapping to sharepoint (also https)
Getting sharepoint contents worked for me via the mapped drive iterating it as a filesystem object; trick is how to set up the mapping: Then copy path (line with http*) (see below)
Use this path in Map drive from explorer or command (i.e. net use N: https:://thepathyoujustcopied
)
Note: https works ok with windows7/8, not with XP.
That may work for you, but I prefer a different approach as drive letters are different on each pc. The trick here is to start from sharepoint (and not from a VBA script accessing sharepoint as a web server).
Set up a data connection to excel sheet
You can either include this query in vba, or maintain the database link in your speadsheet, iterating over the table by VBA. Please note: the image above does not show the actual database connection (command text), which would tell you how to access my sharepoint.
font-weight: bold;
The code worked for me was as follows
ng serve --port ABCD
For Example
ng serve --port 6300
Always use double quotes when using a variable inside a string and backslash any other double quotes except the starting and ending ones. You could also use the brackets like below so it's easier to find your variables inside the strings and make them look cleaner.
$var = 'my variable';
echo "I love ${var}";
or
$var = 'my variable';
echo "I love {$var}";
Above would return the following: I love my variable
If you want to perform this all operation with C programming in the Linux kernel then I suggest to use standard APIs of the Linux kernel.
See https://www.kernel.org/doc/htmldocs/kernel-api/ch02s03.html
set_bit Atomically set a bit in memory
clear_bit Clears a bit in memory
change_bit Toggle a bit in memory
test_and_set_bit Set a bit and return its old value
test_and_clear_bit Clear a bit and return its old value
test_and_change_bit Change a bit and return its old value
test_bit Determine whether a bit is set
Note: Here the whole operation happens in a single step. So these all are guaranteed to be atomic even on SMP computers and are useful to keep coherence across processors.
This is how I fixed this issue on Windows 10:
My JDK is located in C:\Program Files\Java\jdk-11.0.2
and the problem I had was the space in Program Files
. If I set JAVA_HOME using set JAVA_HOME="C:\Program Files\Java\jdk-11.0.2"
then Maven had an issue with the double quotes:
C:\Users>set JAVA_HOME="C:\Program Files\Java\jdk-11.0.2"
C:\Users>echo %JAVA_HOME%
"C:\Program Files\Java\jdk-11.0.2"
C:\Users>mvn -version
Files\Java\jdk-11.0.2""=="" was unexpected at this time.
Referring to Program Files
as PROGRA~1
didn't help either. The solution is using the PROGRAMFILES variable inside of JAVA_HOME:
C:\Users>echo %PROGRAMFILES%
C:\Program Files
C:\Program Files>set JAVA_HOME=%PROGRAMFILES%\Java\jdk-11.0.2
C:\Program Files>echo %JAVA_HOME%
C:\Program Files\Java\jdk-11.0.2
C:\Program Files>mvn -version
Apache Maven 3.6.2 (40f52333136460af0dc0d7232c0dc0bcf0d9e117; 2019-08-27T17:06:16+02:00)
Maven home: C:\apache-maven-3.6.2\bin\..
Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-11.0.2
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
If you know the ID's rather than the strings, use this approach:
where mylookuptablecolumn IN (myarrayorcommadelimitedarray)
Just make sure that myarrayorcommadelimitedarray is not put in string quotes.
works if you want A OR B, but not AND.
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
First I would recommend you always refer docs before you start a new thing.
We have SchedulerFactory
which schedules Job based on the Cron Expression given to it.
//Create instance of factory
SchedulerFactory schedulerFactory=new StdSchedulerFactory();
//Get schedular
Scheduler scheduler= schedulerFactory.getScheduler();
//Create JobDetail object specifying which Job you want to execute
JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);
//Associate Trigger to the Job
CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");
//Pass JobDetail and trigger dependencies to schedular
scheduler.scheduleJob(jobDetail,trigger);
//Start schedular
scheduler.start();
MyJob.class
public class MyJob implements Job{
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("My Logic");
}
}
Congrats to the previous answers... But I realised if the icons are in a row (say three icons as represented in the image above), you need to play around with columns and rows.
Here is the code
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlatButton(
onPressed: () {},
child: Icon(
Icons.call,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.message,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.block,
color: Colors.red,
)),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
' Call',
),
Text(
'Message',
),
Text(
'Block',
style: TextStyle(letterSpacing: 2.0, color: Colors.red),
),
],
),
],
),
The issue isn't with the button, the issue is with the div
. As div
s are block elements, they default to occupying the full width of their parent element (as a general rule; I'm pretty sure there are some exceptions if you're messing around with different positioning schemes in one document that would cause it to occupy the full width of a higher element in the hierarchy).
Anyway, try adding float: left;
to the rules for the .button
selector. That will cause the div
with class button
to fit around the button, and would allow you to have multiple floated div
s on the same line if you wanted more div.button
s.
I strongly recommend that you not define your own scheme. This goes against the web standards for URI schemes, which attempts to rigidly control those names for good reason -- to avoid name conflicts between different entities. Once you put a link to your scheme on a web site, you have put that little name into entire the entire Internet's namespace, and should be following those standards.
If you just want to be able to have a link to your own app, I recommend you follow the approach I described here:
Version .NET Framework Visual Studio Important Features
C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002
Basic features
C# 2.0 .NET Framework 2.0 Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Private setters (properties)
Method group conversions (delegates)
Covariance and Contra-variance
Static classes
C# 3.0 .NET Framework 3.0\3.5 Visual Studio 2008
Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expressions
Expression trees
Partial Methods
C# 4.0 .NET Framework 4.0 Visual Studio 2010
Dynamic binding (late binding)
Named and optional arguments
Generic co- and contravariance
Embedded interop types
C# 5.0 .NET Framework 4.5 Visual Studio 2012/2013
Async features
Caller information
C# 6.0 .NET Framework 4.6 Visual Studio 2013/2015
Expression Bodied Methods
Auto-property initializer
nameof Expression
Primary constructor
Await in catch block
Exception Filter
String Interpolation
C# 7.0 .NET Core 2.0 Visual Studio 2017
out variables
Tuples
Discards
Pattern Matching
Local functions
Generalized async return types
Numeric literal syntax improvements
C# 8.0 .NET Core 3.0 Visual Studio 2019
Readonly members
Default interface methods
Pattern matching enhancements:
Switch expressions
Property patterns
Tuple patterns
Positional patterns
Using declarations
Static local functions
Disposable ref structs
Nullable reference types
Asynchronous streams
Asynchronous disposable
Indices and ranges
Null-coalescing assignment
Unmanaged constructed types
Stackalloc in nested expressions
Enhancement of interpolated verbatim strings
I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.
http://jsfiddle.net/pdXRx/297/
<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>
<h2>Modified behaviors</h2>
<!-- To get simulated placeholder with New Lines behavior,
add the placeholdernl attribute -->
<textarea placeholdernl> (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea placeholder='Address' placeholdernl> (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<h2>Standard behaviors</h2>
<textarea placeholder='Address'> (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea> (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>
<textarea placeholder='Address'></textarea>
The javascript is very simple
<script>
(function($){
var handleFocus = function(){
var $this = $(this);
if($this.val() === $this.attr('placeholdernl')){
$this.attr('value', '');
$this.css('color', '');
}
};
var handleBlur = function(){
var $this = $(this);
if($this.val() == ''){
$this.attr('value', $this.attr('placeholdernl'))
$this.css('color', 'gray');
}
};
$('textarea[placeholdernl]').each(function(){
var $this = $(this),
value = $this.attr('value'),
placeholder = $this.attr('placeholder');
$this.attr('placeholdernl', value ? value : placeholder);
$this.attr('value', '');
$this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>
After a long Google, I came to know that javac.exe will be inside JDK(C:\Program Files\Java\jdk(version number)\bin) not inside JRE (C:\Program Files (x86)\Java\jre7\bin) "JRE doesn't come with a compiler. It(JRE) is simply a java runtime environment. What you need is the Java development kit." in order to use compiler javac
javac will not work if you are pointing bin inside jre
In order to use javac in cmd , JDK must be installed in your system...
For javac path
path = C:\Program Files (x86)\Java\jre7\bin this is wrong
path = C:\Program Files\Java\jdk(version number)\bin this is correct
Make sure that "javac.exe" is inside your "C:\Program Files\Java\jdk(version number)\bin"
Don't get confused with JRE and JDK both are totally different
if you don't have JDK pls download from this link
or
http://www.oracle.com/technetwork/java/javase/downloads/index.html
reference thread for JDK VS JRE What is the difference between JDK and JRE?
We don't need to plt.ioff()
or plt.show()
(if we use %matplotlib inline
). You can test above code without plt.ioff()
. plt.close()
has the essential role. Try this one:
%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2)
to the end of it, you will see nothing.
In conclusion, if you close figure by plt.close(fig)
, it won't be displayed.
It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.
Add disabled Class in your anchor, following are js:
$('.navbar .dropdown-toggle').hover(function() {
$(this).addClass('disabled');
});
But this is not mobile friendly so you need to remove disabled class for mobile, so updated js code is following:
$('.navbar .dropdown-toggle').hover(function() {
if (document.documentElement.clientWidth > 769) { $(this).addClass('disabled');}
else { $(this).removeClass('disabled'); }
});
For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter
definition, e.g.:
private static DateTimeFormatter DATE_FORMAT =
new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
One should set the optional fields if they will appear. And the rest of code should be exactly the same.
Using @angular/forms
when you use a <form>
tag it automatically creates a FormGroup
.
For every contained ngModel
tagged <input>
it will create a FormControl
and add it into the FormGroup
created above; this FormControl
will be named into the FormGroup
using attribute name
.
Example:
<form #f="ngForm">
<input type="text" [(ngModel)]="firstFieldVariable" name="firstField">
<span>{{ f.controls['firstField']?.value }}</span>
</form>
Said this, the answer to your question follows.
When you mark it as standalone: true
this will not happen (it will not be added to the FormGroup
).
Reference: https://github.com/angular/angular/issues/9230#issuecomment-228116474
First what you have to do, before changing web.xml is to make sure your ManagedBean implements Serializable
:
@ManagedBean
@ViewScoped
public class Login implements Serializable {
}
Especially if you use MyFaces
We can use elasticdump to take the backup and restore it, We can move data from one server/cluster to another server/cluster.
1. Commands to move one index data from one server/cluster to another using elasticdump
.
# Copy an index from production to staging with analyzer and mapping:
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=http://staging.es.com:9200/my_index \
--type=analyzer
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=http://staging.es.com:9200/my_index \
--type=mapping
elasticdump \
--input=http://production.es.com:9200/my_index \
--output=http://staging.es.com:9200/my_index \
--type=data
2. Commands to move all indices data from one server/cluster to another using multielasticdump
.
Backup
multielasticdump \
--direction=dump \
--match='^.*$' \
--limit=10000 \
--input=http://production.es.com:9200 \
--output=/tmp
Restore
multielasticdump \
--direction=load \
--match='^.*$' \
--limit=10000 \
--input=/tmp \
--output=http://staging.es.com:9200
Note:
If the --direction is dump, which is the default, --input MUST be a URL for the base location of an ElasticSearch server (i.e. http://localhost:9200) and --output MUST be a directory. Each index that does match will have a data, mapping, and analyzer file created.
For loading files that you have dumped from multi-elasticsearch, --direction should be set to load, --input MUST be a directory of a multielasticsearch dump and --output MUST be a Elasticsearch server URL.
The 2nd command will take a backup of settings
, mappings
, template
and data
itself as JSON files.
The --limit
should not be more than 10000
otherwise, it will give an exception.
If you are like me and don't always retrieve the axes, ax
, when plotting the figure, then a simple solution would be to do
plt.xticks([])
plt.yticks([])
Try doing a complete clean of the target/deployment directory for the app to get rid of any stale library jars. Make a fresh build and check that commons-logging.jar is actually being placed in the correct lib folder. It might not be included when you are building the library for the application.
Depending on your applications (and especially if you're already using boost), you might want to look into boost::optional
.
(UPDATE: As of C++17, optional is now part of the standard library, as std::optional
)
It has the property you are looking for, tracking whether the slot actually holds a value or not. By default it is constructed to not hold a value and evaluate to false, but if it evaluates to true you are allowed to dereference it and get the wrapped value.
class MyClass
{
void SomeMethod();
optional<char> mCharacter;
optional<double> mDecimal;
};
void MyClass::SomeMethod()
{
if ( mCharacter )
{
// do something with *mCharacter.
// (note you must use the dereference operator)
}
if ( ! mDecimal )
{
// call mDecimal.reset(expression)
// (this is how you assign an optional)
}
}
More examples are in the Boost documentation.
First of all, you should use none of them. You are using wrapper
type, which should rarely be used in case you have a primitive type.
So, you should use boolean
rather.
Further, we initialize the boolean
variable to false
to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false
.
But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.
But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default
value.
So, in your case I would use it like this: -
boolean isMatch = email1.equals (email2);
Do you mean like this?
import string
astr='a(b[c])d'
deleter=string.maketrans('()[]',' ')
print(astr.translate(deleter))
# a b c d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a
Using Spark Sql 2.4.0 you can do that:
spark.sql("SELECT STRING(NULLIF(column,'')) as column_string")
In my case $1 was not working, but $0 works fine for my purpose.
In this case I was trying to replace strings with the correct format to translate them in Laravel, I hope this could be useful to someone else because it took me a while to sort it out!
Search: (?<=<div>).*?(?=</div>)
Replace: {{ __('$0') }}
I'm not using different versions of libraries and got the same error, it's happened after remove buildToolsVersion
in AS RC 1, but adding tools:node="replace"
did the trick, just add this into your manifest.xml inside <application ..../>
block:
<meta-data
tools:node="replace"
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;
Where DBName is your database name.
Based on link you've provided, right answer should be
Math.floor(Math.random()*899999+100000);
Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)
While viewWillAppear()
and viewDidDisappear()
are called when the back button is tapped, they are also called at other times. See end of answer for more on that.
Detecting the back button is better done when the VC is removed from it's parent (the NavigationController) with the help of willMoveToParentViewController(_:)
OR didMoveToParentViewController()
If parent is nil, the view controller is being popped off the navigation stack and dismissed. If parent is not nil, it is being added to the stack and presented.
// Objective-C
-(void)willMoveToParentViewController:(UIViewController *)parent {
[super willMoveToParentViewController:parent];
if (!parent){
// The back button was pressed or interactive gesture used
}
}
// Swift
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if parent == nil {
// The back button was pressed or interactive gesture used
}
}
Swap out willMove
for didMove
and check self.parent to do work after the view controller is dismissed.
Do note, checking the parent doesn't allow you to "pause" the transition if you need to do some sort of async save. To do that you could implement the following. Only downside here is you lose the fancy iOS styled/animated back button. Also be careful here with the interactive swipe gesture. Use the following to handle this case.
var backButton : UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Disable the swipe to make sure you get your chance to save
self.navigationController?.interactivePopGestureRecognizer.enabled = false
// Replace the default back button
self.navigationItem.setHidesBackButton(true, animated: false)
self.backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
self.navigationItem.leftBarButtonItem = backButton
}
// Then handle the button selection
func goBack() {
// Here we just remove the back button, you could also disabled it or better yet show an activityIndicator
self.navigationItem.leftBarButtonItem = nil
someData.saveInBackground { (success, error) -> Void in
if success {
self.navigationController?.popViewControllerAnimated(true)
// Don't forget to re-enable the interactive gesture
self.navigationController?.interactivePopGestureRecognizer.enabled = true
}
else {
self.navigationItem.leftBarButtonItem = self.backButton
// Handle the error
}
}
}
If you didn't get the viewWillAppear
viewDidDisappear
issue, Let's run through an example. Say you have three view controllers:
Lets follow the calls on the detailVC
as you go from the listVC
to settingsVC
and back to listVC
List > Detail (push detailVC) Detail.viewDidAppear
<- appear
Detail > Settings (push settingsVC) Detail.viewDidDisappear
<- disappear
And as we go back...
Settings > Detail (pop settingsVC) Detail.viewDidAppear
<- appear
Detail > List (pop detailVC) Detail.viewDidDisappear
<- disappear
Notice that viewDidDisappear
is called multiple times, not only when going back, but also when going forward. For a quick operation that may be desired, but for a more complex operation like a network call to save, it may not.
Check out the cross platform PyMouse: https://github.com/pepijndevos/PyMouse/
I don't know the real reason but Maven pushes developers to install all libraries (custom too) into some maven repositories, so scope:system
is not well liked, A simple workaround is to use maven-install-plugin
follow the usage:
write your dependency in this way
<dependency>
<groupId>com.mylib</groupId>
<artifactId>mylib-core</artifactId>
<version>0.0.1</version>
</dependency>
then, add maven-install-plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<executions>
<execution>
<id>install-external</id>
<phase>clean</phase>
<configuration>
<file>${basedir}/lib/mylib-core-0.0.1.jar</file>
<repositoryLayout>default</repositoryLayout>
<groupId>com.mylib</groupId>
<artifactId>mylib-core</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
<goals>
<goal>install-file</goal>
</goals>
</execution>
</executions>
</plugin>
pay attention to phase:clean
, to install your custom library into your repository, you have to run mvn clean
and then mvn install
The default generator for Windows seems to be set to NMAKE. Try to use:
cmake -G "MinGW Makefiles"
Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.
The simplest solution is :
listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setStackFromBottom(true);
After trying the filter approach without success (it did for some reason not enter the doFilter() function) I changed my setup a bit and found a very simple solution for the root serving problem:
Instead of serving " / * " in my main Servlet, I now only listen to dedicated language prefixes "EN", "EN/ *", "DE", "DE/ *"
Static content gets served by the default Servlet and the empty root requests go to the index.jsp which calls up my main Servlet with the default language:
< jsp:include page="/EN/" /> (no other content on the index page.)
Use the echo
command:
var="text to append";
destdir=/some/directory/path/filename
if [ -f "$destdir" ]
then
echo "$var" > "$destdir"
fi
The if
tests that $destdir
represents a file.
The >
appends the text after truncating the file. If you only want to append the text in $var
to the file existing contents, then use >>
instead:
echo "$var" >> "$destdir"
The cp
command is used for copying files (to files), not for writing text to a file.
The MOUSEBUTTONDOWN
event occurs once when you click the mouse button and the MOUSEBUTTONUP
event occurs once when the mouse button is released. The pygame.event.Event()
object has two attributes that provide information about the mouse event. pos
is a tuple that stores the position that was clicked. button
stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event
.
Use the rect
attribute of the pygame.sprite.Sprite
object and the collidepoint
method to see if the Sprite was clicked.
Pass the list of events to the update
method of the pygame.sprite.Group
so that you can process the events in the Sprite class:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseClick
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.click_image, color, (25, 25), 25)
pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.clicked = False
def update(self, event_list):
for event in event_list:
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.clicked = not self.clicked
self.image = self.click_image if self.clicked else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT:
run = False
group.update(event_list)
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
See further Creating multiple sprites with different update()'s from the same sprite class in Pygame
The current position of the mouse can be determined via pygame.mouse.get_pos()
. The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed()
returns a list of Boolean values ??that represent the state (True
or False
) of all mouse buttons. The state of a button is True
as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True
. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.
Detect evaluate the mouse states in the Update
method of the pygame.sprite.Sprite
object:
class SpriteObject(pygame.sprite.Sprite):
# [...]
def update(self, event_list):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
if self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
# [...]
my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update(event_list)
# [...]
Minimal example: repl.it/@Rabbid76/PyGame-MouseHover
import pygame
class SpriteObject(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.original_image, color, (25, 25), 25)
self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.hover_image, color, (25, 25), 25)
pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
self.image = self.original_image
self.rect = self.image.get_rect(center = (x, y))
self.hover = False
def update(self):
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
#self.hover = self.rect.collidepoint(mouse_pos)
self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)
self.image = self.hover_image if self.hover else self.original_image
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
group.update()
window.fill(0)
group.draw(window)
pygame.display.flip()
pygame.quit()
exit()
Cancelling Angular $http Ajax with the timeout property doesn't work in Angular 1.3.15. For those that cannot wait for this to be fixed I'm sharing a jQuery Ajax solution wrapped in Angular.
The solution involves two services:
Here goes the PendingRequestsService service:
(function (angular) {
'use strict';
var app = angular.module('app');
app.service('PendingRequestsService', ["$log", function ($log) {
var $this = this;
var pending = [];
$this.add = function (request) {
pending.push(request);
};
$this.remove = function (request) {
pending = _.filter(pending, function (p) {
return p.url !== request;
});
};
$this.cancelAll = function () {
angular.forEach(pending, function (p) {
p.xhr.abort();
p.deferred.reject();
});
pending.length = 0;
};
}]);})(window.angular);
The HttpService service:
(function (angular) {
'use strict';
var app = angular.module('app');
app.service('HttpService', ['$http', '$q', "$log", 'PendingRequestsService', function ($http, $q, $log, pendingRequests) {
this.post = function (url, params) {
var deferred = $q.defer();
var xhr = $.ASI.callMethod({
url: url,
data: params,
error: function() {
$log.log("ajax error");
}
});
pendingRequests.add({
url: url,
xhr: xhr,
deferred: deferred
});
xhr.done(function (data, textStatus, jqXhr) {
deferred.resolve(data);
})
.fail(function (jqXhr, textStatus, errorThrown) {
deferred.reject(errorThrown);
}).always(function (dataOrjqXhr, textStatus, jqXhrErrorThrown) {
//Once a request has failed or succeeded, remove it from the pending list
pendingRequests.remove(url);
});
return deferred.promise;
}
}]);
})(window.angular);
Later in your service when you are loading data you would use the HttpService instead of $http:
(function (angular) {
angular.module('app').service('dataService', ["HttpService", function (httpService) {
this.getResources = function (params) {
return httpService.post('/serverMethod', { param: params });
};
}]);
})(window.angular);
Later in your code you would like to load the data:
(function (angular) {
var app = angular.module('app');
app.controller('YourController', ["DataService", "PendingRequestsService", function (httpService, pendingRequestsService) {
dataService
.getResources(params)
.then(function (data) {
// do stuff
});
...
// later that day cancel requests
pendingRequestsService.cancelAll();
}]);
})(window.angular);
You should set the option:
local-infile=1
into your [mysql] entry of my.cnf file or call mysql client with the --local-infile option:
mysql --local-infile -uroot -pyourpwd yourdbname
You have to be sure that the same parameter is defined into your [mysqld] section too to enable the "local infile" feature server side.
It's a security restriction.
LOAD DATA LOCAL INFILE '/softwares/data/data.csv' INTO TABLE tableName;
A javascript method to disable the button itself
document.getElementById("ID NAME").disabled = true;
Once all form fields have satisfied your criteria, you can re-enable the button
Using a Jquery will be something like this
$( "#ID NAME" ).prop( "disabled", true);
I got this error when my directory path is incorrect, ensure your directory names and path are correct
If you are designing your Javafx application using SceneBuilder
then use -fx-text-fill
(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield
.
I came here for the same problem and solved it in this way.
you can use imageEdgeInsets
property
The inset or outset margins for the rectangle around the button’s image.
[self.btn setImageEdgeInsets:UIEdgeInsetsMake(6, 6, 6, 6)];
A positive value shrinks, or insets, that edge—moving. A negative value expands, or outsets, that edge.
This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.
In this case, tester method needs to have access to Class, and you can construct
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, Foo.class)
and then
List<Foo> list = mapper.readValue(new File("input.json"), type);
Installing psqlODBC on 64bit Windows
Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.
How to configure 32 bit ODBC drivers on Win x64
Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe
%SystemRoot%\syswow64\odbcad32.exe
You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.
We use JavaCSV, it works pretty well
The simplest solution to this problem is that you just need to use \"
for space separated arguments when running a shell script:
#!/bin/bash
myFunction() {
echo $1
echo $2
echo $3
}
myFunction "firstString" "\"Hello World\"" "thirdString"
Parentheses do not create a tuple. aka one = (two) is not a tuple. The only way around is either one = (two,) or one = tuple(two). So a solution is:
tuple(i for i in myothertupleorlistordict)
I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):
reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"
I find this easier than using Registry Editor but that's solely a personal preference.
The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.
I know it is a pointed question, and the op wanted to load different properties file.
My answer is, doing custom hacks like this is a terrible idea.
If you are using spring-boot with a cloud provider such as cloud foundry, please do yourself a favor and use cloud config services
https://spring.io/projects/spring-cloud-config
It loads and merges default/dev/project-default/project-dev specific properties like magic
Again, Spring boot already gives you enough ways to do this right https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Please do not re-invent the wheel.
As @Pascal said, it is likely that you encounter problem with the firewall or/and proxy issue. As a first step, go through FAQ on the CRAN web page. After that, try to flag R with --internet2.
Sometimes it could be useful to check global options in R studio and uncheck "Use Internet Explorer library/proxy for HTTP". Tools -> Global Options -> Packages and unchecking the "Use Internet Explorer library/proxy for HTTP" option.
Hope this helps.