I just leave my solution here.
import csv
import numpy as np
with open(name, newline='') as f:
reader = csv.reader(f, delimiter=",")
# skip header
next(reader)
# convert csv to list and then to np.array
data = np.array(list(reader))[:, 1:] # skip the first column
print(data.shape) # => (N, 2)
# sum each row
s = data.sum(axis=1)
print(s.shape) # => (N,)
This change worked for me:
// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width;
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);
In the case of winforms:
If you include the images to your resources you can do it like this, very simple and straight forward:
public Form1()
{
InitializeComponent();
button1.MouseEnter += new EventHandler(button1_MouseEnter);
button1.MouseLeave += new EventHandler(button1_MouseLeave);
}
void button1_MouseLeave(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
void button1_MouseEnter(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
I would not recommend hardcoding image paths.
As you have altered your question ...
There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :
in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover);
button1.MouseMove += new MouseEventHandler(button1_MouseMove);
void button1_MouseMove(object sender, MouseEventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
void button1_MouseHover(object sender, EventArgs e)
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
To add images to your resources: Projectproperties/resources/add/existing file
None of the above worked for me for some reason :/, so I added an element ref to a top element in app.component.html
, and (activate)=onNavigate($event)
to the router-outlet
.
<!--app.component.html-->
<div #topScrollAnchor></div>
<app-navbar></app-navbar>
<router-outlet (activate)="onNavigate($event)"></router-outlet>
Then I added the child to the app.component.ts file to the type of ElementRef
, and had it scroll to it on activation of the router-outlet.
export class AppComponent {
@ViewChild('topScrollAnchor') topScroll: ElementRef;
onNavigate(event): any {
this.topScroll.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
Here's the code in stackblitz
C-style casts conflate const_cast, static_cast, and reinterpret_cast.
I wish C++ didn't have C-style casts. C++ casts stand out properly (as they should; casts are normally indicative of doing something bad) and properly distinguish between the different kinds of conversion that casts perform. They also permit similar-looking functions to be written, e.g. boost::lexical_cast, which is quite nice from a consistency perspective.
It's a matter of making the tests expressive. I set expectations on a Mock if I want the test to describe a relationship between two objects. I stub return values if I'm setting up a supporting object to get me to the interesting behaviour in the test.
a = "MandY"
alow = a.lower()
if "mandy" in alow:
print "true"
work around
I've had this issue in 2 computers in my house using Windows 10 each. The problem began when i had to change few Environmental variables for projects that I've been working on Visual studio 2017 etc. After few months coming back to using node js and npm I had this issue again and non of the solutions above helped. I saw Sean's comment on Yar's solution and i mixed both solutions: 1) at the environmental variables window i had one extra variable that held this value: %APPDATA%\npm. I deleted it and the problem dissapeared!
Here's a way I am doing database restore from production to development:
NOTE: I am doing it via SSAS job to push production database to development daily:
Step1: Delete previous day backup in development:
declare @sql varchar(1024);
set @sql = 'DEL C:\ProdAEandAEXdataBACKUP\AE11.bak'
exec master..xp_cmdshell @sql
Step2: Copy production database to development:
declare @cmdstring varchar(1000)
set @cmdstring = 'copy \\Share\SQLDBBackup\AE11.bak C:\ProdAEandAEXdataBACKUP'
exec master..xp_cmdshell @cmdstring
Step3: Restore by running .sql script
SQLCMD -E -S dev-erpdata1 -b -i "C:\ProdAEandAEXdataBACKUP\AE11_Restore.sql"
Code that is within AE11_Restore.sql file:
RESTORE DATABASE AE11
FROM DISK = N'C:\ProdAEandAEXdataBACKUP\AE11.bak'
WITH MOVE 'AE11' TO 'E:\SQL_DATA\AE11.mdf',
MOVE 'AE11_log' TO 'D:\SQL_LOGS\AE11.ldf',
RECOVERY;
BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.
Example:
[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)
The BindModel
function gets called three times, bombing on the first, as it tries to bind the JSON to customerId
with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.
I added this block of code to the top of BindModel
:
if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
return base.BindModel(controllerContext, bindingContext);
}
The ValueProvider, fortunately, has route values figured out by the time it gets to this method.
If the first segment doesn't start with /
it is a relative route. router.navigate
needs a relativeTo
parameter for relative navigation
Either you make the route absolute:
this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)
or you pass relativeTo
this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})
See also
There are very often relative date/time related questions to solve with batch file. But command line interpreter cmd.exe has no function for date/time calculations. Lots of good working solutions using additional console applications or scripts have been posted already here, on other pages of Stack Overflow and on other websites.
Common for operations based on date/time is the requirement to convert a date/time string to seconds since a determined day. Very common is 1970-01-01 00:00:00 UTC. But any later day could be also used depending on the date range required to support for a specific task.
Jay posted 7daysclean.cmd containing a fast "date to seconds" solution for command line interpreter cmd.exe. But it does not take leap years correct into account. J.R. posted an add-on for taking leap day in current year into account, but ignoring the other leap years since base year, i.e. since 1970.
I use since 20 years static tables (arrays) created once with a small C function for quickly getting the number of days including leap days from 1970-01-01 in date/time conversion functions in my applications written in C/C++.
This very fast table method can be used also in batch code using FOR command. So I decided to code the batch subroutine GetSeconds
which calculates the number of seconds since 1970-01-01 00:00:00 UTC for a date/time string passed to this routine.
Note: Leap seconds are not taken into account as the Windows file systems also do not support leap seconds.
First, the tables:
Days since 1970-01-01 00:00:00 UTC for each year including leap days.
1970 - 1979: 0 365 730 1096 1461 1826 2191 2557 2922 3287
1980 - 1989: 3652 4018 4383 4748 5113 5479 5844 6209 6574 6940
1990 - 1999: 7305 7670 8035 8401 8766 9131 9496 9862 10227 10592
2000 - 2009: 10957 11323 11688 12053 12418 12784 13149 13514 13879 14245
2010 - 2019: 14610 14975 15340 15706 16071 16436 16801 17167 17532 17897
2020 - 2029: 18262 18628 18993 19358 19723 20089 20454 20819 21184 21550
2030 - 2039: 21915 22280 22645 23011 23376 23741 24106 24472 24837 25202
2040 - 2049: 25567 25933 26298 26663 27028 27394 27759 28124 28489 28855
2050 - 2059: 29220 29585 29950 30316 30681 31046 31411 31777 32142 32507
2060 - 2069: 32872 33238 33603 33968 34333 34699 35064 35429 35794 36160
2070 - 2079: 36525 36890 37255 37621 37986 38351 38716 39082 39447 39812
2080 - 2089: 40177 40543 40908 41273 41638 42004 42369 42734 43099 43465
2090 - 2099: 43830 44195 44560 44926 45291 45656 46021 46387 46752 47117
2100 - 2106: 47482 47847 48212 48577 48942 49308 49673
Calculating the seconds for year 2039 to 2106 with epoch beginning 1970-01-01 is only possible with using an unsigned 32-bit variable, i.e. unsigned long (or unsigned int) in C/C++.
But cmd.exe use for mathematical expressions a signed 32-bit variable. Therefore the maximum value is 2147483647 (0x7FFFFFFF) which is 2038-01-19 03:14:07.
Leap year information (No/Yes) for the years 1970 to 2106.
1970 - 1989: N N Y N N N Y N N N Y N N N Y N N N Y N
1990 - 2009: N N Y N N N Y N N N Y N N N Y N N N Y N
2010 - 2029: N N Y N N N Y N N N Y N N N Y N N N Y N
2030 - 2049: N N Y N N N Y N N N Y N N N Y N N N Y N
2050 - 2069: N N Y N N N Y N N N Y N N N Y N N N Y N
2070 - 2089: N N Y N N N Y N N N Y N N N Y N N N Y N
2090 - 2106: N N Y N N N Y N N N N N N N Y N N
^ year 2100
Number of days to first day of each month in current year.
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Year with 365 days: 0 31 59 90 120 151 181 212 243 273 304 334
Year with 366 days: 0 31 60 91 121 152 182 213 244 274 305 335
Converting a date to number of seconds since 1970-01-01 is quite easy using those tables.
Attention please!
The format of date and time strings depends on Windows region and language settings. The delimiters and the order of tokens assigned to the environment variables Day
, Month
and Year
in first FOR loop of GetSeconds
must be adapted to local date/time format if necessary.
It is necessary to adapt the date string of the environment variable if date format in environment variable DATE is different to date format used by command FOR on %%~tF
.
For example when %DATE%
expands to Sun 02/08/2015
while %%~tF
expands to 02/08/2015 07:38 PM
the code below can be used with modifying line 4 to:
call :GetSeconds "%DATE:~4% %TIME%"
This results in passing to subroutine just 02/08/2015
- the date string without the 3 letters of weekday abbreviation and the separating space character.
Alternatively following could be used to pass current date in correct format:
call :GetSeconds "%DATE:~-10% %TIME%"
Now the last 10 characters from date string are passed to function GetSeconds
and therefore it does not matter if date string of environment variable DATE is with or without weekday as long as day and month are always with 2 digits in expected order, i.e. in format dd/mm/yyyy
or dd.mm.yyyy
.
Here is the batch code with explaining comments which just outputs which file to delete and which file to keep in C:\Temp
folder tree, see code of first FOR loop.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Get seconds since 1970-01-01 for current date and time.
call :GetSeconds "%DATE% %TIME%"
rem Subtract seconds for 7 days from seconds value.
set /A "LastWeek=Seconds-7*86400"
rem For each file in each subdirectory of C:\Temp get last modification date
rem (without seconds -> append second 0) and determine the number of seconds
rem since 1970-01-01 for this date/time. The file can be deleted if seconds
rem value is lower than the value calculated above.
for /F "delims=" %%# in ('dir /A-D-H-S /B /S "C:\Temp"') do (
call :GetSeconds "%%~t#:0"
set "FullFileName=%%#"
setlocal EnableDelayedExpansion
rem if !Seconds! LSS %LastWeek% del /F "!FullFileName!"
if !Seconds! LEQ %LastWeek% (
echo Delete "!FullFileName!"
) else (
echo Keep "!FullFileName!"
)
endlocal
)
endlocal
goto :EOF
rem No validation is made for best performance. So make sure that date
rem and hour in string is in a format supported by the code below like
rem MM/DD/YYYY hh:mm:ss or M/D/YYYY h:m:s for English US date/time.
:GetSeconds
rem If there is " AM" or " PM" in time string because of using 12 hour
rem time format, remove those 2 strings and in case of " PM" remember
rem that 12 hours must be added to the hour depending on hour value.
set "DateTime=%~1"
set "Add12Hours=0"
if not "%DateTime: AM=%" == "%DateTime%" (
set "DateTime=%DateTime: AM=%"
) else if not "%DateTime: PM=%" == "%DateTime%" (
set "DateTime=%DateTime: PM=%"
set "Add12Hours=1"
)
rem Get year, month, day, hour, minute and second from first parameter.
for /F "tokens=1-6 delims=,-./: " %%A in ("%DateTime%") do (
rem For English US date MM/DD/YYYY or M/D/YYYY
set "Day=%%B" & set "Month=%%A" & set "Year=%%C"
rem For German date DD.MM.YYYY or English UK date DD/MM/YYYY
rem set "Day=%%A" & set "Month=%%B" & set "Year=%%C"
set "Hour=%%D" & set "Minute=%%E" & set "Second=%%F"
)
rem echo Date/time is: %Year%-%Month%-%Day% %Hour%:%Minute%:%Second%
rem Remove leading zeros from the date/time values or calculation could be wrong.
if "%Month:~0,1%" == "0" if not "%Month:~1%" == "" set "Month=%Month:~1%"
if "%Day:~0,1%" == "0" if not "%Day:~1%" == "" set "Day=%Day:~1%"
if "%Hour:~0,1%" == "0" if not "%Hour:~1%" == "" set "Hour=%Hour:~1%"
if "%Minute:~0,1%" == "0" if not "%Minute:~1%" == "" set "Minute=%Minute:~1%"
if "%Second:~0,1%" == "0" if not "%Second:~1%" == "" set "Second=%Second:~1%"
rem Add 12 hours for time range 01:00:00 PM to 11:59:59 PM,
rem but keep the hour as is for 12:00:00 PM to 12:59:59 PM.
if %Add12Hours% == 1 if %Hour% LSS 12 set /A Hour+=12
set "DateTime="
set "Add12Hours="
rem Must use two arrays as more than 31 tokens are not supported
rem by command line interpreter cmd.exe respectively command FOR.
set /A "Index1=Year-1979"
set /A "Index2=Index1-30"
if %Index1% LEQ 30 (
rem Get number of days to year for the years 1980 to 2009.
for /F "tokens=%Index1% delims= " %%Y in ("3652 4018 4383 4748 5113 5479 5844 6209 6574 6940 7305 7670 8035 8401 8766 9131 9496 9862 10227 10592 10957 11323 11688 12053 12418 12784 13149 13514 13879 14245") do set "Days=%%Y"
for /F "tokens=%Index1% delims= " %%L in ("Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N") do set "LeapYear=%%L"
) else (
rem Get number of days to year for the years 2010 to 2038.
for /F "tokens=%Index2% delims= " %%Y in ("14610 14975 15340 15706 16071 16436 16801 17167 17532 17897 18262 18628 18993 19358 19723 20089 20454 20819 21184 21550 21915 22280 22645 23011 23376 23741 24106 24472 24837") do set "Days=%%Y"
for /F "tokens=%Index2% delims= " %%L in ("N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N N Y N N") do set "LeapYear=%%L"
)
rem Add the days to month in year.
if "%LeapYear%" == "N" (
for /F "tokens=%Month% delims= " %%M in ("0 31 59 90 120 151 181 212 243 273 304 334") do set /A "Days+=%%M"
) else (
for /F "tokens=%Month% delims= " %%M in ("0 31 60 91 121 152 182 213 244 274 305 335") do set /A "Days+=%%M"
)
rem Add the complete days in month of year.
set /A "Days+=Day-1"
rem Calculate the seconds which is easy now.
set /A "Seconds=Days*86400+Hour*3600+Minute*60+Second"
rem Exit this subroutine.
goto :EOF
For optimal performance it would be best to remove all comments, i.e. all lines starting with rem after 0-4 leading spaces.
And the arrays can be made also smaller, i.e. decreasing the time range from 1980-01-01 00:00:00 to 2038-01-19 03:14:07 as currently supported by the batch code above for example to 2015-01-01 to 2019-12-31 as the code below uses which really deletes files older than 7 days in C:\Temp
folder tree.
Further the batch code below is optimized for 24 hours time format.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
call :GetSeconds "%DATE:~-10% %TIME%"
set /A "LastWeek=Seconds-7*86400"
for /F "delims=" %%# in ('dir /A-D-H-S /B /S "C:\Temp"') do (
call :GetSeconds "%%~t#:0"
set "FullFileName=%%#"
setlocal EnableDelayedExpansion
if !Seconds! LSS %LastWeek% del /F "!FullFileName!"
endlocal
)
endlocal
goto :EOF
:GetSeconds
for /F "tokens=1-6 delims=,-./: " %%A in ("%~1") do (
set "Day=%%B" & set "Month=%%A" & set "Year=%%C"
set "Hour=%%D" & set "Minute=%%E" & set "Second=%%F"
)
if "%Month:~0,1%" == "0" if not "%Month:~1%" == "" set "Month=%Month:~1%"
if "%Day:~0,1%" == "0" if not "%Day:~1%" == "" set "Day=%Day:~1%"
if "%Hour:~0,1%" == "0" if not "%Hour:~1%" == "" set "Hour=%Hour:~1%"
if "%Minute:~0,1%" == "0" if not "%Minute:~1%" == "" set "Minute=%Minute:~1%"
if "%Second:~0,1%" == "0" if not "%Second:~1%" == "" set "Second=%Second:~1%"
set /A "Index=Year-2014"
for /F "tokens=%Index% delims= " %%Y in ("16436 16801 17167 17532 17897") do set "Days=%%Y"
for /F "tokens=%Index% delims= " %%L in ("N Y N N N") do set "LeapYear=%%L"
if "%LeapYear%" == "N" (
for /F "tokens=%Month% delims= " %%M in ("0 31 59 90 120 151 181 212 243 273 304 334") do set /A "Days+=%%M"
) else (
for /F "tokens=%Month% delims= " %%M in ("0 31 60 91 121 152 182 213 244 274 305 335") do set /A "Days+=%%M"
)
set /A "Days+=Day-1"
set /A "Seconds=Days*86400+Hour*3600+Minute*60+Second"
goto :EOF
For even more information about date and time formats and file time comparisons on Windows see my answer on Find out if file is older than 4 hours in batch file with lots of additional information about file times.
Another approach you can take if you need to back up a single table out of multiple tables in a database is:
Generate script of specific table(s) from a database (Right-click database, click Task > Generate Scripts...
Run the script in the query editor. You must change/add the first line (USE DatabaseName) in the script to a new database, to avoid getting the "Database already exists" error.
Right-click on the newly created database, and click on Task > Back Up... The backup will contain the selected table(s) from the original database.
I was having the exact same issue, I triple checked the include paths, I also checked that pear was installed and everything looked OK and I was still getting the errors, after a few hours of going crazy looking at this I realized that in my script had this:
include_once "../Mail.php";
instead of:
include_once ("../Mail.php");
Yup, the stupid parenthesis was missing, but there was no generated error on this line of my script which was odd to me
In EF Core you can enter the command Remove-Migration
in the package manager console after you've added your erroneous migration.
The console suggests you do so if your migration could involve a loss of data:
An operation was scaffolded that may result in the loss of data. Please review the migration for accuracy. To undo this action, use Remove-Migration.
ViewBag
is server side code.
Javascript
is client side code.
You can't really connect them.
You can do something like this:
var x = $('#' + '@(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
I allways use UPPER(text)
like UPPER('%blah%')
Here's the official words from the Java Language Specification.
14.20.2. Execution of try-finally and try-catch-finally
A
try
statement with afinally
block is executed by first executing thetry
block. Then there is a choice:
- If execution of the
try
block completes normally, [...]- If execution of the
try
block completes abruptly because of athrow
of a value V, [...]- If execution of the
try
block completes abruptly for any other reason R, then thefinally
block is executed. Then there is a choice:
- If the finally block completes normally, then the
try
statement completes abruptly for reason R.- If the
finally
block completes abruptly for reason S, then thetry
statement completes abruptly for reason S (and reason R is discarded).
The specification for return
actually makes this explicit:
JLS 14.17 The return Statement
ReturnStatement: return Expression(opt) ;
A
return
statement with noExpression
attempts to transfer control to the invoker of the method or constructor that contains it.A
return
statement with anExpression
attempts to transfer control to the invoker of the method that contains it; the value of theExpression
becomes the value of the method invocation.The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any
try
statements within the method or constructor whosetry
blocks contain thereturn
statement, then anyfinally
clauses of thosetry
statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of afinally
clause can disrupt the transfer of control initiated by areturn
statement.
Once the file object is iterated, it is exausted.
>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1
2
3
# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>
Use file.seek
(or close/open the file) to rewind the file:
>>> f.seek(0)
>>> for line in f: print line
...
1
2
3
You can create an empty file whether it exists or not ...
new FileOutputStream("score.txt", false).close();
if you want to leave the file if it exists ...
new FileOutputStream("score.txt", true).close();
You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.
Using a nested .each()
means that your inner loop is doing one td at a time, so you can't set the productId
and product
and quantity
all in the inner loop.
Also using function(key, val)
and then val[key].innerHTML
isn't right: the .each()
method passes the index (an integer) and the actual element, so you'd use function(i, element)
and then element.innerHTML
. Though jQuery also sets this
to the element, so you can just say this.innerHTML
.
Anyway, here's a way to get it to work:
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
});
Update Sep 2017 - tl;dr
Download a single file from a remote ftp server to your machine:
sftp {user}@{host}:{remoteFileName} {localFileName}
Upload a single file from your machine to a remote ftp server:
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Original answer:
Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:
sftp user@host remoteFile localFile
The only documentation shown in the terminal is this:
sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]
However, I came across this site which shows the following under the synopsis:
sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host
sftp [[user@]host[:file [file]]]
sftp [[user@]host[:dir[/]]]
So the simple answer is you just do :
after your user and host then the remote file and local filename. Incredibly simple!
Single line, sftp copy remote file:
sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log
Update Feb 2016
In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp
command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
SELECT *
FROM testcases1 t
WHERE NOT EXISTS (
SELECT 1
FROM executions1 i
WHERE t.tc_id = i.tc_id and t.pro_id=i.pro_id and pro_id=7 and version_id=5
) and pro_id=7 ;
Here testcases1 table contains all datas and executions1 table contains some data among testcases1 table. I am retrieving only the datas which are not present in exections1 table. ( and even I am giving some conditions inside that you can also give.) specify condition which should not be there in retrieving data should be inside brackets.
The following code will help you to get the element of the mouse pointer. The resulted elements will display in the console.
document.addEventListener('mousemove', function(e) {
console.log(document.elementFromPoint(e.pageX, e.pageY));
})
I found my problem. The issue was that my integers were actually type numpy.int64
.
The best way to use is white-space: nowrap;
This will align the text to one line.
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
for example we have a
class Employee
{
int getsalary()
{return 0;}
String getDesignation()
{
return “default”;
}
}
class Manager extends Employee
{
int getsalary()
{
return 20000;
}
String getDesignation()
{
return “Manager”
}
}
class SoftwareEngineer extends Employee
{
int getsalary()
{
return 20000;
}
String getDesignation()
{
return “Manager”
}
}
now if you want to set or get salary and designation of all employee (i.e software enginerr,manager etc )
we will take an array of Employee and call both method getsalary(),getDesignation
Employee arr[]=new Employee[10];
arr[1]=new SoftwareEngieneer();
arr[2]=new Manager();
arr[n]=…….
for(int i;i>arr.length;i++)
{
System.out.println(arr[i].getDesignation+””+arr[i].getSalary())
}
now its an kind of loose coupling because you can have different types of employees ex:softeware engineer,manager,hr,pantryEmployee etc
so you can give object to the parent reference irrespective of different employee object
To create a user with sudo privileges is to put the user into /etc/sudoers
, or make the user a member of a group specified in /etc/sudoers
. And to make it password-less is to additionally specify NOPASSWD
in /etc/sudoers
.
Example of /etc/sudoers
:
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
## Allows people in group wheel to run all commands
%wheel ALL=(ALL) ALL
## Same thing without a password
%wheel ALL=(ALL) NOPASSWD: ALL
And instead of fiddling with /etc/sudoers
file, we can create a new file in /etc/sudoers.d/
directory since this directory is included by /etc/sudoers
by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers
.
To achieve above in Ansible, refer to the following:
- name: sudo without password for wheel group
copy:
content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
dest: /etc/sudoers.d/wheel_nopasswd
mode: 0440
You may replace %wheel
with other group names like %sudoers
or other user names like deployer
.
in gradle.properties, you can even delete
org.gradle.jvmargs=-Xmx1536m
such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.
Could you add z-index style to the two sections so that the one you want appears on top?
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
@Test
public void testIndexofCaseSensitive() {
TestCase.assertEquals(-1, "abcDef".indexOf("d") );
}
With spring configuration :
@Configuration
public class ProjectConfiguration {
private static final Logger log =
LoggerFactory.getLogger(ProjectConfiguration.class);
@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
log.info("hello world, I have just started up");
}
}
You'll have to style your printout with @media print {}
in the CSS but the simple code is:
export default class Component extends Component {
print(){
window.print();
}
render() {
...
<span className="print"
onClick={this.print}>
PRINT
</span>
}
}
Hope that's helpful!
Git is Version Control System, created for software development, so from the whole set of modes and permissions it stores only executable bit (for ordinary files) and symlink bit. If you want to store full permissions, you need third party tool, like git-cache-meta
(mentioned by VonC), or Metastore (used by etckeeper). Or you can use IsiSetup, which IIRC uses git as backend.
See Interfaces, frontends, and tools page on Git Wiki.
If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.
$(window).hover(function() {
// code here...
});
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
null
is a value assigned to a reference type. null
is a reserved value, indicating that a reference does not resemble an instance of an object.
A boolean
is not an instance of an Object. It is a primitive type, like int
and float
. In the same way that: int x
has a value of 0
, boolean x
has a value of false
.
You might be better off using os.walk()
for this.
os.listdir()
doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using os.walk()
to recursively remove a directory here, and hints on how to adapt it to your circumstances.
The most comprehensive and reliable method I know is still by using DBMS_METADATA:
select dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'OBJECT_GRANT', :username ) from dual;
select dbms_metadata.get_granted_ddl( 'ROLE_GRANT', :username ) from dual;
(username must be written all uppercase)
Interesting answers though.
I think it would be interesting to write both of them in a way that only by switching some lines of code would give you one algorithm or the other, so that you will see that your dillema is not so strong as it seems to be at first.
I personally like the interpretation of BFS as flooding a landscape: the low altitude areas will be flooded first, and only then the high altitude areas would follow. If you imagine the landscape altitudes as isolines as we see in geography books, its easy to see that BFS fills all area under the same isoline at the same time, just as this would be with physics. Thus, interpreting altitudes as distance or scaled cost gives a pretty intuitive idea of the algorithm.
With this in mind, you can easily adapt the idea behind breadth first search to find the minimum spanning tree easily, shortest path, and also many other minimization algorithms.
I didnt see any intuitive interpretation of DFS yet (only the standard one about the maze, but it isnt as powerful as the BFS one and flooding), so for me it seems that BFS seems to correlate better with physical phenomena as described above, while DFS correlates better with choices dillema on rational systems (ie people or computers deciding which move to make on a chess game or going out of a maze).
So, for me the difference between lies on which natural phenomenon best matches their propagation model (transversing) in real life.
To clear an item delete it and call $$compose
if ($location.$$search.yourKey) {
delete $location.$$search.yourKey;
$location.$$compose();
}
derived from angularjs source : https://github.com/angular/angular.js/blob/c77b2bcca36cf199478b8fb651972a1f650f646b/src/ng/location.js#L419-L443
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
Try:
awk -F',' '{print $3}' myfile.txt
Here in -F you are saying to awk that use "," as field separator.
The way you import a .cer file into the trust store is the same way you'd import a .crt file from say an export from Firefox.
You do not have to put an alias and the password of the keystore, you can just type:
keytool -v -import -file somefile.crt -alias somecrt -keystore my-cacerts
Preferably use the cacerts file that is already in your Java installation (jre\lib\security\cacerts) as it contains secure "popular" certificates.
Update regarding the differences of cer and crt (just to clarify) According to Apache with SSL - How to convert CER to CRT certificates? and user @Spawnrider
CER is a X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
It is not the same encoding.
%d
, 0 is FALSE, 1 is TRUE.
BOOL b;
NSLog(@"Bool value: %d",b);
or
NSLog(@"bool %s", b ? "true" : "false");
On the bases of data type %@
changes as follows
For Strings you use %@
For int you use %i
For float and double you use %f
It is important to remember when using defaultdict and similar nested dict modules such as nested_dict
, that looking up a nonexistent key may inadvertently create a new key entry in the dict and cause a lot of havoc.
Here is a Python3 example with nested_dict
module:
import nested_dict as nd
nest = nd.nested_dict()
nest['outer1']['inner1'] = 'v11'
nest['outer1']['inner2'] = 'v12'
print('original nested dict: \n', nest)
try:
nest['outer1']['wrong_key1']
except KeyError as e:
print('exception missing key', e)
print('nested dict after lookup with missing key. no exception raised:\n', nest)
# Instead, convert back to normal dict...
nest_d = nest.to_dict(nest)
try:
print('converted to normal dict. Trying to lookup Wrong_key2')
nest_d['outer1']['wrong_key2']
except KeyError as e:
print('exception missing key', e)
else:
print(' no exception raised:\n')
# ...or use dict.keys to check if key in nested dict
print('checking with dict.keys')
print(list(nest['outer1'].keys()))
if 'wrong_key3' in list(nest.keys()):
print('found wrong_key3')
else:
print(' did not find wrong_key3')
Output is:
original nested dict: {"outer1": {"inner2": "v12", "inner1": "v11"}}
nested dict after lookup with missing key. no exception raised:
{"outer1": {"wrong_key1": {}, "inner2": "v12", "inner1": "v11"}}
converted to normal dict.
Trying to lookup Wrong_key2
exception missing key 'wrong_key2'
checking with dict.keys
['wrong_key1', 'inner2', 'inner1']
did not find wrong_key3
You can log all queries:
$ mongo
MongoDB shell version: 2.4.9
connecting to: test
> use myDb
switched to db myDb
> db.getProfilingLevel()
0
> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 1, "ok" : 1 }
> db.getProfilingLevel()
2
> db.system.profile.find().pretty()
Source: http://docs.mongodb.org/manual/reference/method/db.setProfilingLevel/
db.setProfilingLevel(2)
means "log all operations".
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
I have come to the same problem and fixed the same way as Alex K.
So if "Send Errors To Browser" is not working set also this:
Error Pages -> 500 -> Edit Feature Settings -> "Detailed Errors"
Also note that if the content of the error page sent back is quite short and you're using IE, IE will happily ignore the useful content sent back by the server and show you its own generic error page instead. You can turn this off in IE's options, or use a different browser.
Another possible fix:
For some reason, this work.
Turns out I had a .csv file at the end of the folder from which I was reading all the images. Once I deleted that it worked alright
Make sure that it's all images and that you don't have any other type of file
You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup
mm
stands for "minutes". Use MM
instead:
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
You can use EnvInject plugin to injects environment variables at build startup. For example:
There are several answers. i ended up with a similar yet different solution that makes sense to me, maybe it will make sense to you as well. My main objective was to be able to pass logs to handlers by their level (debug level logs to the console, warnings and above to files):
from flask import Flask
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
# make default logger output everything to the console
logging.basicConfig(level=logging.DEBUG)
rotating_file_handler = RotatingFileHandler(filename="logs.log")
rotating_file_handler.setLevel(logging.INFO)
app.logger.addHandler(rotating_file_handler)
created a nice util file named logger.py:
import logging
def get_logger(name):
return logging.getLogger("flask.app." + name)
the flask.app is a hardcoded value in flask. the application logger is always starting with flask.app as its the module's name.
now, in each module, i'm able to use it in the following mode:
from logger import get_logger
logger = get_logger(__name__)
logger.info("new log")
This will create a new log for "app.flask.MODULE_NAME" with minimum effort.
<input type="text" id="input_id" />
$('#input_id').keydown(function (event) {
if (event.keyCode == 13) {
// Call your function here or add code here
}
});
Swift 4
extension String {
func convertToDictionary() -> [String: Any]? {
if let data = self.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
}
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
LIKE
and the equality operator have different purposes, they don't do the same thing:
=
is much faster, whereas LIKE
can interpret wildcards. Use =
wherever you can and LIKE
wherever you must.
SELECT * FROM user WHERE login LIKE 'Test%';
Sample matches:
TestUser1
TestUser2
TestU
Test
I had same problem with provisioning profile. If you have any kind of iPhone, you can connect to your Mac with cable and provisioning profile is automatically defined.
Try wrapping whatever you want to print out in parentheses:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
Your code is being interpreted as many parameters being passed to Write-Host
. Wrapping it up inside parentheses will concatenate the values and then pass the resulting value as a single parameter.
The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example).
For the detailed rules for the SUN JVM check my old blog
Regards, Markus
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).
bless
associates a reference with a package.
It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).
The effect bless
-ing has is that it allows you to apply special syntax to the blessed reference.
For example, if a blessed reference is stored in $obj
(associated by bless
with package "Class"), then $obj->foo(@args)
will call a subroutine foo
and pass as first argument the reference $obj
followed by the rest of the arguments (@args
). The subroutine should be defined in package "Class". If there is no subroutine foo
in package "Class", a list of other packages (taken form the array @ISA
in the package "Class") will be searched and the first subroutine foo
found will be called.
Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.
var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;
$.each(data, function(i) {
if(!(i%numCols)) tRow = $('<tr>');
tCell = $('<td>').html(data[i]);
$('table').append(tRow.append(tCell));
});
?
I think it is implemented in the engine as Matthias said: WHERE, GROUP BY, HAVING
Was trying to find a reference online that lists the entire sequence (i.e. "SELECT" comes right down at the bottom), but I can't find it. It was detailed in a "Inside Microsoft SQL Server 2005" book I read not that long ago, by Solid Quality Learning
Edit: Found a link: http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx
What worked for me was:
Resources.getSystem().getConfiguration().locale;
Resources.getSystem()
returns a global shared Resources object that provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc).
Because getConfiguration.locale
has now been deprecated, the preferred way to get the primary locale in Android Nougat is:
Resources.getSystem().getConfiguration().getLocales().get(0);
To guarantee compatibility with the previous Android versions a possible solution would be a simple check:
Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
locale = Resources.getSystem().getConfiguration().locale;
}
Update
Starting with support library 26.1.0
you don't need to check the Android version as it offers a convenient method backward compatible getLocales()
.
Simply call:
ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration());
git rev-parse
is an ancillary plumbing
command primarily used for manipulation.
One common usage of git rev-parse
is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short
for printing a shorter unique SHA1.
There are other use cases as well (in scripts and other tools built on top of git) that I've used for:
--verify
to verify that the specified object is a valid git object.--git-dir
for displaying the abs/relative path of the the .git
directory.--is-inside-git-dir
or within a work-tree using --is-inside-work-tree
--is-bare-repository
--branches
), tags (--tags
) and the refs can also be filtered based on the remote (using --remote
)--parse-opt
to normalize arguments in a script (kind of similar to getopt
) and print an output string that can be used with eval
Massage
just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:
A..B
for git log
or git diff
into the equivalent arguments for the underlying plumbing command as B ^A
Include the facebook button on the page which you want to share
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://trial.com/news.php?newsid=<?php echo $content; ?>">
<img src="http://trial/new_img/facebook_link.png" style=" border: 1px solid #d9d9d9; box-shadow: 0 4px 7px 0 #a5a5a5; padding: 5px;" title="facebook_link" alt="facebook_link" />
</a>
PixlUI project allows you to use textAllCaps in any textview or subclass of textview including: Button, EditText AutoCompleteEditText Checkbox RadioButton and several others.
You will need to create your textviews using the pixlui version rather than the ones from the android source, meaning you have to do this:
<com.neopixl.pixlui.components.textview.TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
pixlui:textAllCaps="true" />
PixlUI also allows you to set a custom typeface/font which you put in your assets folder.
I'm working on a Gradle fork of the PixlUI framework which uses gradle and allows one to specify textAllCaps as well as the typeface from styles rather than requiring them inline as the original project does.
For SDK 29 :
String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}
public static void createTextFile(String sBody, String FileName, String Where) {
try {
File gpxfile = new File(Where, FileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then you can save your file like this :
createTextFile("This is Content","file.txt",str1);
You need to use Regular Expression For Website URL it is
var urlPattern = /(http|ftp|https)://[\w-]+(.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/
Use this Expression as in example
var regex = new RegExp(urlPattern ); var t = 'www.google.com';
var res = t.match(regex /g);
For You have to pass your web page as string to this javascript in variable t and get array
To uninstall it globally just run below command:
npm uninstall -g @angular/cli
Once it is done, clear your cache by running below command:
npm cache clean
Now, to install the latset version of Angular, just run:
npm install -g @angular/cli@latest
For details about Angular CLI, take a look at Angular introduction and CLI guide
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
When multiple keys end up in same hash code which is present in same bucket. When the same key has different values then the old value will be replaced with new value.
Liked list converted to balanced Binary tree from java 8 version on wards in worst case scenario.
Collision happen when 2 distinct keys generate the same hashcode() value. When there are more collisions then there it will leads to worst performance of hashmap.
Objects which are are equal according to the equals method must return the same hashCode value. When both objects return the same has code then they will be moved into the same bucket.
Don't forget URNs. URIs and URLs are both URNs. URLs have a location:
URI: foo
URL: http://some.domain.com/foo
URL: http://some.domain.com:8080/foo
URL: ftp://some.domain.com/foo
They're all URNs.
With recent builds of mongodb community edition, this is straightforward.
When you install via brew, it tells you what exactly to do. There is no need to create a new launch control file.
$ brew install mongodb
==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.0.6.yosemite.bottle.tar.gz ### 100.0%
==> Pouring mongodb-3.0.6.yosemite.bottle.tar.gz
==> Caveats
To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
mongod --config /usr/local/etc/mongod.conf
==> Summary
/usr/local/Cellar/mongodb/3.0.6: 17 files, 159M
Open your id_dsa.pub or some_name.pub file with gedit and copy-paste the contents!
Just use:
~/.ssh$ gedit some_name.pub
Adding one more answer as the solution is from different contexts:
I connected to MongoDB Atlas and whitelisted my machine's IP by following the below steps:
Other answers work, but
To get the full/default price:
$product->get_price_html();
The right way is to use Culture:
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())
Note: This will capitalise each word within a string, e.g. "red house" --> "Red House". The solution will also lower-case capitalisation within words, e.g. "old McDonald" --> "Old Mcdonald".
You can use the fixed
CSS position property to accomplish this. There is a basic tutorial on this here.
EDIT: However, this approach is NOT supported in IE versions < IE7, and only in IE7 if it is in standards mode. This is discussed in a little more detail here.
There is also a hack, explained here, that shows how to accomplish fixed positioning in IE6 without affecting absolute positioning. What version of IE are you targeting your website for?
For mac, this works really well: http://martinfitzpatrick.name/article/add-git-branch-name-to-terminal-prompt-mac/:
# Git branch in prompt.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
You can take a look at this wonderful articles, under section Deadlock. It is in C# but the idea is still the same for other platform. I quote here for easy reading
A deadlock happens when two threads each wait for a resource held by the other, so neither can proceed. The easiest way to illustrate this is with two locks:
object locker1 = new object();
object locker2 = new object();
new Thread (() => {
lock (locker1)
{
Thread.Sleep (1000);
lock (locker2); // Deadlock
}
}).Start();
lock (locker2)
{
Thread.Sleep (1000);
lock (locker1); // Deadlock
}
A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<script type="text/javascript">
function loadData() {
// getData() will return the string of data...
document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
}
</script>
</head>
<body onload='loadData()'>
<h1>check out the data!</h1>
<div id='data'></div>
</body>
</html>
// function wrapper, just return the string of data (csv etc)
function getData () {
return 'look at this line of data\n\
oh, look at this line'
}
See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview
The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\'
).
If you mean an equal number of lines, split
has an option for this:
split --lines=75
If you need to know what that 75
should really be for N
equal parts, its:
lines_per_part = int(total_lines + N - 1) / N
where total lines can be obtained with wc -l
.
See the following script for an example:
#!/usr/bin/bash
# Configuration stuff
fspec=qq.c
num_files=6
# Work out lines per file.
total_lines=$(wc -l <${fspec})
((lines_per_file = (total_lines + num_files - 1) / num_files))
# Split the actual file, maintaining lines.
split --lines=${lines_per_file} ${fspec} xyzzy.
# Debug information
echo "Total lines = ${total_lines}"
echo "Lines per file = ${lines_per_file}"
wc -l xyzzy.*
This outputs:
Total lines = 70
Lines per file = 12
12 xyzzy.aa
12 xyzzy.ab
12 xyzzy.ac
12 xyzzy.ad
12 xyzzy.ae
10 xyzzy.af
70 total
More recent versions of split
allow you to specify a number of CHUNKS
with the -n/--number
option. You can therefore use something like:
split --number=l/6 ${fspec} xyzzy.
(that's ell-slash-six
, meaning lines
, not one-slash-six
).
That will give you roughly equal files in terms of size, with no mid-line splits.
I mention that last point because it doesn't give you roughly the same number of lines in each file, more the same number of characters.
So, if you have one 20-character line and 19 1-character lines (twenty lines in total) and split to five files, you most likely won't get four lines in every file.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME='Name'
allow less secure apps to access your account in the Gmail security setting.
A small usage of np.nan ! = np.nan
s[s==s]
Out[953]:
0 1.0
1 2.0
2 3.0
3 4.0
5 5.0
dtype: float64
More Info
np.nan == np.nan
Out[954]: False
As long as the User does not delete their cookies or close their browser, the session should stay in existence.
I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.
JS:
function make () {
var cl = 1;
function gett () {
console.log(cl);
}
function sett (val) {
cl = val;
}
return [gett, sett]
}
and executing:
a = make(); g = a[0]; s = a[1];
s(2); g(); // 2
s(3); g(); // 3
Python:
def make ():
cl = 1
def gett ():
print(cl);
def sett (val):
cl = val
return gett, sett
and executing:
g, s = make()
g() #1
s(2); g() #1
s(3); g() #1
Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var
keyword.
I had a similar issue that was resolved with the following:
If the user is a domain user use Domain username and password
For existing matches, use query
:
df.query(' A > 3' ).head(1)
Out[33]:
A B C
2 4 6 3
df.query(' A > 4 and B > 3' ).head(1)
Out[34]:
A B C
4 5 4 5
df.query(' A > 3 and (B > 3 or C > 2)' ).head(1)
Out[35]:
A B C
2 4 6 3
You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.
So just change the gaussian() function to:
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
You do not need to clear focus, just add this code where you want to focus
time_statusTV.setFocusable(true);
time_statusTV.requestFocus();
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput( time_statusTV, 0);
Here how you can print without using Data::Dumper
print "@{[%hash]}";
On OSX, for me it's cmd ? + p. cmd ? + e just searches within the currently opened file.
Say:
sed "s|\$ROOT|${HOME}|" abc.sh
Note:
/
since the replacement contains /
$
in the pattern since you don't want to expand it.EDIT: In order to replace all occurrences of $ROOT
, say
sed "s|\$ROOT|${HOME}|g" abc.sh
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
STATICFILES_DIRS=[STATIC_DIR]
var top = event.target.offsetTop + 'px';
Parent element top position like we are adding elemnt inside div
var rect = event.target.offsetParent;
rect.offsetTop;
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
Here is the simplest and most concise way, although I do not know how it compares in terms of CPU cycles. This works great if you only wish to know if the root is a whole number. If you really care if it is an integer, you can also figure that out. Here is a simple (and pure) function:
private static final MathContext precision = new MathContext(20);
private static final Function<Long, Boolean> isRootWhole = (n) -> {
long digit = n % 10;
if (digit == 2 || digit == 3 || digit == 7 || digit == 8) {
return false;
}
return new BigDecimal(n).sqrt(precision).scale() == 0;
};
If you do not need micro-optimization, this answer is better in terms of simplicity and maintainability. If you will be calculating negative numbers, you will need to handle that accordingly, and send the absolute value into the function. I have included a minor optimization because no perfect squares have a tens digit of 2, 3, 7, or 8 due to quadratic residues mod 10.
On my CPU, a run of this algorithm on 0 - 10,000,000 took an average of 1000 - 1100 nanoseconds per calculation.
If you are performing a lesser number of calculations, the earlier calculations take a bit longer.
I had a negative comment that my previous edit did not work for large numbers. The OP mentioned Longs, and the largest perfect square that is a Long is 9223372030926249001, so this method works for all Longs.
While risking you punching me, I guess you are stuck with the solution you mentioned. Have a look at this posting on SuperUser:
Which are the non-x text editors in Powershell?
Also, there is a nano version for windows:
I'll duck and cover now, hopefully someone will have a more sufficient answer.
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
I use dotLiquid for exactly this task.
It takes a template, and fills special identifiers with the content of an anonymous object.
//define template
String templateSource = "<h1>{{Heading}}</h1>Dear {{UserName}},<br/><p>First part of the email body goes here");
Template bodyTemplate = Template.Parse(templateSource); // Parses and compiles the template source
//Create DTO for the renderer
var bodyDto = new {
Heading = "Heading Here",
UserName = userName
};
String bodyText = bodyTemplate.Render(Hash.FromAnonymousObject(bodyDto));
It also works with collections, see some online examples.
Using Linq we can simplify this by this
Enumerable.Range(0, (int)(to - from).TotalHours + 1)
.Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))
I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:
UserModel.find({}, function (err, users) {
console.log(users.save); // { [Function] numAsyncPres: 0 }
var json = JSON.stringify(users);
users = users.map(function (user) {
return user.toObject();
}
console.log(user.save); // undefined
console.log(json == JSON.stringify(users)); // true
}
doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.
More simple, just set the buttonTint color: (only works on api level 21 or above)
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radio"
android:checked="true"
android:buttonTint="@color/your_color"/>
in your values/colors.xml put your color in this case a reddish one:
<color name="your_color">#e75748</color>
Result:
If you want to do it by code (also api 21 and above):
if(Build.VERSION.SDK_INT>=21)
{
ColorStateList colorStateList = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled}, //disabled
new int[]{android.R.attr.state_enabled} //enabled
},
new int[] {
Color.BLACK //disabled
,Color.BLUE //enabled
}
);
radio.setButtonTintList(colorStateList);//set the color tint list
radio.invalidate(); //could not be necessary
}
Using one line to convert the dates to preferred format:
nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")
Many changes you can make very easily and visually in the table editor in SQL Server Management Studio actually require SSMS to drop the table in the background and re-create it from scratch. Even simple things like reordering the columns cannot be expressed in standard SQL DDL statement - all SSMS can do is drop and recreate the table.
This operation can be a) very time consuming on a large table, or b) might even fail for various reasons (like FK constraints and stuff). Therefore, SSMS in SQL Server 2008 introduced that new option the other answers have already identified.
It might seem counter-intuitive at first to prevent such changes - and it's certainly a nuisance on a dev server. But on a production server, this option and its default value of preventing such changes becomes a potential life-saver!
For Chrome/Chromium
console.log(myObj)
or it's equivalent
console.debug(myObj)
If all the previous answers didn't give any solution, you should check your user privileges.
If you could login as root
to mysql
then you should add this:
CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY '***';
GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.1.100' IDENTIFIED BY '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;
Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100
. It should work.
You could try this code:
private float GetBrightestColor(float r, float g, float b) {
if (r > g && r > b) {
return r;
} else if (g > r && g > b) {
return g;
} else if (b > r && b > g) {
return b;
}
}
You can use the stringr
library:
library('stringr')
a <- runif(10)
b <- letters[1:10]
c <- c(rep('A-B', 4), rep('A_B', 6))
data <- data.frame(a, b, c)
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A_C
# 6 0.55313288 f A_C
# 7 0.31264280 g A_C
# 8 0.33759921 h A_C
# 9 0.72322599 i A_C
# 10 0.25223075 j A_C
data$c <- str_replace_all(data$c, '_', '-')
data
# a b c
# 1 0.19426707 a A-B
# 2 0.12902673 b A-B
# 3 0.78324955 c A-B
# 4 0.06469028 d A-B
# 5 0.34752264 e A-C
# 6 0.55313288 f A-C
# 7 0.31264280 g A-C
# 8 0.33759921 h A-C
# 9 0.72322599 i A-C
# 10 0.25223075 j A-C
Note that this does change factored variables into character.
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
For +300k concurrent connection:
Set these variables in /etc/sysctl.conf
:
fs.file-max = 10000000
fs.nr_open = 10000000
Also, change these variables in /etc/security/limits.conf
:
* soft nofile 10000000
* hard nofile 10000000
root soft nofile 10000000
root hard nofile 10000000
And finally, increase TCP buffers in /etc/sysctl.conf
, too:
net.ipv4.tcp_mem = 786432 1697152 1945728
net.ipv4.tcp_rmem = 4096 4096 16777216
net.ipv4.tcp_wmem = 4096 4096 16777216
for more information please refer to this.
Its faster with MUTT command
echo "Body Of the Email" | mutt -a "File_Attachment.csv" -s "Daily Report for $(date)" -c [email protected] [email protected] -y
@Xeon06, nice but just as a fyi for those that read this thread and tried like me...
when returning the array from php => json_encode($theArray)
. converts to a string which to me isn't easy to manipulate esp for soft js users like myself.
Inside js, you are trying to get the array values and/or keys of the array u r better off using JSON.parse as in var jsArray = JSON.parse(data)
where data is return array from php. the json encoded string is converted to js object that can now be manipulated easily.
e.g. foo={one:1, two:2, three:3} - gotten after JSON.parse
for (key in foo){ console.log("foo["+ key +"]="+ foo[key]) }
- prints to ur firebug console. voila!
If you have McAfee HIPS and if you see the following error in event viewer application log:
The Module DLL C:\Windows\System32\inetsrv\HipIISEngineStub.dll failed to load.
The data is the error.
Then the following resolved the issue in my case: https://kc.mcafee.com/corporate/index?page=content&id=KB72677&actp=LIST
Quote from the page:
- Click Start, Run, type explorer and click OK.
- Navigate to: %windir%\system32\inetsrv\config
- Open the file applicationHost.config as Administrator for editing in Notepad.
Edit the <globalModules> section and remove the following line:
<add name="MfeEngine" image="%windir%\System32\inetsrv\HipIISEngineStub.dll" />Edit the <modules> section and remove the following line:
<add name="MfeEngine" />- After you have finished editing the applicationHost.config file, save the file, then restart the IIS server using iisreset or by restarting the system.
That should work. Better if you pass a function to val
:
$('#replyBox').val(function(i, text) {
return text + quote;
});
This way you avoid searching the element and calling val
twice.
In Laravel 5.1+, you can use the value() instead of pluck.
To get first occurence, You can either use
DB::table('users')->value('name');
or use,
DB::table('users')->where('id', 1)->pluck('name')->first();
One special capability of std::list is splicing (linking or moving part of or a whole list into a different list).
Or perhaps if your contents are very expensive to copy. In such a case it might be cheaper, for example, to sort the collection with a list.
Also note that if the collection is small (and the contents are not particularly expensive to copy), a vector might still outperform a list, even if you insert and erase anywhere. A list allocates each node individually, and that might be much more costly than moving a few simple objects around.
I don't think there are very hard rules. It depends on what you mostly want to do with the container, as well as on how large you expect the container to be and the contained type. A vector generally trumps a list, because it allocates its contents as a single contiguous block (it is basically a dynamically allocated array, and in most circumstances an array is the most efficient way to hold a bunch of things).
Simple alert with array data:
NSString *name = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"Name"];
NSString *msg = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"message"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name
message:msg
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.
I've added some CSS to the demo below to change the button's font color to red when its aria-expanded
is set to true
const button = document.querySelector('button');_x000D_
_x000D_
button.addEventListener('click', () => {_x000D_
button.ariaExpanded = !JSON.parse(button.ariaExpanded);_x000D_
})
_x000D_
button[aria-expanded="true"] {_x000D_
color: red;_x000D_
}
_x000D_
<button type="button" aria-expanded="false">Click me!</button>
_x000D_
You shouldn't use CascadeType.ALL
on @ManyToOne
since entity state transitions should propagate from parent entities to child ones, not the other way around.
The @ManyToOne
side is always the Child association since it maps the underlying Foreign Key column.
Therefore, you should move the CascadeType.ALL
from the @ManyToOne
association to the @OneToMany
side, which should also use the mappedBy
attribute since it's the most efficient one-to-many table relationship mapping.
In case if you hate Inner classes, by taking the advantage of functional interface you can write less code in Java 8 with a lambda expression.
JsonDeserializer<Date> dateJsonDeserializer =
(json, typeOfT, context) -> json == null ? null : new Date(json.getAsLong());
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,dateJsonDeserializer).create();
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:
if (@type not set or empty) {
if (@language not set or empty) {
// Treat as default script language; what this is depends on the
// content-script-type HTTP header or equivalent META tag
} else {
if (@language is one of "javascript", "livescript", "mocha",
"javascript1.0", "javascript1.1",
"javascript1.2", "javascript1.3",
"javascript1.4", "javascript1.5",
"javascript1.6", "javascript1.7",
"javascript1.8") {
// Treat as javascript
} else {
// Treat as unknown script language; do not execute
}
}
} else {
if (@type is one of "text/javascript", "text/ecmascript",
"application/javascript",
"application/ecmascript",
"application/x-javascript") {
// Treat as javascript
} else {
// Treat as specified (e.g. if pyxpcom is installed and
// python script is allowed in this context and the type
// is one that the python runtime claims to handle, use that).
// If we don't have a runtime for this type, do not execute.
}
}
Reinstall node, then update npm.
First I removed node
apt-get purge node
Then install node according to the distibution. Docs here .
Then
npm install npm@latest -g
If after changing the namespace and the config/auth.php
it still fails, you could try the following:
In the file vendor/composer/autoload_classmap.php
change the line
App\\User' => $baseDir . '/app/User.php',
,
to
App\\Models\\User' => $baseDir . '/app/Models/User.php',
At the beginning of the file app/Services/Registrar.php
change "use App\User" to "App\Models\User"
Microsoft just added an official prelease version of exactly what you're looking for (called a MultiDictionary) available through NuGet here: https://www.nuget.org/packages/Microsoft.Experimental.Collections/
Info on usage and more details can be found through the official MSDN blog post here: http://blogs.msdn.com/b/dotnet/archive/2014/06/20/would-you-like-a-multidictionary.aspx
I'm the developer for this package, so let me know either here or on MSDN if you have any questions about performance or anything.
Hope that helps.
Update
The MultiValueDictionary
is now on the corefxlab repo, and you can get the NuGet package from this MyGet feed.
Here is pure JavaScript approach:
var form = document.querySelector('form');
var data = new FormData(form);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "<YOUR-URL>", true);
xhttp.send(data);
}
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
One thing that seems to work for me is this:
@ComponentScan(basePackageClasses = {SomeTypeInYourPackage.class}, resourcePattern = "*.class")
Or in XML:
<context:component-scan base-package="com.example" resource-pattern="*.class"/>
This overrides the default resourcePattern
which is "**/*.class"
.
This would seem like the most type-safe way to ONLY include your base package since that resourcePattern would always be the same and relative to your base package.
There are two different Lambda integrations you can configure in API Gateway, such as Lambda integration and Lambda proxy integration. For Lambda integration, you can customise what you are going to pass to Lambda in the payload that you don't need to parse the body, but when you are using Lambda Proxy integration in API Gateway, API Gateway will proxy everything to Lambda in payload like this,
{
"message": "Hello me!",
"input": {
"path": "/test/hello",
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, lzma, sdch, br",
"Accept-Language": "en-US,en;q=0.8",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
"X-Forwarded-For": "192.168.100.1, 192.168.1.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"pathParameters": {"proxy": "hello"},
"requestContext": {
"accountId": "123456789012",
"resourceId": "us4z18",
"stage": "test",
"requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
"identity": {
"cognitoIdentityPoolId": "",
"accountId": "",
"cognitoIdentityId": "",
"caller": "",
"apiKey": "",
"sourceIp": "192.168.100.1",
"cognitoAuthenticationType": "",
"cognitoAuthenticationProvider": "",
"userArn": "",
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
"user": ""
},
"resourcePath": "/{proxy+}",
"httpMethod": "GET",
"apiId": "wt6mne2s9k"
},
"resource": "/{proxy+}",
"httpMethod": "GET",
"queryStringParameters": {"name": "me"},
"stageVariables": {"stageVarName": "stageVarValue"},
"body": "{\"foo\":\"bar\"}",
"isBase64Encoded": false
}
}
For the example you are referencing, it is not getting the body from the original request. It is constructing the response body back to API Gateway. It should be in this format,
{
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "...",
"isBase64Encoded": false
}
(1:nrow(mydata_2))[mydata_2[,4] == 1578]
Of course there may be more than one row with a value of 1578.
The reason this occur is the JVM/Dalvik haven't not confidence in the CA certificates in the system or in the user certificate stores.
To fix this with Retrofit, If you are used okhttp, with another client it's very similar.
You've to do:
A). Create a cert store contain public Key of CA. To do this you need to launch next script for *nix. You need openssl install in your machine, and download from https://www.bouncycastle.org/ the jar bcprov-jdk16-1.46.jar. Download this version not other, the version 1.5x is not compatible with android 4.0.4.
#!/bin/bash
if [ -z $1 ]; then
echo "Usage: cert2Android<CA cert PEM file>"
exit 1
fi
CACERT=$1
BCJAR=bcprov-jdk16-1.46.jar
TRUSTSTORE=mytruststore.bks
ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT`
if [ -f $TRUSTSTORE ]; then
rm $TRUSTSTORE || exit 1
fi
echo "Adding certificate to $TRUSTSTORE..."
keytool -import -v -trustcacerts -alias $ALIAS \
-file $CACERT \
-keystore $TRUSTSTORE -storetype BKS \
-providerclass org.bouncycastle.jce.provider.BouncyCastleProvider \
-providerpath $BCJAR \
-storepass secret
echo ""
echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..."
B). Copy the file truststore mytruststore.bks in res/raw of your project
C). Setting SSLContext of the connection:
.............
okHttpClient = new OkHttpClient();
try {
KeyStore ksTrust = KeyStore.getInstance("BKS");
InputStream instream = context.getResources().openRawResource(R.raw.mytruststore);
ksTrust.load(instream, "secret".toCharArray());
// TrustManager decides which certificate authorities to use.
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ksTrust);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
e.printStackTrace();
}
.................
execCommand('SaveAs', false, filename);
functionalityEdit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.
Now this code is an rare antique zero day collectible.
// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
var dlg = false;
with(document){
ir=createElement('iframe');
ir.id='ifr';
ir.location='about.blank';
ir.style.display='none';
body.appendChild(ir);
with(getElementById('ifr').contentWindow.document){
open("text/plain", "replace");
charset = "utf-8";
write(content);
close();
document.charset = "utf-8";
dlg = execCommand('SaveAs', false, filename);
}
body.removeChild(ir);
}
return dlg;
}
Invoke the function like this:
msg = "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");
Create you menu options the normal way see code below and add a global reference within the class to the menu
Menu mMenu; // global reference within the class
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tcktdetails, menu);
mMenu=menu; // assign the menu to the new menu item you just created
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_cancelticket) {
cancelTicket();
return true;
}
return super.onOptionsItemSelected(item);
}
Now you can toggle your menu by running this code with a button or within a function
if(mMenu != null) {
mMenu.findItem(R.id.action_cancelticket).setVisible(false);
}
The object your method decompressGZIP()
needs is a byte[]
.
So the basic, technical answer to the question you have asked is:
byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only
However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString()
will just give you the default Object.toString()
which is the class name + memory address. In your result [B@38ee9f13
, the [B
means byte[]
and 38ee9f13
is the memory address, separated by an @
.
For display purposes you can use:
Arrays.toString(bytes);
But this will just display as a sequence of comma-separated integers, which may or may not be what you want.
To get a readable String
back from a byte[]
, use:
String string = new String(byte[] bytes, Charset charset);
The reason the Charset
version is favoured, is that all String
objects in Java are stored internally as UTF-16. When converting to a byte[]
you will get a different breakdown of bytes for the given glyphs of that String
, depending upon the chosen charset.
You also can use in this form:
<a href="@Url.Action("Information", "Admin", null)"> Admin</a>
CTRL+R, CTRL+W : Toggle showing whitespace
or under the Edit Menu:
[BTW, it also appears you are using Tabs. It's common practice to have the IDE turn Tabs into spaces (often 4), via Options.]
C++11 has some portable timer stuff. Check out sleep_for.
@IBAction func btn_LogIn(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://demo.hackerkernel.com/ios_api/login.php")!)
request.HTTPMethod = "POST"
let postString = "email: [email protected] & password: testtest"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
guard error == nil && data != nil else{
print("error")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200{
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/
Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).
If the order of element is not important, you can
select
id, elem, row_number() over (partition by id) as nr
from (
select
id,
unnest(string_to_array(elements, ',')) AS elem
from myTable
) a
You can use tcpkill
(part of the dsniff
package) to kill the connection that's on the port you need:
sudo tcpkill -9 port PORT_NUMBER
Pure datetime solution, does not depend on language or DATEFORMAT, no strings
SELECT
DATEADD(year, [year]-1900, DATEADD(month, [month]-1, DATEADD(day, [day]-1, 0)))
FROM
dbo.Table
I use matplotlib for reading TIFF files:
import matplotlib.pyplot as plt
I = plt.imread(tiff_file)
and I
will be of type ndarray
.
According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fine for me.
There's also a plt.imsave
function for saving.
Even though SimpleXML doesn't have a detailed way to remove elements, you can remove elements from SimpleXML by using PHP's unset()
. The key to doing this is managing to target the desired element. At least one way to do the targeting is using the order of the elements. First find out the order number of the element you want to remove (for example with a loop), then remove the element:
$target = false;
$i = 0;
foreach ($xml->seg as $s) {
if ($s['id']=='A12') { $target = $i; break; }
$i++;
}
if ($target !== false) {
unset($xml->seg[$target]);
}
You can even remove multiple elements with this, by storing the order number of target items in an array. Just remember to do the removal in a reverse order (array_reverse($targets)
), because removing an item naturally reduces the order number of the items that come after it.
Admittedly, it's a bit of a hackaround, but it seems to work fine.
I struggled for half a day to get JSCH to work without using the System.in as the input stream to no avail. I tried Ganymed http://www.ganymed.ethz.ch/ssh2/ and had it going in 5 minutes. All the examples seem to be aimed at one usage of the app and none of the examples showed what i needed. Ganymed's example Basic.java Baaaboof Has everything i need.
Dim array As String() = Array.Empty(Of String)
Seems nobody noticed that -x
operator does not differ file with directory.
So to precisely check an executable file, you may use
[[ -f SomeFile && -x SomeFile ]]
My last adventure with MSDTC and this error today turned out to be a DNS issue. You're on the right track asking if the machines are on the same domain, EBarr. Terrific list for this issue, by the way!
My situation: I needed a server in a child domain to be able to run distributed transactions against a server in the parent domain through a firewall. I've used linked servers quite a bit over the years, so I had all the usual settings in SQL for a linked server and in MSDTC that Ian documented so nicely above. I set up MSDTC with a range of TCP ports (5000-5200) to use on both servers, and arranged for a firewall hole between the boxes for ports 1433 and 5000-5200. That should have worked. The linked server tested OK and I could query the remote SQL server via the linked server nicely, but I couldn't get it to allow a distributed transaction. I could even see a connection on the QA server from the DEV server, but something wasn't making the trip back.
I could PING the DEV server from QA using a FQDN like: PING DEVSQL.dev.domain.com
I could not PING the DEV server with just the machine name: PING DEVSQL
The DEVSQL server was supposed to be a member of both domains, but the name wasn't resolving in the parent domain's DNS... something had happened to the machine account for DEVSQL in the parent domain. Once we added DEVSQL to the DNS for the parent domain, and "PING DEVSQL" worked from the remote QA server, this issue was resolved for us.
I hope this helps!
As required in Question::
var string1= "foo/bar/test.html";
if(string1.contains("/"))
{
var string_parts = string1.split("/");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
and for question asked on url (asked for one occurence of '=' )::
[http://stackoverflow.com/questions/24156535/how-to-split-a-string-after-a-particular-character-in-jquery][1]
var string1= "Hello how are =you";
if(string1.contains("="))
{
var string_parts = string1.split("=");
var result = string_parts[string_parts.length - 1];
console.log(result);
}
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
Old question, but first result in Google for me, so here's what I had to do.
Ubuntu 12.04 Desktop with Apache installed
All the configuration and mod_ssl was installed when I installed Apache, but it just wasn't linked in the right spots yet. Note: all paths below are relative to /etc/apache2/
mod_ssl
is stored in ./mods-available
, and the SSL site configuration is in ./sites-available
, you just have to link these to their correct places in ./mods-enabled
and ./sites-enabled
cd /etc/apache2
cd ./mods-enabled
sudo ln -s ../mods-available/ssl.* ./
cd ../sites-enabled
sudo ln -s ../sites-available/default-ssl ./
Restart Apache and it should work. I was trying to access https://localhost, so your results may vary for external access, but this worked for me.
Try using this command : (this will stop tomcat servlet this really helps)
sudo service tomcat7 stop
or
sudo tomcat7 restart (if you need a restart)
Add a type="search"
to your input
The support is pretty decent but will not work in IE<10
<input type="search">
_x000D_
If you need IE9 support here are some workarounds
<input type="text">
and some HTML elements:/**
* Clearable text inputs
*/
$(".clearable").each(function() {
const $inp = $(this).find("input:text"),
$cle = $(this).find(".clearable__clear");
$inp.on("input", function(){
$cle.toggle(!!this.value);
});
$cle.on("touchstart click", function(e) {
e.preventDefault();
$inp.val("").trigger("input");
});
});
_x000D_
/* Clearable text inputs */
.clearable{
position: relative;
display: inline-block;
}
.clearable input[type=text]{
padding-right: 24px;
width: 100%;
box-sizing: border-box;
}
.clearable__clear{
display: none;
position: absolute;
right:0; top:0;
padding: 0 8px;
font-style: normal;
font-size: 1.2em;
user-select: none;
cursor: pointer;
}
.clearable input::-ms-clear { /* Remove IE default X */
display: none;
}
_x000D_
<span class="clearable">
<input type="text" name="" value="" placeholder="">
<i class="clearable__clear">×</i>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
_x000D_
<input class="clearable" type="text">
(No additional elements)set a class="clearable"
and play with it's background image:
/**
* Clearable text inputs
*/
function tog(v){return v ? "addClass" : "removeClass";}
$(document).on("input", ".clearable", function(){
$(this)[tog(this.value)]("x");
}).on("mousemove", ".x", function( e ){
$(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]("onX");
}).on("touchstart click", ".onX", function( ev ){
ev.preventDefault();
$(this).removeClass("x onX").val("").change();
});
// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
_x000D_
/*
Clearable text inputs
*/
.clearable{
background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
border: 1px solid #999;
padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
border-radius: 3px;
transition: background 0.4s;
}
.clearable.x { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
_x000D_
<input class="clearable" type="text" name="" value="" placeholder="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
_x000D_
The trick is to set some right padding (I used 18px) to the input
and push the background-image right, out of sight (I used right -10px center
).
That 18px padding will prevent the text hide underneath the icon (while visible).
jQuery will add the class "x"
(if input
has value) showing the clear icon.
Now all we need is to target with jQ the inputs with class x
and detect on mousemove
if the mouse is inside that 18px "x" area; if inside, add the class onX
.
Clicking the onX
class removes all classes, resets the input value and hides the icon.
7x7px gif:
Base64 string:
data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
You can try this: By Using Authentication Object from Spring we can get User details from it in the controller method . Below is the example , by passing Authentication object in the controller method along with argument.Once user is authenticated the details are populated in the Authentication Object.
@GetMapping(value = "/mappingEndPoint") <ReturnType> methodName(Authentication auth) {
String userName = auth.getName();
return <ReturnType>;
}
You can use ipdb
inside jupyter with:
from IPython.core.debugger import Tracer; Tracer()()
Edit: the functions above are deprecated since IPython 5.1. This is the new approach:
from IPython.core.debugger import set_trace
Add set_trace()
where you need a breakpoint. Type help
for ipdb
commands when the input field appears.
The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:
/* this
is a
multi-line comment */
// this is a single line comment
This can do the trick,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection
, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection
.
public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
private void Handle(object sender, PropertyChangedEventArgs args)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (object t in e.NewItems) {
((T) t).PropertyChanged += Handle;
}
}
if (e.OldItems != null) {
foreach (object t in e.OldItems) {
((T) t).PropertyChanged -= Handle;
}
}
base.OnCollectionChanged(e);
}
While Items are added or removed the class forwards the items PropertyChanged
event to the collections PropertyChanged
event.
usage:
public abstract class ParameterBase : INotifyPropertyChanged
{
protected readonly CultureInfo Ci = new CultureInfo("en-US");
private string _value;
public string Value {
get { return _value; }
set {
if (value == _value) return;
_value = value;
OnPropertyChanged();
}
}
}
public class AItem {
public NotifyObservableCollection<ParameterBase> Parameters {
get { return _parameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_parameters != null) _parameters.CollectionChanged -= cceh;
_parameters = value;
//needed for Binding to AItem at xaml directly
_parameters.CollectionChanged += cceh;
}
}
public NotifyObservableCollection<ParameterBase> DefaultParameters {
get { return _defaultParameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
_defaultParameters = value;
//needed for Binding to AItem at xaml directly
_defaultParameters.CollectionChanged += cceh;
}
}
public class MyViewModel {
public NotifyObservableCollection<AItem> DataItems { get; set; }
}
If now a property of an item in DataItems
changes, the following xaml will get a notification, though it binds to Parameters[0]
or to the item itself except to the changing property Value
of the item (Converters at Triggers are called reliable on every change).
<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Aqua" />
<Style.Triggers>
<DataTrigger Value="False">
<!-- Bind to Items with changing properties -->
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ParameterCompareConverter}">
<Binding Path="DefaultParameters[0]" />
<Binding Path="Parameters[0]" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="DeepPink" />
</DataTrigger>
<!-- Binds to AItem directly -->
<DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
<Setter Property="FontWeight" Value="ExtraBold" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
I've got the silimar problem. The solution was to migrate db (manage.py syncdb
or manage.py schemamigration --auto <table name>
if you use south).
m - min M - Months
Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.
Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.
(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).
To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)
empty
is an operator:
The
empty
operator is a prefix operation that can be used to determine whether a value is null or empty.
<c:if test="${empty myObject.featuresList}">
All other answers show how to calculate the new image height in function of the new image width or vice-versa and how to resize the image using Java Image API. For those people who are looking for a straightforward solution I recommend any java image processing framework that can do this in a single line.
The exemple below uses Marvin Framework:
// 300 is the new width. The height is calculated to maintain aspect.
scale(image.clone(), image, 300);
Necessary import:
import static marvin.MarvinPluginCollection.*
Ended up using .closest() instead.
$(document).on("click", function (event) {
if($(event.target).closest(".CustomControllerMainDiv").length == 1)
alert('element is a child of the custom controller')
});
Since Spring 3.0, you can add a line like
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean" />
to your applicationContext.xml
(or where you configure things).
As Dmitry Chornyi points out in a comment, Java based configuration looks like:
@Bean public ConversionService conversionService() {
return new DefaultConversionService();
}
This activates the new configuration service which supports converting String
to Collection
types.
If you do not activate this configuration service, Spring falls back on its legacy property editors as configuration services, which do not support this kind of conversion.
Converting to collections of other types works, too:
@Value("${my.list.of.ints}")
private List<Integer> myList
will work with a line like
my.list.of.ints= 1, 2, 3, 4
No problems with whitespace there, the ConversionServiceFactoryBean
takes care of it.
In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework. [...] If no ConversionService is registered with Spring, the original PropertyEditor-based system is used.
Just use Instant
of java.time
.
System.out.println(Instant.now());
This just printed:
2018-01-27T09:35:23.179612Z
Instant.toString
always gives UTC time.
The output is usually sortable, but there are unfortunate exceptions. toString
gives you enough groups of three decimals to render the precision it holds. On the Java 9 on my Mac the precision of Instant.now()
seems to be microseconds, but we should expect that in approximately one case out of a thousand it will hit a whole number of milliseconds and print only three decimals. Strings with unequal numbers of decimals will be sorted in the wrong order (unless you write a custom comparator to take this into account).
Instant
is one of the classes in java.time
, the modern Java date and time API, which I warmly recommend that you use instead of the outdated Date
class. java.time
is built into Java 8 and later and has also been backported to Java 6 and 7.
Your TextView Attributes need to be something like,
<TextView ...
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right" ../>
Now, Description why these need to be done,
android:layout_width="match_parent"
android:layout_height="match_parent"
Makes your TextView to match_parent
or fill_parent
if You don't want to be it like, match_parent
you have to give some specified values to layout_height
so it get space for vertical center gravity. android:layout_width="match_parent"
necessary because it align your TextView in Right side so you can recognize respect to Parent Layout of TextView.
Now, its about android:gravity
which makes the content of Your TextView alignment. android:layout_gravity
makes alignment of TextView respected to its Parent Layout.
Update:
As below comment says use fill_parent
instead of match_parent
. (Problem in some device.)
You should not be testing the private methods of your code in the first place. You should be testing the 'public interface' or API, the public things of your classes. The API are all the public methods you expose to outside callers.
The reason is that once you start testing the private methods and internals of your class you are coupling the implementation of your class (the private things) to your tests. This means that when you decide to change your implementation details you will also have to change your tests.
You should for this reason avoid using InternalsVisibleToAtrribute.
Here is a great talk by Ian Cooper which covers this subject: Ian Cooper: TDD, where did it all go wrong
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
Take attention with the parentheses !
The foreach
underhood is creating the iterator
, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.
for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
CustomObj custObj = iter.next();
....
}
Performance issues with the iterator-based loop is because it is:
Iterator<CustomObj> iter = customList.iterator();
);iter.hasNext()
during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).hasNext()
call figure the value: #1 get current count and #2 get total countiter.next
(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).A potential optimiziation is to switch to an index iteration
with the cached size lookup:
for(int x = 0, size = customList.size(); x < size; x++){
CustomObj custObj = customList.get(x);
...
}
Here we have:
customList.size()
on the initial creation of the for loop to get the size customList.get(x)
during the body for loop, which is a field lookup to the array and then can do the offset into the arrayWe reduced a ton of method calls, field lookups. This you don't want to do with LinkedList
or with something that is not a RandomAccess
collection obj, otherwise the customList.get(x)
is gonna turn into something that has to traverse the LinkedList
on every iteration.
This is perfect when you know that is any RandomAccess
based list collection.
I believe you can also accomplish this quite simply as follows:
e.g. #1:
# Libraries to import
import pandas as pd
import nump as np
#N x N numpy array (dimensions dont matter)
corr_mat #your numpy array
my_df = pd.DataFrame(corr_mat) #converting it to a pandas dataframe
e.g. #2:
#save as csv
my_df.to_csv('foo.csv', index=False) # "foo" is the name you want to give
# to csv file. Make sure to add ".csv"
# after whatever name like in the code
There might two issues
1) $blogs may be a stdObject
or
2) The properties of the array might be the stdObject
Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this
$blog->id;
$blog->content;
$blog->title;
In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.
This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.
BTW ignore-whitespace
did not help.
by jquery you can do this:
var arr = $.map(obj,function(value, key) {
return value;
});
alert(obj[0]);
Use np.where
to get the indices where a given condition is True
.
Examples:
For a 2D np.ndarray
called a
:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
For a 1D array:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
Note that this also works for conditions like >=
, <=
, !=
and so forth...
You can also create a subclass of np.ndarray
with an index()
method:
class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
Testing:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)
What you're looking for is min-height
and max-height
.
img {
max-width: 100%;
height: auto;
}
.item {
width: 120px;
min-height: 120px;
max-height: auto;
float: left;
margin: 3px;
padding: 3px;
}
Here is a reusable Angular service for high quality image / canvas resizing: https://gist.github.com/fisch0920/37bac5e741eaec60e983
The service supports lanczos convolution and step-wise downscaling. The convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.
Example usage:
angular.module('demo').controller('ExampleCtrl', function (imageService) {
// EXAMPLE USAGE
// NOTE: it's bad practice to access the DOM inside a controller,
// but this is just to show the example usage.
// resize by lanczos-sinc filter
imageService.resize($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
// resize by stepping down image size in increments of 2x
imageService.resizeStep($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
})
You always need to check for XACT_STATE()
, irrelevant of the XACT_ABORT
setting. I have an example of a template for stored procedures that need to handle transactions in the TRY/CATCH context at Exception handling and nested transactions:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(),
@message = ERROR_MESSAGE(),
@xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
end catch
end
I had a similar issue where I wanted a banner across the top of the screen that had one image on the left and a repeating image on the right to the edge of the screen. I ended up resolving it like so:
CSS:
.banner_left {
position: absolute;
top: 0px;
left: 0px;
width: 131px;
height: 150px;
background-image: url("left_image.jpg");
background-repeat: no-repeat;
}
.banner_right {
position: absolute;
top: 0px;
left: 131px;
right: 0px;
height: 150px;
background-image: url("right_repeating_image.jpg");
background-repeat: repeat-x;
background-position: top left;
}
The key was the right tag. I'm basically specifying that I want it to repeat from 131px in from the left to 0px from the right.
Using template literals...
var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;
If you use brew to install maven, then the settings file should be in
/usr/local/Cellar/maven/<version>/libexec/conf
Perhaps this what you're looking for - https://www.w3schools.com/css/css3_flexbox.asp
CSS:
#container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.block {
width: 150px;
height: 150px;
margin: 10px;
}
HTML:
<div id="container">
<div class="block">1</div>
<div class="block">2</div>
<div class="block">3</div>
</div>
Can be fixed after the fact by zip -d filename.zip __MACOSX/\*
You need to use a ServerSocket
. You can find an explanation here.
Another possible case (but rare) could be if you have server to server communications and have set server.maxConnections
to a very low value.
In node's core lib net.js it will call clientHandle.close()
which will also cause error ECONNRESET:
if (self.maxConnections && self._connections >= self.maxConnections) {
clientHandle.close(); // causes ECONNRESET on the other end
return;
}
To write inline styling use:
<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>
Inline styling serves a purpose however, it is not recommended in most situations.
The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.
if you have the file structure:
index.html
>>/css/
>>/css/styles.css
Then in your HTML document between <head>
and </head>
write:
<link href="css/styles.css" rel="stylesheet" />
Then, change your div structure to be:
<div id="someidname" class="someclassname">
asdfashdjkfhaskjdf
</div>
In css, you can reference your div from the ID or the CLASS.
To do so write:
.someclassname { height: 100px; }
OR
#someidname { height: 100px; }
Note that if you do both, the one that comes further down the file structure will be the one that actually works.
For example... If you have:
.someclassname { height: 100px; }
.someclassname { height: 150px; }
Then in this situation the height will be 150px.
EDIT:
To answer your secondary question from your edit, probably need overflow: hidden;
or overflow: visible;
. You could also do this:
<div class="span12">
<div style="height:100px;">
asdfashdjkfhaskjdf
</div>
</div>
Another solution might look like this,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
which avoids using an extra variable.
In [Package Manager Console]
try the below
Install-Package NuGet.CommandLine
try this:
(for /f "delims=" %i in (file.unix) do @echo %i)>file.dos
Session protocol:
C:\TEST>xxd -g1 file.unix 0000000: 36 31 36 38 39 36 32 39 33 30 38 31 30 38 36 35 6168962930810865 0000010: 0a 34 38 36 38 39 37 34 36 33 32 36 31 38 31 39 .486897463261819 0000020: 37 0a 37 32 30 30 31 33 37 33 39 31 39 32 38 35 7.72001373919285 0000030: 34 37 0a 35 30 32 32 38 31 35 37 33 32 30 32 30 47.5022815732020 0000040: 35 32 34 0a 524. C:\TEST>(for /f "delims=" %i in (file.unix) do @echo %i)>file.dos C:\TEST>xxd -g1 file.dos 0000000: 36 31 36 38 39 36 32 39 33 30 38 31 30 38 36 35 6168962930810865 0000010: 0d 0a 34 38 36 38 39 37 34 36 33 32 36 31 38 31 ..48689746326181 0000020: 39 37 0d 0a 37 32 30 30 31 33 37 33 39 31 39 32 97..720013739192 0000030: 38 35 34 37 0d 0a 35 30 32 32 38 31 35 37 33 32 8547..5022815732 0000040: 30 32 30 35 32 34 0d 0a 020524..