0 [main] us 0 init_cheap: VirtualAlloc pointer is null, Win32 error 487
AllocationBase 0x0, BaseAddress 0x68570000, RegionSize 0x2A0000, State 0x10000
PortableGit\bin\bash.exe: *** Couldn't reserve space for cygwin's heap, Win32 error 0
This symptom by itself has nothing to do with image bases of executables, corrupted Cygwin's shared memory sections, conflicting versions of DLLs etc.
It's Cygwin code failing to allocate a ~5 MB large chunk of memory for its heap at this fixed address 0x68570000, while only a hole ~2.5 MB large was apparently available there. The relevant code can be seen in msysgit source.
There can be many reasons. In my case it was some other modules loaded at a conflicting address:
The last address would be around 0x68570000 + 5 MB = 0x68C50000, but there are these WOW64-related DLLs loaded from 0x68810000 upwards, which block the allocation.
Whenever there is some shared DLL, Windows in general tries to load it at the same virtual address in all processes to save some relocation processing. It's just a matter of bad luck that these system components got somehow loaded at a conflicting address this time.
Because Git is a rich suite consisting of some low level commands and a lot of helpful utilities, and mostly developed on Unix-like systems. In order to be able to build it and run it without massive rewriting, it need at least a partial Unix-like environment.
To accomplish that, people have invented MinGW and MSYS - a minimal set of build tools to develop programs on Windows in an Unix-like fashion. MSYS also contains a shared library, this msys-1.0.dll
, which helps with some of the compatibility issues between the two platforms during runtime. And many parts of that have been taken from Cygwin, because someone already had to solve the same problems there.
So it's not Cygwin, it's MinGW's runtime DLL what's behaving weird here.
In Cygwin, this code has actually changed a lot since what's in MSYS 1.0 - the last commit message for that file says "Import Cygwin 1.3.4", which is from 2001!
Both current Cygwin and the new version of MSYS - MSYS2 - already have different logic in place, which is hopefully more robust. It's only old versions of Git for Windows which have been still built using the old broken MSYS system.
PATH
can sometimes work because there might be different versions of msys-1.0.dll
in different versions of Git or other MSYS-based applications, which perhaps use different address, different size of this heap etc.msys-1.0.dll
might be a waste of time, because 1) being a DLL, it already has relocation information and 2) "in any version of Windows OS there is no guarantee that a (...) DLL will always load at same address space" anyway (source). The only way this can help is if the msys-1.0.dll
itself loads at the conflicting address it's then trying to use. Apparently that's the case sometimes, as this is what the Git for Windows guys are doing automatically on 32-bit systems.msys-1.0.dll
binary to use a different value for _cygheap_start
and that resolved the problem immediately.I know this is an old post, but another simple option is using the INPUT TYPE="FILE" tag according to compatibility most major browser support this feature.
Is your SQL Server in 'mixed mode authentication' ? This is necessary to login with a SQL server account instead of a Windows login.
You can verify this by checking the properties of the server and then SECURITY, it should be in 'SQL Server and Windows Authentication Mode'
This problem occurs if the user tries to log in with credentials that cannot be validated. This problem can occur in the following scenarios:
Scenario 1: The login may be a SQL Server login but the server only accepts Windows Authentication.
Scenario 2: You are trying to connect by using SQL Server Authentication but the login used does not exist on SQL Server.
Scenario 3: The login may use Windows Authentication but the login is an unrecognized Windows principal. An unrecognized Windows principal means that Windows can't verify the login. This might be because the Windows login is from an untrusted domain.
It's also possible the user put in incorrect information.
The bug is found in pip 10.0.0.
In linux you need to modify file: /usr/bin/pip from:
from pip import main
if __name__ == '__main__':
sys.exit(main())
to this:
from pip import __main__
if __name__ == '__main__':
sys.exit(__main__._main())
If you are using reactiveFormModule and have formGroup defined like this:
public exampleForm = new FormGroup({
name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
email: new FormControl('[email protected]', [Validators.required, Validators.maxLength(50)]),
age: new FormControl(45, [Validators.min(18), Validators.max(65)])
});
than you are able to add a new validator (and keep old ones) to FormControl with this approach:
this.exampleForm.get('age').setValidators([
Validators.pattern('^[0-9]*$'),
this.exampleForm.get('age').validator
]);
this.exampleForm.get('email').setValidators([
Validators.email,
this.exampleForm.get('email').validator
]);
FormControl.validator returns a compose validator containing all previously defined validators.
You could use git reset
(see docs)
This isn't really going to help with your more complex issue but I'm posting this anyway because it is a simple solution for people that aren't doing a global search like you are.
I've simplified the regex in the answer to be clearer (this is not a solution to your exact problem).
var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);
// We only want the group matches in the array
function purify_regex(reResult){
// Removes the Regex specific values and clones the array to prevent mutation
let purifiedArray = [...reResult];
// Removes the full match value at position 0
purifiedArray.shift();
// Returns a pure array without mutating the original regex result
return purifiedArray;
}
// purifiedResult= ["description", "aoeu"]
That looks more verbose than it is because of the comments, this is what it looks like without comments
var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);
function purify_regex(reResult){
let purifiedArray = [...reResult];
purifiedArray.shift();
return purifiedArray;
}
Note that any groups that do not match will be listed in the array as undefined
values.
This solution uses the ES6 spread operator to purify the array of regex specific values. You will need to run your code through Babel if you want IE11 support.
figlegend may be what you're looking for: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend
Example here: http://matplotlib.org/examples/pylab_examples/figlegend_demo.html
Another example:
plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )
or:
fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )
Way too late for an answer, but the original string was in UTF-8 and '\xc2\xa0' is UTF-8 for NO-BREAK SPACE. Simply decode the original string as s.decode('utf-8')
(\xa0 displays as a space when decoded incorrectly as Windows-1252 or latin-1:
s = b'6\xc2\xa0918\xc2\xa0417\xc2\xa0712'
print(s.decode('latin-1')) # incorrectly decoded
u = s.decode('utf8') # correctly decoded
print(u)
print(u.replace('\N{NO-BREAK SPACE}','_'))
print(u.replace('\xa0','-')) # \xa0 is Unicode for NO-BREAK SPACE
6Â 918Â 417Â 712
6 918 417 712
6_918_417_712
6-918-417-712
Every method should be within a class. Your method derivativeQuiz
is outside a class.
public class ClassName {
///your methods
}
Just as others said, you can perform a case sensitive search. Or just change the collation format of a specified column as me. For the User/Password columns in my database I change them to collation through the following command:
ALTER TABLE `UserAuthentication` CHANGE `Password` `Password` VARCHAR(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL;
Yes. 'Z' stands for Zulu time, which is also GMT and UTC.
From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.
Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.
From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.
For Rails 4 you can put the following in an environment file:
# /config/environments/development.rb
config.active_record.logger = nil
If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.
SELECT
a.[CUSTOMER ID],
a.[NAME],
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a
Vectors and matrices can only be of a single type and cbind
and rbind
on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.
(Note that in your rbind
example, the promotion happens within the c
call:
> c(10, "[]", "[[1,2]]")
[1] "10" "[]" "[[1,2]]"
If you want a rectangular structure where the columns can be different types, you want a data.frame
. Any of the following should get you what you want:
> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
v1 v2 v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ v1: num 10 20
$ v2: Factor w/ 1 level "[]": 1 1
$ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using specifically the data.frame
version of cbind
)
> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c(10, 20) : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using cbind
, but making the first a data.frame
so that it combines as data.frames do):
> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c.10..20. : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
This code lists modules imported by your module:
import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]
It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.
It won't list the sys
module or modules imported from it.
If your app is behind a trusted proxy (e.g. an AWS ELB or a correctly configured nginx), this code should work:
app.enable('trust proxy');
app.use(function(req, res, next) {
if (req.secure){
return next();
}
res.redirect("https://" + req.headers.host + req.url);
});
Notes:
you'll have to pre-scale that drawable before you use it as a background
A more pythonic way would be:
try:
os.remove(filename)
except OSError:
pass
Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists()
and follows the python convention of overusing exceptions.
It may be worthwhile to write a function to do this for you:
import os, errno
def silentremove(filename):
try:
os.remove(filename)
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occurred
How about iTextSharp?
iText is a PDF (among others) generation library that is also ported (and kept in sync) to C#.
Another solution consists in pass your function like that (if you've got dynamics vars) : setInterval('funca('+x+','+y+')',500);
A more explicit example, built on Damien's code (calls a test resource at http://httpbin.org/). For python3. Note that if the server redirects to another URL, uri
in add_password
has to contain the new root URL (it's possible to pass a list of URLs, also).
import ssl
import urllib.parse
import urllib.request
def get_resource(uri, user, passwd=False):
"""
Get the content of the SSL page.
"""
uri = 'https://httpbin.org/basic-auth/user/passwd'
user = 'user'
passwd = 'passwd'
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, uri, user, passwd)
auth_handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
opener = urllib.request.build_opener(auth_handler, urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)
return urllib.request.urlopen(uri).read()
<div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>
EDIT 01-10-2014:
Since this question is so popular this answer has been improved.
The example above will only get the values from RouteData
, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest
. Fastest way is by calling (as TruMan pointed out) `Request.Querystring' so the answer should be:
<div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div>
You can also check RouteValues vs QueryString MVC?
EDIT 03-05-2019:
Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query
object from Context.Request
path. So it would be:
<div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div>
Please notice I am using StringValues("1")
in the statement because Query
returns StringValues
struct instead of pure string
. That's cleanes way for this scenerio which I've found.
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
Make left-margin: 2em or so will push the whole text including first line to right 2em. Than add text-indent (applicable to first line) as -2em or so.. This brings first line back to start without margin. I tried it for list tags
<style>
ul li{
margin-left: 2em;
text-indent: -2em;
}
</style>
Though I like Justin's response, I feel it more accurately represents a filter rather than a search. What if I want to know about cars with names that start with cam?
The way I see it, you could build it into the way you handle specific resources:
/cars/cam*
Or, you could simply add it into the filter:
/cars/doors/4/name/cam*/colors/red,blue,green
Personally, I prefer the latter, however I am by no means an expert on REST (having first heard of it only 2 or so weeks ago...)
you can use UPDATE command.
UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Use $(this)
for get the desire element.
function openAll()
{
$("tr.b_row").each(function(){
var a_href = $(this).find('.cpt h2 a').attr('href');
alert ("Href is: "+a_href);
});
}
It's important to store the data in a way that it can be retrieved in the languages used. C-language stores in row-major order (all of first row comes first, then all of second row,...) with every index running from 0 to it's dimension-1. So the order of array x[2][3] is x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2]. So in C language, x[i][j] is stored the same place as a 1-dimensional array entry x1dim[ i*3 +j]. If the data is stored that way, it is easy to retrieve in C language.
Fortran and MATLAB are different. They store in column-major order (all of first column comes first, then all of second row,...) and every index runs from 1 to it's dimension. So the index order is the reverse of C and all the indices are 1 greater. If you store the data in the C language order, FORTRAN can find X_C_language[i][j] using X_FORTRAN(j+1, i+1). For instance, X_C_language[1][2] is equal to X_FORTRAN(3,2). In 1-dimensional arrays, that data value is at X1dim_C_language[2*Cdim2 + 3], which is the same position as X1dim_FORTRAN(2*Fdim1 + 3 + 1). Remember that Cdim2 = Fdim1 because the order of indices is reversed.
MATLAB is the same as FORTRAN. Ada is the same as C except the indices normally start at 1. Any language will have the indices in one of those C or FORTRAN orders and the indices will start at 0 or 1 and can be adjusted accordingly to get at the stored data.
Sorry if this explanation is confusing, but I think it is accurate and important for a programmer to know.
This is maybe not the case of original OP question, but: if you exceeds the default max size, this maybe a symptom of some other issue you have. in my case, I had the warrning, but finally it turned into a FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory. the reason was that i dynamically imported the current module, so this ended up with an endless loop...
In CentOS 6 and Solr 4.4.0
I had to comp some lib files to get this error addressed
cp ~/solr-4.4.0/example/lib/ext/* /usr/share/tomcat6/lib/
There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false,"
code line in main .dart file. So I think these methods are effective:
"Dart DevTools"
from extensions. After installation, you can easily find "Dart DevTools"
text icon at the bottom of the VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.NOTE:-- Dart DevTools is a dart language debugger extension in VS Code
Dart DevTools
is already installed in your VS Code, then you can directly open the google chrome and open this URL = "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX"
NOTE:-- In this link replace "XXXXX" by 5 digit port-id (on which your flutter app is running) which will vary whenever you use "flutter run"
command and replace "ZZZZZ" by your global(unchangeable) 5 digit debugger-id
NOTE:-- these dart dev tools are only for "Google Chrome Browser"
I had the same error. Creating a new AVD with the appropriate API level solved my problem.
If you have named tuples you can do this:
results = [t.age for t in mylist if t.person_id == 10]
Otherwise use indexes:
results = [t[1] for t in mylist if t[0] == 10]
Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _)
to unpack a six item tuple.
That's an old question, I know. But, according to me, it is missing proper answer.
The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.
You may find the following links interesting:
In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:
#!/bin/sh
# POST-COMMIT HOOK
REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log
MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
echo post-commit $* >> $LOGFILE 2>&1
# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENK >> $LOGFILE 2>&1
curl -qs $JENK >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENKtest >> $LOGFILE 2>&1
curl -qs $JENKtest >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
exit 0
For getting the list of ip addresses associated, you can use netstat command
netstat -rn
This gives a long list of ip addresses and it is not easy to find the required field. The sample result is as following:
Routing tables
Internet:
Destination Gateway Flags Refs Use Netif Expire
default 192.168.195.1 UGSc 17 0 en2
127 127.0.0.1 UCS 0 0 lo0
127.0.0.1 127.0.0.1 UH 1 254107 lo0
169.254 link#7 UCS 0 0 en2
192.168.195 link#7 UCS 3 0 en2
192.168.195.1 0:27:22:67:35:ee UHLWIi 22 397 en2 1193
192.168.195.5 127.0.0.1 UHS 0 0 lo0
More result is truncated.......
The ip address of gateway is in the first line; one with default at its first column.
To display only the selected lines of result, we can use grep command along with netstat
netstat -rn | grep 'default'
This command filters and displays those lines of result having default. In this case, you can see result like following:
default 192.168.195.1 UGSc 14 0 en2
If you are interested in finding only the ip address of gateway and nothing else you can further filter the result using awk. The awk command matches pattern in the input result and displays the output. This can be useful when you are using your result directly in some program or batch job.
netstat -rn | grep 'default' | awk '{print $2}'
The awk command tells to match and print the second column of the result in the text. The final result thus looks like this:
192.168.195.1
In this case, netstat displays all result, grep only selects the line with 'default' in it, and awk further matches the pattern to display the second column in the text.
You can similarly use route -n get default command to get the required result. The full command is
route -n get default | grep 'gateway' | awk '{print $2}'
These commands work well in linux as well as unix systems and MAC OS.
For something simple, you can combine ls with sort. For just a list of file names:
ls -1 | sort
To sort them in reverse order:
ls -1 | sort -r
You use a function component:
const def = (props) => {
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>
<div ...>
<someComponent
do something
/>
if (some condition) {
do this
} else {
do that
}
</div>
};
In the function component, you have to write a return or just add parentheses. After the added return or parentheses your code should look like this:
const def = (props) => ({
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>
<div ...>
<someComponent
do something
/>
if (some condition) {
do this
} else {
do that
}
</div>
});
How do I have a div not take up space until it is timed to come in (using CSS for the timing.)
Here is my solution to the same problem.
Moreover I have an onclick
on the last frame loading another slideshow, and it must not be clickable until the last frame is visible.
Basically my solution is to keep the div
1 pixel high using a scale(0.001)
, zooming it when I need it. If you don't like the zoom effect you can restore the opacity
to 1 after zooming the slide.
#Slide_TheEnd {
-webkit-animation-delay: 240s;
animation-delay: 240s;
-moz-animation-timing-function: linear;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-moz-animation-duration: 20s;
-webkit-animation-duration: 20s;
animation-duration: 20s;
-moz-animation-name: Slide_TheEnd;
-webkit-animation-name: Slide_TheEnd;
animation-name: Slide_TheEnd;
-moz-animation-iteration-count: 1;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
-moz-animation-direction: normal;
-webkit-animation-direction: normal;
animation-direction: normal;
-moz-animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
transform: scale(0.001);
background: #cf0;
text-align: center;
font-size: 10vh;
opacity: 0;
}
@-moz-keyframes Slide_TheEnd {
0% { opacity: 0; transform: scale(0.001); }
10% { opacity: 1; transform: scale(1); }
95% { opacity: 1; transform: scale(1); }
100% { opacity: 0; transform: scale(0.001); }
}
Other keyframes are removed for the sake of bytes. Please disregard the odd coding, it is made by a php script picking values from an array and str_replacing a template: I'm too lazy to retype everything for every proprietary prefix on a 100+ divs slideshow.
Since scipy
's imread
is deprecated, use imageio.imread
.
pip install imageio
height, width, channels = imageio.imread(filepath).shape
Cross browser compatible JS solution:
var e = document.getElementById('elem');_x000D_
var spin = false;_x000D_
_x000D_
var spinner = function(){_x000D_
e.classList.toggle('running', spin);_x000D_
if (spin) setTimeout(spinner, 2000);_x000D_
}_x000D_
_x000D_
e.onmouseover = function(){_x000D_
spin = true;_x000D_
spinner();_x000D_
};_x000D_
_x000D_
e.onmouseout = function(){_x000D_
spin = false;_x000D_
};
_x000D_
body { _x000D_
height:300px; _x000D_
}_x000D_
#elem {_x000D_
position:absolute;_x000D_
top:20%;_x000D_
left:20%;_x000D_
width:0; _x000D_
height:0;_x000D_
border-style: solid;_x000D_
border-width: 75px;_x000D_
border-color: red blue green orange;_x000D_
border-radius: 75px;_x000D_
}_x000D_
_x000D_
#elem.running {_x000D_
animation: spin 2s linear 0s infinite;_x000D_
}_x000D_
_x000D_
@keyframes spin { _x000D_
100% { transform: rotate(360deg); } _x000D_
}
_x000D_
<div id="elem"></div>
_x000D_
They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).
Well this is a solution for defining IMG presentation (no really the image) in CSS style.
It works like a charm :)
The fastest way to check if a string contains another string is using indexOf
:
if (code.indexOf('ST1') !== -1) {
// string code has "ST1" in it
} else {
// string code does not have "ST1" in it
}
If you call printStackTrace()
on an exception the trace is written to System.err
and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)
).
Doing that allows you to:
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
See the Java EE 7 Json specification. This is the right way:
String json = Json.createObjectBuilder()
.add("key1", "value1")
.add("key2", "value2")
.build()
.toString();
Run from the project folder
msbuild /p:DeployOnBuild=true /p:PublishProfile="release-file.pubxml" /p:AspnetMergePath="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools" /p:Configuration=Release
This takes care of web.config Transform and AspnetMergePath
Ok, so the easiest method to create several plots is this:
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
plt.figure()
plt.plot(x[i],y[i])
# Show/save figure as desired.
plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()
Note that you need to create a figure
every time or pyplot
will plot in the first one created.
If you want to create several data series all you need to do is:
import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')
You could automate it by having a list of colours like ['r','g','b','k']
and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.
for i in range(len(x)):
plt.plot(x[i],y[i],colours[i])
plt.show()
Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.
17 Dec 2019: added plt.show()
and plt.figure()
calls to clarify this part of the story.
In ECMAScript 6, a one-line answer using the arrow function:
const captialize = words => words.split(' ').map( w => w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
you can use simply inside your controller:
return response()->download($filePath);
Happy coding :)
Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.
Contacts is here for example.
Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.
To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.
And others:
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
Checking if line segments intersect is very easy with Shapely library using intersects
method:
from shapely.geometry import LineString
line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 0)])
print(line.intersects(other))
# True
line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 2)])
print(line.intersects(other))
# False
There is a problem in that whilst:
LIKE 'WC[[]R]S123456'
and:
LIKE 'WC\[R]S123456' ESCAPE '\'
Both work for SQL Server but neither work for Oracle.
It seems that there is no ISO/IEC 9075 way to recognize a pattern involving a left brace.
Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:
@"first" @"second"
And it will result in:
@"firstsecond"
You can not use it with NSString objects, only with literals, but it can be useful in some cases.
In general compact is preferable to repairDatabase. But one advantage of repair over compact is you can issue repair to the whole cluster. compact you have to log into each shard, which is kind of annoying.
import UIKit
extension UIView {
func addShadow(shadowColor: UIColor, offSet: CGSize, opacity: Float, shadowRadius: CGFloat, cornerRadius: CGFloat, corners: UIRectCorner, fillColor: UIColor = .white) {
let shadowLayer = CAShapeLayer()
let size = CGSize(width: cornerRadius, height: cornerRadius)
let cgPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size).cgPath //1
shadowLayer.path = cgPath //2
shadowLayer.fillColor = fillColor.cgColor //3
shadowLayer.shadowColor = shadowColor.cgColor //4
shadowLayer.shadowPath = cgPath
shadowLayer.shadowOffset = offSet //5
shadowLayer.shadowOpacity = opacity
shadowLayer.shadowRadius = shadowRadius
self.layer.addSublayer(shadowLayer)
}
}
This should do:
$chunk = "abc\tdef\tghi";
Here is a link to an article with more extensive examples.
The line starting ALREADYEXISTS
uses ’
as the closing quote, it should be using '
. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.
I have just used dompdf and the code was a little different but it worked.
Here it is:
require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('Brochure.pdf', $output);
Only difference here is that all of the files in the include directory are included.
Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.
So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money)
is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw
method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
This worked for me in El Capitan
brew install pkg-config libffi openssl
env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install cryptography
You can also check the thread here : https://github.com/pyca/cryptography/issues/2350
The problem I was having is that I was only using https for my GitHub account. I needed to make sure that my GitHub account was setup for ssh access and that GitHub and heroku were both using the same public keys. These are the steps I took:
Navigate to the ~/.ssh directory and delete the id_rsa and id_rsa.pub if they are there. I started with new keys, though it might not be necessary.
$ cd ~/.ssh
$ rm id_rsa id_rsa.pub
Login to heroku, create a new site and add your public keys:
$ heroku login
...
$ heroku create
$ heroku keys:add
$ git push heroku master
You need to use:
await client.PostAsync(uri, content);
Something like that:
var comment = "hello world";
var questionId = 1;
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("comment", comment),
new KeyValuePair<string, string>("questionId", questionId)
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);
And if you need to get the response after post, you should use:
var stringContent = await response.Content.ReadAsStringAsync();
Hope it helps ;)
I would prefer not use Count function at all:
IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
<do smth>
For example if you want to check if user exists before inserting it into the database the query can look like this:
IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END
This won't show custom events like those your script might create if it's a jquery plugin. for example :
jQuery(function($){
var ThingName="Something";
$("body a").live('click', function(Event){
var $this = $(Event.target);
$this.trigger(ThingName + ":custom-event-one");
});
$.on(ThingName + ":custom-event-one", function(Event){
console.log(ThingName, "Fired Custom Event: 1", Event);
})
});
The Event Panel under Scripts in chrome developer tools will not show you "Something:custom-event-one"
Here is a reference if someone is looking for Scala implementation:
scala> import scala.collection.mutable.LinkedList
import scala.collection.mutable.LinkedList
scala> def reverseLinkedList[A](ll: LinkedList[A]): LinkedList[A] =
ll.foldLeft(LinkedList.empty[A])((accumulator, nextElement) => nextElement +: accumulator)
reverseLinkedList: [A](ll: scala.collection.mutable.LinkedList[A])scala.collection.mutable.LinkedList[A]
scala> reverseLinkedList(LinkedList("a", "b", "c"))
res0: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(c, b, a)
scala> reverseLinkedList(LinkedList("1", "2", "3"))
res1: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(3, 2, 1)
Laravel sometimes does not support {!! Form::open(['url' => 'posts/store']) !!}
for security reasons. That's why the error has happened. You can solve this error by simply replacing the below code
{!! Form::open(array('route' => 'posts.store')) !!}
Error Code {!! Form::open(['url' => 'posts/store']) !!}
Correct Code {!! Form::open(array('route' => 'posts.store')) !!}
The first solution does not work for any UTF-8 alphabet. (It will cut text such as ????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø
== Tromso
).
```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```
see Chunk Options in the Knitr docs
Solution: Edit and save the file!
From VisualStudio go to the View and expand to see it's resx file
Right-click menu select OpenWith... XML (Text) Editor.
Just add a space at the end and save.
I've made some research and found that Richard Watson's solution is fastest in most cases. That's the table with results of every solution in the post (except those use Regex because it throws exceptions while parsing string like "test{test")
Name | Short/char | Long/char | Short/short| Long/short | Long/long |
Inspite | 134| 1853| 95| 1146| 671|
LukeH_1 | 346| 4490| N/A| N/A| N/A|
LukeH_2 | 152| 1569| 197| 2425| 2171|
Bobwienholt | 230| 3269| N/A| N/A| N/A|
Richard Watson| 33| 298| 146| 737| 543|
StefanosKargas| N/A| N/A| 681| 11884| 12486|
You can see that in case of finding number of occurences of short substrings (1-5 characters) in short string(10-50 characters) the original algorithm is preferred.
Also, for multicharacter substring you should use the following code (based on Richard Watson's solution)
int count = 0, n = 0;
if(substring != "")
{
while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
{
n += substring.Length;
++count;
}
}
When setting a variable make sure you have no spaces before and/or after the =
sign. I literally spent an hour trying to figure this out, trying all kinds of solutions! This is not cool.
Correct:
WTFF=`echo "stuff"`
echo "Example: $WTFF"
Will Fail with error "stuff: not found" or similar
WTFF= `echo "stuff"`
echo "Example: $WTFF"
You should be able to set the server.session.timeout
in your application.properties file.
ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html
This query gets the columns name
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
And this one gets the count
SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'YourTableName'
Try Request.Url.Query
if you want the raw querystring as a string.
I like sliding over arguments for relatively simple configurations.
var name = ""
var port = 0
var ip = ""
args.sliding(2, 2).toList.collect {
case Array("--ip", argIP: String) => ip = argIP
case Array("--port", argPort: String) => port = argPort.toInt
case Array("--name", argName: String) => name = argName
}
Where can I download (certified) 64 bit Apache httpd binaries for Windows?
Right now, there are none. The Apache Software Foundation produces Open Source Software. The 32 bit binaries provided are a courtesy of the community members.
Though there are some unofficial e.g. http://www.apachelounge.com/download/win64/, but I have no idea if they can be trusted.
I had the same problem, after some Windows 8.0 crash and update, on msys git 1.9. I didn't find any msys/git in my path, so I just added it in windows local-user envinroment settings. It worked without restarting.
Basically, similiar to RobertB, but I didn't have any git/msys in my path.
Btw:
I tried using rebase -b blablabla msys.dll, but had error "ReBaseImage (msys-1.0.dll) failed with last error = 6"
if you need this quickly and don't have time debugging, I noticed "Git Bash.vbs" in Git directory successfuly starts bash shell.
Another way to do this is to define a base (abstract) test class that your actual test classes will extend :
@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles("staging")
public abstract class BaseIntegrationTest {
}
Concrete test :
public class SampleSearchServiceTest extends BaseIntegrationTest{
@Inject
private SampleSearchService service;
@Test
public void shouldInjectService(){
assertThat(this.service).isNotNull();
}
}
This allows you to extract more than just the @ActiveProfiles
annotation. You could also imagine more specialised base classes for different kinds of integration tests, e.g. data access layer vs service layer, or for functional specialties (common @Before
or @After
methods etc).
It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.
Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.
You can have multiple .gitignore
, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore
: git check-ignore -v -- afile
.
And you can have different version of a .gitignore
file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.
If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore
files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.
Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile
in order to see which gitignore run (from which .gitignore
file) is applied to 'yourfile
', and better understand why said file is ignored.
See "which gitignore
rule is ignoring my file?"
Now you can use insert
method instead add
' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")
$total_ratings
is an array, which you can't use for a division.
From above:
$total_ratings = mysqli_fetch_array($result);
=IF(A2="Y","Male",IF(A2="N","Female",""))
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py
and interactive.py
have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin
acts like a standard Python file object, so ssh_stdin.write
should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write
method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command
method is implemented for all the gory details.
'T'
and 'Z'
are considered here as constants. You need to pass Z
without the quotes. Moreover you need to specify the timezone in the input string.
Example : 2013-09-29T18:46:19-0700
And the format as "yyyy-MM-dd'T'HH:mm:ssZ"
A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort, etc. And some sorting algorithms are not, like Heap Sort, Quick Sort, etc.
However, any given sorting algo which is not stable can be modified to be stable. There can be sorting algo specific ways to make it stable, but in general, any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys considers position as a factor for objects with equal keys.
References: http://www.math.uic.edu/~leon/cs-mcs401-s08/handouts/stability.pdf http://en.wikipedia.org/wiki/Sorting_algorithm#Stability
Select
CASE
WHEN listing.OfferText is null or listing.OfferText = '' THEN company.OfferText
ELSE COALESCE(Company.OfferText, '')
END As Offer_Text,
from tbl_directorylisting listing
Inner Join tbl_companymaster company
On listing.company_id= company.company_id
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
This works for me
# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
return im_bytes
I'd like to clarify a few things:
pandas.Series.tolist()
. I'm not sure why the top voted answer
leads off with using pandas.Series.values.tolist()
since as far as I can tell, it adds syntax/confusion with no added benefit.tst[lookupValue][['SomeCol']]
is a dataframe (as stated in the
question), not a series (as stated in a comment to the question). This is because tst[lookupValue]
is a dataframe, and slicing it with [['SomeCol']]
asks for
a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you
remove the extra set of brackets, as in
tst[lookupValue]['SomeCol']
, then you are asking for just that one
column rather than a list of columns, and thus you get a series back.pandas.Series.tolist()
, so you should
definitely skip the second set of brackets in this case. FYI, if you
ever end up with a one-column dataframe that isn't easily avoidable
like this, you can use pandas.DataFrame.squeeze()
to convert it to
a series.tst[lookupValue]['SomeCol']
is getting a subset of a particular column via
chained slicing. It slices once to get a dataframe with only certain rows
left, and then it slices again to get a certain column. You can get
away with it here since you are just reading, not writing, but
the proper way to do it is tst.loc[lookupValue, 'SomeCol']
(which returns a series).ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
Demo Code:
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
Result:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
On windows, nearly all AMPP (Apache,MySQL,PHP,PHPmyAdmin) packages don't include a mail server (but nearly all naked linuxes do have!). So, when using PHP under windows, you need to setup a mail server!
Imo the best and most simple tool ist this: http://smtp4dev.codeplex.com/
SMTP4Dev is a simple one-file mail server tool that does collect the mails it send (so it does not really sends mail, it just keeps them for development). Perfect tool.
Put a Console.Read() as the last line in your program. That will prevent it from closing until you press a key
static void Main(string[] args)
{
StringAddString s = new StringAddString();
Console.Read();
}
Android: where to run keytool command in android
Keytool command can be run at your dos command prompt, if JRE has been set in your classpath variable.
For example, if you want to get the MD5 Fingerprint of the SDK Debug Certificate for android,
just run the following command...
C:\Documents and Settings\user\.android> keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android
where C:\Documents and Settings\user\.android>
is the path which contains the debug.keystore
that has to be certified.
For detailed information, please visit http://code.google.com/android/add-ons/google-apis/mapkey.html#getdebugfingerprint
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.
CREATE PROCEDURE SP1 AS
EXEC SP2
PRINT 'Done'
you can also quote string
''+document.location+''.substring(2,3);
You can use SQL on the command line:
echo 'CREATE DATABASE dbname;' | mysql <...>
Or you can use mysqladmin
:
mysqladmin create dbname
Alamofire Fetch data with POST,Parameter and Headers
func feedbackApi(){
DispatchQueue.main.async {
let headers = [
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "------"
]
let url = URL(string: "---------")
var parameters = [String:AnyObject]()
parameters = [
"device_id":"-----" as AnyObject,
"user_id":"----" as AnyObject,
"cinema_id":"-----" as AnyObject,
"session_id":"-----" as AnyObject,
]
Alamofire.request(url!, method: .post, parameters: parameters,headers:headers).responseJSON { response in
switch response.result{
case.success(let data):
self.myResponse = JSON(data)
print(self.myResponse as Any)
let slide = self.myResponse!["sliders"]
print(slide)
print(slide.count)
for i in 0..<slide.count{
let single = Sliders(sliderJson: slide[i])
self.slidersArray.append(single)
}
DispatchQueue.main.async {
self.getSliderCollection.reloadData()
}
case .failure(let error):
print("dddd",error)
}
}
}
}
The problem with calling async void is that
you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing
Here are the three ways to call an async function:
async Task<T> SomethingAsync() { ... return t; } async Task SomethingAsync() { ... } async void SomethingAsync() { ... }
In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.
In the first case, the function returns a task that eventually produces the t.
In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.
The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.
The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.
You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.
You can then import project to your workspace, copy paste project to your new workspace folder, then
File?Import?Existing project in to workspace?select project.
Surprised that no one mentioned how a logger is created/retrieved. For example, below shows how Log4J logger is retrieved.
// Retrieve a logger named according to the value of the name parameter. If the named logger already exists, then the existing instance will be returned. Otherwise, a new instance is created.
public static Logger getLogger(String name)
There are some levels of indirections, but the key part is below method which pretty much tells everything about how it works. It uses a hash table to store the exiting loggers and the key is derived from name. If the logger doesn't exist for a give name, it uses a factory to create the logger and then adds it to the hash table.
69 Hashtable ht;
...
258 public
259 Logger getLogger(String name, LoggerFactory factory) {
260 //System.out.println("getInstance("+name+") called.");
261 CategoryKey key = new CategoryKey(name);
262 // Synchronize to prevent write conflicts. Read conflicts (in
263 // getChainedLevel method) are possible only if variable
264 // assignments are non-atomic.
265 Logger logger;
266
267 synchronized(ht) {
268 Object o = ht.get(key);
269 if(o == null) {
270 logger = factory.makeNewLoggerInstance(name);
271 logger.setHierarchy(this);
272 ht.put(key, logger);
273 updateParents(logger);
274 return logger;
275 } else if(o instanceof Logger) {
276 return (Logger) o;
277 }
...
If you want a really simple answer:
s_1 = "abc def ghi"
s_2 = "def ghi abc"
flag = 0
for i in s_1:
if i not in s_2:
flag = 1
if flag == 0:
print("a == b")
else:
print("a != b")
The first basic thing to understand is the difference in architectures.
One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:
Browser <---> Controller <---> Model
| |
+-View-+
The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.
On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.
That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView
where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.
But when we use @ResponseBody
, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use
@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)
to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces
, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces
to MediaType.APPLICATION_XML_VALUE
and I believe you need to configure the HttpMessageConverter
for JAXB. As for the JSON MappingJacksonHttpMessageConverter
configured, when we have Jackson on the classpath.
I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.
In this sample in catch block i change the value of counter and it will break while block:
class TestBreak {
public static void main(String[] a) {
int counter = 0;
while(counter<5) {
try {
counter++;
int x = counter/0;
}
catch(Exception e) {
counter = 1000;
}
}
}
}k
syntax:
git reflog --date=local | grep checkout: | grep ${current_branch} | tail -1
example:
git reflog --date=local | grep checkout: | grep dev-2.19.0 | tail -1
result:
cc7a3a8ec HEAD@{Wed Apr 29 14:58:50 2020}: checkout: moving from dev-2.18.0 to dev-2.19.0
I recently used ez_setup.py
as well and I did a tutorial on how to install it. The tutorial has snapshots and simple to follow. You can find it below:
Installing easy_install Using ez_setup.py
I hope you find this helpful.
You can do this: add oldvalue attribute to html element, add set oldvalue when user click. Then onchange event use oldvalue.
<input type="text" id="test" value ="ABS" onchange="onChangeTest(this)" onclick="setoldvalue(this)" oldvalue="">
<script>
function setoldvalue(element){
element.setAttribute("oldvalue",this.value);
}
function onChangeTest(element){
element.setAttribute("value",this.getAttribute("oldvalue"));
}
</script>
Taken from this answer.
packages.config
file. This is the first time I see ignoring a problem actually makes it go away...
Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can
Get device list with this command
xcrun simctl list devices
Console
== Devices ==
-- iOS 13.5 --
iPhone 6s (9981E5A5-48A8-4B48-B203-1C6E73243E83) (Shutdown)
iPhone 8 (FC540A6C-F374-4113-9E71-1291790C8C4C) (Shutting Down)
iPhone 8 Plus (CAC37462-D873-4EBB-9D71-7C6D0C915C12) (Shutdown)
iPhone 11 (347EFE28-9B41-4C1A-A4C3-D99B49300D8B) (Shutting Down)
iPhone 11 Pro (5AE964DC-201C-48C9-BFB5-4506E3A0018F) (Shutdown)
iPhone 11 Pro Max (48EE985A-39A6-426C-88A4-AA1E4AFA0133) (Shutdown)
iPhone SE (2nd generation) (48B78183-AFD7-4832-A80E-AF70844222BA) (Shutdown)
iPad Pro (9.7-inch) (2DEF27C4-6A18-4477-AC7F-FB31CCCB3960) (Shutdown)
iPad (7th generation) (36A4AF6B-1232-4BCB-B74F-226E025225E4) (Shutdown)
iPad Pro (11-inch) (2nd generation) (79391BD7-0E55-44C8-B1F9-AF92A1D57274) (Shutdown)
iPad Pro (12.9-inch) (4th generation) (ED90A31F-6B20-4A6B-9EE9-CF22C01E8793) (Shutdown)
iPad Air (3rd generation) (41AD1CF7-CB0D-4F18-AB1E-6F8B6261AD33) (Shutdown)
-- tvOS 13.4 --
Apple TV 4K (51925935-97F4-4242-902F-041F34A66B82) (Shutdown)
-- watchOS 6.2 --
Apple Watch Series 5 - 40mm (7C50F2E9-A52B-4E0D-8B81-A811FE995502) (Shutdown)
Apple Watch Series 5 - 44mm (F7D8C256-DC9F-4FDC-8E65-63275C222B87) (Shutdown)
Select Simulator string without ID here is an example.
iPad Pro (12.9-inch) (4th generation)
Final command
iPhone
• iPhone 6s
react-native run-ios --simulator="iPhone 6s"
• iPhone 8
react-native run-ios --simulator="iPhone 8"
• iPhone 8 Plus
react-native run-ios --simulator="iPhone 8 Plus"
• iPhone 11
react-native run-ios --simulator="iPhone 11"
• iPhone 11 Pro
react-native run-ios --simulator="iPhone 11 Pro"
• iPhone 11 Pro Max
react-native run-ios --simulator="iPhone 11 Pro Max"
• iPhone SE (2nd generation)
react-native run-ios --simulator="iPhone SE (2nd generation)"
iPad
• iPad Pro (9.7-inch)
react-native run-ios --simulator="iPad Pro (9.7-inch)"
• iPad (7th generation)
react-native run-ios --simulator="iPad (7th generation)"
• iPad Pro (11-inch) (2nd generation)
react-native run-ios --simulator="iPad Pro (11-inch) (2nd generation)"
• iPad Pro (12.9-inch) 4th generation
react-native run-ios --simulator="iPad Pro (12.9-inch) (4th generation)"
• iPad Air (3rd generation)
react-native run-ios --simulator="iPad Air (3rd generation)"
I got the above error message while trying to access a file from Internal Storage using openFileInput("/Dir/data.txt")
method with subdirectory Dir
.
You cannot access sub-directories using the above method.
Try something like:
FileInputStream fIS = new FileInputStream (new File("/Dir/data.txt"));
let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
layout?.minimumLineSpacing = 8
During my research for a similar case, I have been ending up by checking the stack trace in the subclass method to find out from where the call is coming from. There are probably smarter ways to do so, but it works out for me and it's a dynamic approach.
public void method2(){
Exception ex=new Exception();
StackTraceElement[] ste=ex.getStackTrace();
if(ste[1].getClassName().equals(this.getClass().getSuperclass().getName())){
super.method2();
}
else{
//subclass method2 code
}
}
I think the question to have a solution for the case is reasonable. There are of course ways to solve the issue with different method names or even different parameter types, like already mentioned in the thread, but in my case I dindn't like to confuse by different method names.
you just need to give focus to the next input field (by invoking focus()method on that input element), for example if you're using jQuery this code will simulate the tab key when enter is pressed:
var inputs = $(':input').keypress(function(e){
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
We render the PDF file pages as PNG files on the server using JPedal (a java library). That, combined with some javascript, gives us high control over visualization and navigation.
Postcodes are subject to change, and the only true way of validating a postcode is to have the complete list of postcodes and see if it's there.
But regular expressions are useful because they:
But regular expressions tend to be difficult to maintain, especially for someone who didn't come up with it in the first place. So it must be:
That means that most of the regular expressions in this answer aren't good enough. E.g. I can see that [A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]
is going to match a postcode area of the form AA1A — but it's going to be a pain in the neck if and when a new postcode area gets added, because it's difficult to understand which postcode areas it matches.
I also want my regular expression to match the first and second half of the postcode as parenthesised matches.
So I've come up with this:
(GIR(?=\s*0AA)|(?:[BEGLMNSW]|[A-Z]{2})[0-9](?:[0-9]|(?<=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])[A-HJ-NP-Z])?)\s*([0-9][ABD-HJLNP-UW-Z]{2})
In PCRE format it can be written as follows:
/^
( GIR(?=\s*0AA) # Match the special postcode "GIR 0AA"
|
(?:
[BEGLMNSW] | # There are 8 single-letter postcode areas
[A-Z]{2} # All other postcode areas have two letters
)
[0-9] # There is always at least one number after the postcode area
(?:
[0-9] # And an optional extra number
|
# Only certain postcode areas can have an extra letter after the number
(?<=N1|E1|SE1|SW1|W1|NW1|EC[0-9]|WC[0-9])
[A-HJ-NP-Z] # Possible letters here may change, but [IO] will never be used
)?
)
\s*
([0-9][ABD-HJLNP-UW-Z]{2}) # The last two letters cannot be [CIKMOV]
$/x
For me this is the right balance between validating as much as possible, while at the same time future-proofing and allowing for easy maintenance.
Referring to the answer of jnml, you could prevent new instances of Base type by not exporting the Base type at all (i.e. write it lowercase). If needed, you may make an exportable interface that has a method that returns a base type. This interface could be used in functions from the outside that deal with Bases, i.e.
package a
type base int
const (
A base = iota
C
T
G
)
type Baser interface {
Base() base
}
// every base must fulfill the Baser interface
func(b base) Base() base {
return b
}
func(b base) OtherMethod() {
}
package main
import "a"
// func from the outside that handles a.base via a.Baser
// since a.base is not exported, only exported bases that are created within package a may be used, like a.A, a.C, a.T. and a.G
func HandleBasers(b a.Baser) {
base := b.Base()
base.OtherMethod()
}
// func from the outside that returns a.A or a.C, depending of condition
func AorC(condition bool) a.Baser {
if condition {
return a.A
}
return a.C
}
Inside the main package a.Baser
is effectively like an enum now.
Only inside the a package you may define new instances.
don't have to chain so many tools. Just one awk command does the job
COMPANY_NAME=$(awk -F"=" '/company_name/{gsub(/;$/,"",$2) ;print $2}' file.txt)
Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).
The command line option
-verbose:gc
causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:[GC 325407K->83000K(776768K), 0.2300771 secs] [GC 325816K->83372K(776768K), 0.2454258 secs] [Full GC 267628K->83769K(776768K), 1.8479984 secs]
Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g.,
325407K->83000K
from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.The next number in parentheses (e.g.,
(776768K)
again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.The last item on the line (e.g.,
0.2300771 secs
) indicates the time taken to perform the collection; in this case approximately a quarter of a second.The format for the major collection in the third line is similar.
The format of the output produced by
-verbose:gc
is subject to change in future releases.
I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?
This is an old question, but I am still able to see this at the top of the search result of Google, so I guess it would be meaningful to add a new answer 4 years after the question is asked.
First of all, there is better support in storing JSON in RDBMS. You may consider switching to PostgreSQL (although MySQL has supported JSON since v5.7.7). PostgreSQL uses very similar SQL commands as MySQL except they support more functions. One of the functions they added is that they provide JSON data type and you are now able to query the JSON stored. (Some reference on this) If you are not making up the query directly in your program, for example, using PDO in php or eloquent in Laravel, all you need to do is just to install PostgreSQL on your server and change database connection settings. You don't even need to change your code.
Most of the time, as the other answers suggested, storing data as JSON directly in RDBMS is not a good idea. There are some exception though. One situation I can think of is a field with variable number of linked entry.
For example, for storing tag of a blog post, normally you will need to have a table for blog post, a table of tag and a matching table. So, when the user wants to edit a post and you need to display which tag is related to that post, you will need to query 3 tables. This will damage the performance a lot if your matching table / tag table is long.
By storing the tags as JSON in the blog post table, the same action only requires a single table search. The user will then be able to see the blog post to be edit quicker, but this will damage the performance if you want to make a report on what post is linked to a tag, or maybe search by tag.
You may also try to de-normalize the database. By duplicating the data and storing the data in both ways, you can receive benefit of both method. You will just need a little bit more time to store your data and more storage space (which is cheap comparing to the cost of more computing power)
In terms of how this is implemented, this changes the method - from OrderBy/ThenBy to OrderByDescending/ThenByDescending. However, you can apply the sort separately to the main query...
var qry = from .... // or just dataList.AsEnumerable()/AsQueryable()
if(sortAscending) {
qry = qry.OrderBy(x=>x.Property);
} else {
qry = qry.OrderByDescending(x=>x.Property);
}
Any use? You can create the entire "order" dynamically, but it is more involved...
Another trick (mainly appropriate to LINQ-to-Objects) is to use a multiplier, of -1/1. This is only really useful for numeric data, but is a cheeky way of achieving the same outcome.
UPDATE: As TimK pointed out, this isn't needed with jquery 1.5.2 any more. But if you want to add custom headers or allow the use of credentials (username, password, or cookies, etc), read on.
I think I found the answer! (4 hours and a lot of cursing later)
//This does not work!!
Access-Control-Allow-Headers: *
You need to manually specify all the headers you will accept (at least that was the case for me in FF 4.0 & Chrome 10.0.648.204).
jQuery's $.ajax method sends the "x-requested-with" header for all cross domain requests (i think its only cross domain).
So the missing header needed to respond to the OPTIONS request is:
//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with
If you are passing any non "simple" headers, you will need to include them in your list (i send one more):
//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by
So to put it all together, here is my PHP:
// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: http://www.example.com');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
{
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Max-Age: 604800');
//if you need special headers
header('Access-Control-Allow-Headers: x-requested-with');
exit(0);
}
Take a look at the JavaDoc for RestTemplate.
There is the corresponding getForObject
methods that are the HTTP GET equivalents of postForObject
, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.
Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange
methods allow you to provide an HttpEntity
object representing the details of the request (including headers). The execute
methods allow you to specify a RequestCallback
from which you can add the headers upon its invocation.
To make the solution by @flion look really great, you could adjust the center point for that icon so it doesn't wobble up and down. This looks right for me at a small font size:
.glyphicon-refresh.spinning {
transform-origin: 48% 50%;
}
Here an other solution
public static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for(int i = 0; i < ba.length; i++)
str.append(String.format("%x", ba[i]));
return str.toString();
}
public static String fromHexString(String hex) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
}
return str.toString();
}
If you don't mind using lodash try out https://github.com/rockabox/ng-lodash it wraps lodash completely so it is the only dependency and you don't need to load any other script files such as lodash.
Lodash is completely off of the window scope and no "hoping" that it's been loaded prior to your module.
Create this function prototype:
Array.prototype.contains = function ( needle ) {
for (i in this) {
if (this[i] == needle) return true;
}
return false;
}
and then you can use following code to search in array x
if (x.contains('searchedString')) {
// do a
}
else
{
// do b
}
I too faced the same exception, none of the solutions over internet helped me out. my project contains multiple modules. My Junit code resides in Web module. And it's referring to client module's code.
Finally , I tried : Right click on (Web module) project -->build path--> source tab--> Link source --> added the src files location (Client module's)
Thats it! It worked like a charm Hope it helps
<html>
<title>Practice Session</title>
<body>
<form name="RegForm" onsubmit="return validate()" method="post">
<p>Name: <input type="text" name="Name"> </p><br>
<p>Contact: <input type="text" name="Telephone"> </p><br>
<p><input type="submit" value="send" name="Submit"></p>
</form>
</body>
<script>
function validate()
{
var name = document.forms["RegForm"]["Name"];
var phone = document.forms["RegForm"]["Telephone"];
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{
window.alert("please enter character");
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}
}
</script>
</html>
In version 1.1.1:
.*
><
>\n<
Below function is to remove all match word like (this) from the string set. By Ravikant Sonare.
private static void myfun()
{
string mystring = "thiTHISThiss This THIS THis tThishiThiss. Box";
var regex = new Regex("this", RegexOptions.IgnoreCase);
mystring = regex.Replace(mystring, "");
string[] str = mystring.Split(' ');
for (int i = 0; i < str.Length; i++)
{
if (regex.IsMatch(str[i].ToString()))
{
mystring = mystring.Replace(str[i].ToString(), string.Empty);
}
}
Console.WriteLine(mystring);
}
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
if(is_array($EMailArr)){
foreach($EMailArr as $key => $value){
$R_ID = (int) $value['R_ID'];
$email = mysql_real_escape_string( $value['email'] );
$name = mysql_real_escape_string( $value['name'] );
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
mysql_query($sql) or exit(mysql_error());
}
}
A better example solution with PDO:
$q = $sql->prepare("INSERT INTO `email_list`
SET `R_ID` = ?, `EMAIL` = ?, `NAME` = ?");
foreach($EMailArr as $value){
$q ->execute( array( $value['R_ID'], $value['email'], $value['name'] ));
}
@mixin box-shadow($left: 0, $top: 0, $blur: 6px, $color: hsla(0,0%,0%,0.25), $inset: false) {
@if $inset {
-webkit-box-shadow: inset $left $top $blur $color;
-moz-box-shadow: inset $left $top $blur $color;
box-shadow: inset $left $top $blur $color;
} @else {
-webkit-box-shadow: $left $top $blur $color;
-moz-box-shadow: $left $top $blur $color;
box-shadow: $left $top $blur $color;
}
}
If you really want a vba solution you can loop through a range like this:
Sub Check()
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = Range("A1:A100")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
If dat(i, 1) <> "" Then
rng(i, 2).Value = "My Text"
End If
Next
End Sub
*EDIT*
Instead of using varients you can just loop through the range like this:
Sub Check()
Dim rng As Range
Dim i As Long
'Set the range in column A you want to loop through
Set rng = Range("A1:A100")
For Each cell In rng
'test if cell is empty
If cell.Value <> "" Then
'write to adjacent cell
cell.Offset(0, 1).Value = "My Text"
End If
Next
End Sub
Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.
if ($('#mydialog').dialog('isOpen') === true) {
// true
} else {
// false
}
We managed it via the http.conf
file (edited and then restarted the HTTP service):
<Directory "/home/the directory_where_your_serverside_pages_is">
Header set Access-Control-Allow-Origin "*"
AllowOverride all
Order allow,deny
Allow from all
</Directory>
In the Header set Access-Control-Allow-Origin "*"
, you can put a precise URL.
Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}
You're right in thinking that, in order to share an image in this way without going down the Twitter Cards route, you need to to have tweeted the image already. As you say, it's also important that you grab the image link that's of the form pic.twitter.com/NuDSx1ZKwy
This step-by-step guide is worth checking out for anyone looking to implement a 'tweet this' link or button: http://onlinejournalismblog.com/2015/02/11/how-to-make-a-tweetable-image-in-your-blog-post/.
Adding _CRT_SECURE_NO_WARNINGS
to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn't work for me, don't know why.
The following hint works: In stdafx.h file, please add
#define _CRT_SECURE_NO_DEPRECATE
before include other header files.
Tuples are known values which is used to relate the table in relational DB.
Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.
I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.
<div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
<div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>
function setMobDeskCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value + "; path=/";
window.location.reload();
}
$(function() {
$(".make_desktop").click(function() {
setMobDeskCookie('deskmob', 1, 3650);
});
$(".make_responsive").click(function() {
setMobDeskCookie('deskmob', 0, 3650);
});
});`enter code here`
i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me
and i also created non-responsive.css that forces the grid to maintain the large screen version
in case u select mobile i would load / echo
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />
in case you select desktop i would load /echo
<meta name="viewport" content="width=1024">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
<!-- Main CSS -->
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />
the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files
please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me
if you have a MSSQL compatible SQL dump you can convert it to MySQL queries one by one using this online tool
Hope it saved your time
I came across this post even though I needed to SHRINKFILE on MSSQL 2012 version which is little trickier since 2000 or 2005 versions. After reading up on all risks and issues related to this issue I ended up testing. Long story short, the best results I got were from using the MS SQL Server Management Studio.
Right-Click the DB -> TASKS -> SHRINK -> FILES -> select the LOG file
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:
return StatusCode(500, "My error");
Or
return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
Or
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });
Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error:
in client side (ajax).
you can have ajax call like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
success: function (response) {
console.log("Custom message : " + response.responseText);
}, //Is Called when Status Code is 200[OK] or other Http success code
error: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
})
Additionally you can handle different HTTP errors from jQuery side like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
statusCode: {
500: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
501: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}
})
statusCode:
is useful when you want to call different functions for different status codes that you return from server.
You can see list of different Http Status codes here:Wikipedia
Additional resources:
<string name="hello_world"><font fgcolor="red">Hello</font>
</font fgcolor="blue">world!</font></string>
But note that this only works on a relatively short list of built-in colors: aqua, black, blue, fuchsia, green, grey, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. See https://stackoverflow.com/a/31655150/338479 for a way to do it with arbitrary colors.
The path location must not contain á,à,â, and similars. Chinese characters or any other diferent than the usual alphabetical characters. For example, my path was C:\Users\Vinícius\AndroidStudioProjects\MyApplication .But my user name had the letter í. So I create a folder 'custom2222' and change the path to C:\custom2222\MyApplication
Try it as below:
var scope = $(this).scope();
alert(JSON.stringify(scope.model.options[$('#selOptions').val()].value));
Here's a table to help find the required flags for different permission combinations.
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ ¦ ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦ files ¦ ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦ ¦ Propagation ¦ none ¦ none ¦ none ¦ none ¦ InheritOnly ¦ InheritOnly ¦ InheritOnly ¦ ¦ Inheritance ¦ none ¦ Container|Object ¦ Container ¦ Object ¦ Container|Object ¦ Container ¦ Object ¦ +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
So, as David said, you'll want
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
find:
^>([^\n\r]+)[\n\r]([A-Z\n\r]+)
\1 = some_varying_text
\2 = lines of all CAPS
Edit (proof that this works):
text = """> some_Varying_TEXT
DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF
GATACAACATAGGATACA
GGGGGAAAAAAAATTTTTTTTT
CCCCAAAA
> some_Varying_TEXT2
DJASDFHKJFHKSDHF
HHASGDFTERYTERE
GAGAGAGAGAG
PPPPPAAAAAAAAAAAAAAAP
"""
import re
regex = re.compile(r'^>([^\n\r]+)[\n\r]([A-Z\n\r]+)', re.MULTILINE)
matches = [m.groups() for m in regex.finditer(text)]
for m in matches:
print 'Name: %s\nSequence:%s' % (m[0], m[1])
This is shorter and works
<connectionStrings>
<add name="DBConnection"
connectionString="data source=SERVER\INSTANCE;
Initial Catalog=MyDB;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Persist Security Info not needed
I combined the best performance results I found around that check if a given object:
The result is the following:
function isValidDate(input) {
if(!(input && input.getTimezoneOffset && input.setUTCFullYear))
return false;
var time = input.getTime();
return time === time;
};
You just have syntax error when saying = {return self.someValue}
. The =
isn't needed.
Use :
var numPages: Int {
get{
return categoriesPerPage.count
}
}
if you want get only you can write
var numPages: Int {
return categoriesPerPage.count
}
with the first way you can also add observers as set
willSet
& didSet
var numPages: Int {
get{
return categoriesPerPage.count
}
set(v){
self.categoriesPerPage = v
}
}
allowing to use = operator
as a setter
myObject.numPages = 5
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
It's because you have:
def readTTable(fname):
try:
without a matching except
block after the try:
block. Every try
must have at least one matching except
.
See the Errors and Exceptions section of the Python tutorial.
I found another very easy way to create dictionaries using itertools.
generator=itertools.combinations_with_replacement('abcd', 4 )
This will iterate through all combinations of 'a','b','c' and 'd' and create combinations with a total length of 1 to 4. ie. a,b,c,d,aa,ab.........,dddc,dddd. generator is an itertool object and you can loop through normally like this,
for password in generator:
''.join(password)
Each password is infact of type tuple and you can work on them as you normally do.
I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete
So I see here tons of answers that are frankly overcomplicated, and that's an understatement.
The answer is pretty simple: :: it's called a Method References https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
So I won't copy-paste, on the link, you can find all the information if you scroll down to the table.
Now, let's take a short look at what is a Method References:
A::b somewhat substitutes the following inline lambda expression: (params ...) -> A.b(params ...)
To correlate this with your questions, it's necessary to understand a java lambda expression. Which is not hard.
An inline lambda expression is similar to a defined functional interface (which is an interface that has no more and no less than 1 method). Let's take a short look what I mean:
InterfaceX f = (x) -> x*x;
InterfaceX must be a functional interface. Any functional interface, the only thing what's important about InterfaceX for that compiler is that you define the format:
InterfaceX can be any of this:
interface InterfaceX
{
public Integer callMe(Integer x);
}
or this
interface InterfaceX
{
public Double callMe(Integer x);
}
or more generic:
interface InterfaceX<T,U>
{
public T callMe(U x);
}
Let's take the first presented case and the inline lambda expression that we defined earlier.
Before Java 8, you could've defined it similarly this way:
InterfaceX o = new InterfaceX(){
public int callMe (int x)
{
return x*x;
} };
Functionally, it's the same thing. The difference is more in how the compiler perceives this.
Now that we took a look at inline lambda expression, let's return to Method References (::). Let's say you have a class like this:
class Q {
public static int anyFunction(int x)
{
return x+5;
}
}
Since method anyFunctions has the same types as InterfaceX callMe, we can equivalate those two with a Method Reference.
We can write it like this:
InterfaceX o = Q::anyFunction;
and that is equivalent to this :
InterfaceX o = (x) -> Q.anyFunction(x);
A cool thing and advantage of Method References are that at first, until you assign them to variables, they are typeless. So you can pass them as parameters to any equivalent looking (has same defined types) functional interface. Which is exactly what happens in your case
This question was opened years ago, but hey, there's an easy way to simulate the binding of a function to a class instance using decorators:
def binder (function, instance):
copy_of_function = type (function) (function.func_code, {})
copy_of_function.__bind_to__ = instance
def bound_function (*args, **kwargs):
return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)
return bound_function
class SupaClass (object):
def __init__ (self):
self.supaAttribute = 42
def new_method (self):
print self.supaAttribute
supaInstance = SupaClass ()
supaInstance.supMethod = binder (new_method, supaInstance)
otherInstance = SupaClass ()
otherInstance.supaAttribute = 72
otherInstance.supMethod = binder (new_method, otherInstance)
otherInstance.supMethod ()
supaInstance.supMethod ()
There, when you pass the function and the instance to the binder decorator, it will create a new function, with the same code object as the first one. Then, the given instance of the class is stored in an attribute of the newly created function. The decorator return a (third) function calling automatically the copied function, giving the instance as the first parameter.
In conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.
If you are already doing databinding:
<asp:Calendar ID="Calendar1" runat="server" SelectedDate="<%# DateTime.Today %>" />
Will do it. This does require that somewhere you are doing a Page.DataBind() call (or a databind call on a parent control). If you are not doing that and you absolutely do not want any codebehind on the page, then you'll have to create a usercontrol that contains a calendar control and sets its selecteddate.
The following (C#) code should do the trick
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Perhaps with the canvas tag (though it's not portable). There's a blog about how to rotate an image with canvas here, I suppose if you can rotate it, you can resize it. Maybe it can be a starting point.
See this library also.
Maybe a bit astray to the answer, but if anyone who is looking to do the other way around, you can use Model.hydrate()
(since mongoose v4) to convert a javascript object (JSON) to a mongoose document.
An useful case would be when you using Model.aggregate(...)
. Because it is actually returning plain JS object, so you may want to convert it into a mongoose document in order to get access to Model.method
(e.g. your virtual property defined in the schema).
PS. I thought it should have a thread running like "Convert json to Mongoose docs", but actually not, and since I've found out the answer, so I think it is not good to do self-post-and-self-answer.
Here's a simple single threaded sleep based version that drifts, but tries to auto-correct when it detects drift.
NOTE: This will only work if the following 3 reasonable assumptions are met:
-
from datetime import timedelta
from datetime import datetime
def exec_every_n_seconds(n,f):
first_called=datetime.now()
f()
num_calls=1
drift=timedelta()
time_period=timedelta(seconds=n)
while 1:
time.sleep(n-drift.microseconds/1000000.0)
current_time = datetime.now()
f()
num_calls += 1
difference = current_time - first_called
drift = difference - time_period* num_calls
print "drift=",drift
The tools can now be found ("Hardware IO tools") here: https://developer.apple.com/download/more/
editText1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog.OnDateSetListener dpd = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
int s = monthOfYear + 1;
String a = dayOfMonth + "/" + s + "/" + year;
editText1.setText(a);
}
};
Time date = new Time();
DatePickerDialog d = new DatePickerDialog(UpdateStore.this, dpd, date.year, date.month, date.monthDay);
d.show();
}
});
An alternative to the above commands that is a little more bulletproof.
It can list all files irrespective of permissions or path length.
robocopy "C:\YourFolderPath" "C:\NULL" /E /L /NJH /NJS /FP /NS /NC /B /XJ
I have a slight issue with the use of C:\NULL which I have written about in my blog
https://theitronin.com/bulletproofdirectorylisting/
But nevertheless it's the most robust command I know.
This problem occurred for me when I imported an existing project into eclipse. What happens is it copied all the files not in the package, but outside the package. Hence, when I tried run > run configurations, it couldn't find the main method because it was not in the package. All I did was copy the files into the package and Eclipse was then able to detect the main method. So ultimately make sure that Eclipse can find your main method, by making sure that your java files are in the right package.
There is in fact a way to do this using Visual block mode. Simply pressing $A
in Visual block mode appends to the end of all lines in the selection. The appended text will appear on all lines as soon as you press Esc.
So this is a possible solution:
vip<C-V>$A,<Esc>
That is, in Normal mode, Visual select a paragraph vip
, switch to Visual block mode CTRLV, append to all lines $A
a comma ,
, then press Esc to confirm.
The documentation is at :h v_b_A
. There is even an illustration of how it works in the examples section: :h v_b_A_example
.
For Angular 9+ You can add headers and params directly without the key-value notion:
const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params});
In my case, the issue was caused by a connection problem to the SQL database. I just disconnected and then reconnected the SQL datasource from the design view. I am back up and running. Hope this works for everyone.
$ DOCS="/cygdrive/c/Users/my\ dir/Documents"
Here's your first problem. This puts an actual backslash character into $DOCS
, as you can see by running this command:
$ echo "$DOCS"
/cygdrive/c/Users/my\ `
When defining DOCS
, you do need to escape the space character. You can quote the string (using either single or double quotes) or you can escape just the space character with a backslash. You can't do both. (On most Unix-like systems, you can have a backslash in a file or directory name, though it's not a good idea. On Cygwin or Windows, \
is a directory delimiter. But I'm going to assume the actual name of the directory is my dir
, not my\ dir
.)
$ cd $DOCS
This passes two arguments to cd
. The first is cygdrive/c/Users/my\
, and the second is dir/Documents
. It happens that cd
quietly ignores all but its first argument, which explains the error message:
-bash: cd: /cygdrive/c/Users/my\: No such file or directory
To set $DOCS
to the name of your Documents
directory, do any one of these:
$ DOCS="/cygdrive/c/Users/my dir/Documents"
$ DOCS='/cygdrive/c/Users/my dir/Documents'
$ DOCS=/cygdrive/c/Users/my\ dir/Documents
Once you've done that, to change to your Documents
directory, enclose the variable reference in double quotes (that's a good idea for any variable reference in bash, unless you're sure the value doesn't have any funny characters):
$ cd "$DOCS"
You might also consider giving that directory a name without any spaces in it -- though that can be hard to do in general on Windows.
 
is the numeric reference for the entity reference
— they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.
See the Wikipedia page for the non-breaking space.
Most of what you "know" is wrong.
First of all, as a few of the relational gurus routinely (and sometimes stridently) point out, SQL doesn't really fit nearly as closely with relational theory as many people think. Second, most of the differences in "NoSQL" stuff has relatively little to do with whether it's relational or not. Finally, it's pretty difficult to say how "NoSQL" differs from SQL because both represent a pretty wide range of possibilities.
The one major difference that you can count on is that almost anything that supports SQL supports things like triggers in the database itself -- i.e. you can design rules into the database proper that are intended to ensure that the data is always internally consistent. For example, you can set things up so your database asserts that a person must have an address. If you do so, anytime you add a person, it will basically force you to associate that person with some address. You might add a new address or you might associate them with some existing address, but one way or another, the person must have an address. Likewise, if you delete an address, it'll force you to either remove all the people currently at that address, or associate each with some other address. You can do the same for other relationships, such as saying every person must have a mother, every office must have a phone number, etc.
Note that these sorts of things are also guaranteed to happen atomically, so if somebody else looks at the database as you're adding the person, they'll either not see the person at all, or else they'll see the person with the address (or the mother, etc.)
Most of the NoSQL databases do not attempt to provide this kind of enforcement in the database proper. It's up to you, in the code that uses the database, to enforce any relationships necessary for your data. In most cases, it's also possible to see data that's only partially correct, so even if you have a family tree where every person is supposed to be associated with parents, there can be times that whatever constraints you've imposed won't really be enforced. Some will let you do that at will. Others guarantee that it only happens temporarily, though exactly how long it can/will last can be open to question.
You could use the argument accumulator pattern.
Big discussion about this here:
http://blogs.msdn.com/csharpfaq/archive/2004/03/11/87817.aspx
PRAGMA table_info([tablename]);
Apart from having a Path
variable, the directory C:\data\db
is mandatory.
Create this and the error shall be solved.
I had to do: c:\Users\xxxx>c:/python27/scripts/pip install openpyxl
I had to save the openpyxl files in the scripts folder.
<script type="text/javascript">
if(window.location.href === "http://stackoverflow.com") {
window.location.replace("https://www.google.co.in/");
}
</script>
groupByKey()
is just to group your dataset based on a key. It will result in data shuffling when RDD is not already partitioned. reduceByKey()
is something like grouping + aggregation. We can say reduceBykey() equvelent to dataset.group(...).reduce(...). It will shuffle less data unlike groupByKey()
. aggregateByKey()
is logically same as reduceByKey() but it lets you return result in different type. In another words, it lets you have a input as type x and aggregate result as type y. For example (1,2),(1,4) as input and (1,"six") as output. It also takes zero-value that will be applied at the beginning of each key.Note : One similarity is they all are wide operations.
Use the not
boolean operator:
nyval = not myval
not
returns a boolean value (True
or False
):
>>> not 1
False
>>> not 0
True
If you must have an integer, cast it back:
nyval = int(not myval)
However, the python bool
type is a subclass of int
, so this may not be needed:
>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
The predicate-based searching methods allow a method delegate or lambda expression to decide whether a given element is a “match.” A predicate is simply a delegate accepting an object and returning true or false: public delegate bool Predicate (T object);
static void Main()
{
string[] names = { "Lukasz", "Darek", "Milosz" };
string match1 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
//or
string match2 = Array.Find(names, delegate(string name) { return name.Contains("L"); });
//or
string match3 = Array.Find(names, x => x.Contains("L"));
Console.WriteLine(match1 + " " + match2 + " " + match3); // Lukasz Lukasz Lukasz
}
static bool ContainsL(string name) { return name.Contains("L"); }
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: '[email protected]',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: '[email protected]',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser
in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
put it in double quotes
echo "\t";
See: http://php.net/language.types.string#language.types.string.syntax.double
You could try a ColorMatrixColorFilter, since your key color is white:
// Assuming "color" is your target color
float r = Color.red(color) / 255f;
float g = Color.green(color) / 255f;
float b = Color.blue(color) / 255f;
ColorMatrix cm = new ColorMatrix(new float[] {
// Change red channel
r, 0, 0, 0, 0,
// Change green channel
0, g, 0, 0, 0,
// Change blue channel
0, 0, b, 0, 0,
// Keep alpha channel
0, 0, 0, 1, 0,
});
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
myDrawable.setColorFilter(cf);
This is rather an old question, but I will add my notes for future references.
I had a similar issue and fixed it by changing the order of the exports in the PATH variable.
For example I was using a method of concatenating strings to my PATH by doing (this is just an example):
$> export PATH='$PATH:'$JAVA_HOME
If my variable PATH already had a java in it, the last value would be meaningless, thus the order would matter. To solve this I started inverting it by adding my variable first, then adding the PATH.
Following this idea I inverted the order that ANT_HOME was being exported. Adding JAVA_HOME before ANT_HOME.
This could be just a coincidence, but it worked for me.
public class WishServletTest {
WishServlet wishServlet;
HttpServletRequest mockhttpServletRequest;
HttpServletResponse mockhttpServletResponse;
@Before
public void setUp(){
wishServlet=new WishServlet();
mockhttpServletRequest=createNiceMock(HttpServletRequest.class);
mockhttpServletResponse=createNiceMock(HttpServletResponse.class);
}
@Test
public void testService()throws Exception{
File file= new File("Sample.txt");
File.createTempFile("ashok","txt");
expect(mockhttpServletRequest.getParameter("username")).andReturn("ashok");
expect(mockhttpServletResponse.getWriter()).andReturn(new PrintWriter(file));
replay(mockhttpServletRequest);
replay(mockhttpServletResponse);
wishServlet.doGet(mockhttpServletRequest, mockhttpServletResponse);
FileReader fileReader=new FileReader(file);
int count = 0;
String str = "";
while ( (count=fileReader.read())!=-1){
str=str+(char)count;
}
Assert.assertTrue(str.trim().equals("Helloashok"));
verify(mockhttpServletRequest);
verify(mockhttpServletResponse);
}
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<p data-foo="0"></p>
<h6 data-foo="1"></h6>
<script>
var a = document.querySelectorAll('[data-foo]');
for (var i in a) if (a.hasOwnProperty(i)) {
alert(a[i].getAttribute('data-foo'));
}
</script>
</body>
</html>
First find out your IP camera's streaming url, like whether it's RTSP/HTTP etc.
Code changes will be as follows:
cap = cv2.VideoCapture("ipcam_streaming_url")
For example:
cap = cv2.VideoCapture("http://192.168.18.37:8090/test.mjpeg")
Its best practice to have TOP 1 1
always.
What if I use SELECT 1
-> If condition matches more than one record then your query will fetch all the columns records and returns 1.
What if I use SELECT TOP 1 1
-> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.
IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx')
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 2
END
Have you tried to define a custom background in xml? decreasing the Spinner background width which is doing your arrow look like that.
Define a layer-list with a rectangle background and your custom arrow icon:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/color_white" />
<corners android:radius="2.5dp" />
</shape>
</item>
<item android:right="64dp">
<bitmap android:gravity="right|center_vertical"
android:src="@drawable/custom_spinner_icon">
</bitmap>
</item>
</layer-list>
I would like to show here another example of a singleton in C++. It makes sense to use template programming. Besides, it makes sense to derive your singleton class from a not copyable and not movabe classes. Here how it looks like in the code:
#include<iostream>
#include<string>
class DoNotCopy
{
protected:
DoNotCopy(void) = default;
DoNotCopy(const DoNotCopy&) = delete;
DoNotCopy& operator=(const DoNotCopy&) = delete;
};
class DoNotMove
{
protected:
DoNotMove(void) = default;
DoNotMove(DoNotMove&&) = delete;
DoNotMove& operator=(DoNotMove&&) = delete;
};
class DoNotCopyMove : public DoNotCopy,
public DoNotMove
{
protected:
DoNotCopyMove(void) = default;
};
template<class T>
class Singleton : public DoNotCopyMove
{
public:
static T& Instance(void)
{
static T instance;
return instance;
}
protected:
Singleton(void) = default;
};
class Logger final: public Singleton<Logger>
{
public:
void log(const std::string& str) { std::cout << str << std::endl; }
};
int main()
{
Logger::Instance().log("xx");
}
The splitting into NotCopyable and NotMovable clases allows you to define your singleton more specific (sometimes you want to move your single instance).
For a ready-to-use solution, see https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html.
It provides running average with the flat
window type. Note that this is a bit more sophisticated than the simple do-it-yourself convolve-method, since it tries to handle the problems at the beginning and the end of the data by reflecting it (which may or may not work in your case...).
To start with, you could try:
a = np.random.random(100)
plt.plot(a)
b = smooth(a, window='flat')
plt.plot(b)
See if this works for you.
Paste -> By Value
That's It!
I was able to copy all the sheets in a workbook that had a vba app running, to a new workbook w/o the app macros, with:
ActiveWorkbook.Sheets.Copy
I use something like this
>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>
>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'
>>> assert regex('08/03/20', '%m/%d/%y')
>>>
>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'