1)
select *
from employee em
where CONCAT(em.firstname, ' ', em.lastname) like '%parth pa%';
2)
select *
from employee em
where CONCAT_ws('-', em.firstname, em.lastname) like '%parth-pa%';
First is usefull when we have data like : 'firstname lastname'.
e.g
Second is usefull when we have data like : 'firstname-lastname'. In it you can also use special characters.
e.g
The answer provided didn't work for me, but it gave me an idea:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
var c=[];
var d=[];
function a()
{
var e = '1';
var f = '2';
c[0] = ['1','1'];
c[1] = ['2','2'];
c[2] = ['3','3'];
d[0] = [document.getElementById('g').value,document.getElementById('h').value];
document.getElementById('i').value = c.join(',');
document.getElementById('j').value = d.join(',');
document.getElementById('b').value = c.contains(d);
}
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.
When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe
You can do it using:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
In case if your frameId is dynamic, and you only have one iframe, you can use something like:
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
One thing to also look at: Are you saving your .gitignore file with the correct line endings?
Windows:
If you're using it on Windows, are you saving it with Windows line endings? Not all programs will do this by default; Notepad++ and many PHP editors default to Linux line endings so the files will be server compatible. One easy way to check this, is open the file in Windows Notepad. If everything appears on one line, then the file was saved with Linux line endings.
Linux:
If you are having trouble with the file working in a Linux environment, open the file in an editor such as Emacs or nano. If you see any non-printable characters, then the file was saved with Windows line endings.
I know this is an older question, but I thought I would also post my solution:
I faced the same problem. Solution on windows:
mkdir .ssh
This will create a .ssh folder.
Based on the answer by Mark B and the comments bellow:
protected void launchUrl(String url) {
Uri uri = Uri.parse(url);
if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
uri = Uri.parse("http://" + url);
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
if (browserIntent.resolveActivity(getPackageManager()) != null) {
startActivity(browserIntent);
}
}
I solved it moving the file spring-context.xml in a src folder. ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Having my tslint
rules configuration here always replacing the line Object["values"](myObject)
with Object.values(myObject)
.
Two options if you have same issue:
(Object as any).values(myObject)
or
/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`
Assuming the items override ToString
appropriately:
public void WriteToConsole(IEnumerable items)
{
foreach (object o in items)
{
Console.WriteLine(o);
}
}
(There'd be no advantage in using generics in this loop - we'd end up calling Console.WriteLine(object)
anyway, so it would still box just as it does in the foreach
part in this case.)
EDIT: The answers using List<T>.ForEach
are very good.
My loop above is more flexible in the case where you have an arbitrary sequence (e.g. as the result of a LINQ expression), but if you definitely have a List<T>
I'd say that List<T>.ForEach
is a better option.
One advantage of List<T>.ForEach
is that if you have a concrete list type, it will use the most appropriate overload. For example:
List<int> integers = new List<int> { 1, 2, 3 };
List<string> strings = new List<string> { "a", "b", "c" };
integers.ForEach(Console.WriteLine);
strings.ForEach(Console.WriteLine);
When writing out the integers, this will use Console.WriteLine(int)
, whereas when writing out the strings it will use Console.WriteLine(string)
. If no specific overload is available (or if you're just using a generic List<T>
and the compiler doesn't know what T
is) it will use Console.WriteLine(object)
.
Note the use of Console.WriteLine
as a method group, by the way. This is more concise than using a lambda expression, and actually slightly more efficient (as the delegate will just be a call to Console.WriteLine
, rather than a call to a method which in turn just calls Console.WriteLine
).
You return four variables s1,s2,s3,s4 and receive them using a single variable obj
. This is what is called a tuple
, obj
is associated with 4 values, the values of s1,s2,s3,s4
. So, use index as you use in a list to get the value you want, in order.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
print obj[3] + " is a benefit of functions!"
if your eclipse is auto-closing at startup you may do this: open the properties of your shortcut and add -clean at the end of the path. or do this in cmd : cd C:\PATH_TO_YOUR_ECLIPSE\eclipse -clean like mentioned earlier above comments
In my case - In storyboard i had a two labels as in image below, both labels was having desired width values been set before i made it equal. once you unselect, it will change to automatic, and as usual having below things should work like charm.
1.rowHeight = UITableView.automaticDimension, and
2.estimatedRowHeight = 100(In my case).
3.make sure label number of lines is zero.
Really this is an extension to Marcin's answer.
But you could also try passing "rubbish" arguments to see if you get any errors back. Getting any response from the executable directly in the shell will mean that it is likely looking at the arguments you're passing, with an error response being close to a guarantee that it is.
Failing that you might have to directly ask the publishers/creators/owners... sniffing the binaries yourself just seems like far too much work for an end-user.
It will store value of number of characters printed so far in that printf()
function.
Example:
int a;
printf("Hello World %n \n", &a);
printf("Characters printed so far = %d",a);
The output of this program will be
Hello World
Characters printed so far = 12
You can do
$('.page-address-edit').addClass('test1 test2');
More here:
More than one class may be added at a time, separated by a space, to the set of matched elements, like so:
$("p").addClass("myClass yourClass");
with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#
but it still limited on so many aspect. And browser support is also not so ready.
your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:
#include <bits/stdc++.h>
using namespace std;
queue<int>Q;
stack<int>Stk;
void PRINT(stack<int>ss , queue<int>qq) {
while( ss.size() ) {
cout << ss.top() << " " ;
ss.pop();
}
puts("");
while( qq.size() ) {
cout << qq.front() << " " ;
qq.pop();
}
puts("\n----------------------------------");
}
void POP() {
queue<int>Tmp ;
while( Q.size() > 1 ) {
Tmp.push( Q.front() );
Q.pop();
}
cout << Q.front() << " " << Stk.top() << endl;
Q.pop() , Stk.pop() ;
Q = Tmp ;
}
void PUSH(int x ) {
Q.push(x);
Stk.push(x);
}
int main() {
while( true ) {
string typ ;
cin >> typ ;
if( typ == "push" ) {
int x ;
cin >> x;
PUSH(x);
} else POP();
PRINT(Stk,Q);
}
}
Check the properties of App.xaml. Is the Build Action
still ApplicationDefinition
?
I use sql-workbench for working with H2 and any other DBMS I have to deal with and it makes me smile :-)
I have done a little plugin to show a iframe window to preview a link. Still in beta version. Maybe it fits your case: https://github.com/Fischer-L/previewbox.
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
You may be used to MySQL's syntax: Microsoft SQL @
is the same as the MySQL's ?
strikes = [number_map[int(x)] for x in input_str.split()]
You get an element from a dict using these []
brackets, not these ()
.
There are many answers already that tell you how to make a proper copy, but none of them say why your original 'copy' failed.
Python doesn't store values in variables; it binds names to objects. Your original assignment took the object referred to by my_list
and bound it to new_list
as well. No matter which name you use there is still only one list, so changes made when referring to it as my_list
will persist when referring to it as new_list
. Each of the other answers to this question give you different ways of creating a new object to bind to new_list
.
Each element of a list acts like a name, in that each element binds non-exclusively to an object. A shallow copy creates a new list whose elements bind to the same objects as before.
new_list = list(my_list) # or my_list[:], but I prefer this syntax
# is simply a shorter way of:
new_list = [element for element in my_list]
To take your list copy one step further, copy each object that your list refers to, and bind those element copies to a new list.
import copy
# each element must have __copy__ defined for this...
new_list = [copy.copy(element) for element in my_list]
This is not yet a deep copy, because each element of a list may refer to other objects, just like the list is bound to its elements. To recursively copy every element in the list, and then each other object referred to by each element, and so on: perform a deep copy.
import copy
# each element must have __deepcopy__ defined for this...
new_list = copy.deepcopy(my_list)
See the documentation for more information about corner cases in copying.
In Expression Language you can just use the ==
or eq
operator to compare object values. Behind the scenes they will actually use the Object#equals()
. This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).
So the particular line
<c:when test="${lang}.equals(${pageLang})">
should be written as (note that the whole expression is inside the {
and }
)
<c:when test="${lang == pageLang}">
or, equivalently
<c:when test="${lang eq pageLang}">
Both are behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))
If you want to compare constant String
values, then you need to quote it
<c:when test="${lang == 'en'}">
or, equivalently
<c:when test="${lang eq 'en'}">
which is behind the scenes roughly interpreted as
jspContext.findAttribute("lang").equals("en")
Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:
SELECT t.owner,
t.table_name,
t.num_rows,
Count(*)
FROM all_tables t
LEFT JOIN all_tab_columns c
ON t.table_name = c.table_name
WHERE num_rows IS NOT NULL
GROUP BY t.owner,
t.table_name,
t.num_rows
ORDER BY t.num_rows DESC;
I try using the top answer, but it occur Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
.
I found this is because of cross domain problems, the solution is
function convert(oldImag, callback) {
var img = new Image();
img.onload = function(){
callback(img)
}
img.setAttribute('crossorigin', 'anonymous');
img.src = oldImag.src;
}
function getBase64Image(img,callback) {
convert(img, function(newImg){
var canvas = document.createElement("canvas");
canvas.width = newImg.width;
canvas.height = newImg.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(newImg, 0, 0);
var base64=canvas.toDataURL("image/png");
callback(base64)
})
}
getBase64Image(document.getElementById("imageid"),function(base64){
// base64 in here.
console.log(base64)
});
No, you can't do that. range()
expects integer arguments. If you want to know if x
is inside this range try some form of this:
print 0.0 <= x <= 0.5
Be careful with your upper limit. If you use range()
it is excluded (range(0, 5)
does not include 5!)
You can also use binding
<TextBlock Text="{Binding MyText}"/>
And set MyText like this:
Public string MyText
{
get{return string.Format("My Text \n Your Text");}
}
For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-
DecimalFormat formater = new DecimalFormat("#.##");
2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-
DecimalFormat formater = new DecimalFormat("0.00");
(Extension of @lepe
's and @redsquare
answer for ASP.NET MVC
+ jquery.validate.unobtrusive.js
)
The jquery validation plugin (not the Microsoft unobtrusive one) allows you to put a .cancel
class on your submit button to bypass validation completely (as shown in accepted answer).
To skip validation while still using a submit-button, add a class="cancel" to that input.
<input type="submit" name="submit" value="Submit"/>
<input type="submit" class="cancel" name="cancel" value="Cancel"/>
(don't confuse this with type='reset'
which is something completely different)
Unfortunately the jquery.validation.unobtrusive.js
validation handling (ASP.NET MVC) code kinda screws up the jquery.validate plugin's default behavior.
This is what I came up with to allow you to put .cancel
on the submit button as shown above. If Microsoft ever 'fixes' this then you can just remvoe this code.
// restore behavior of .cancel from jquery validate to allow submit button
// to automatically bypass all jquery validation
$(document).on('click', 'input[type=image].cancel,input[type=submit].cancel', function (evt)
{
// find parent form, cancel validation and submit it
// cancelSubmit just prevents jQuery validation from kicking in
$(this).closest('form').data("validator").cancelSubmit = true;
$(this).closest('form').submit();
return false;
});
Note: If at first try it appears that this isn't working - make sure you're not roundtripping to the server and seeing a server generated page with errors. You'll need to bypass validation on the server side by some other means - this just allows the form to be submitted client side without errors (the alternative would be adding .ignore
attributes to everything in your form).
(Note: you may need to add button
to the selector if you're using buttons to submit)
Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:
var redirectUrl =
status == LoginStatusEnum.Success ? "/SecretPage"
: status == LoginStatusEnum.Failure ? "/LoginFailed"
: status == LoginStatusEnum.Sms ? "/2-StepSms"
: status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
: "/404-Error";
instead of
string redirectUrl;
switch (status)
{
case LoginStatusEnum.Success:
redirectUrl = "/SecretPage";
break;
case LoginStatusEnum.Failure:
redirectUrl = "/LoginFailed";
break;
case LoginStatusEnum.Sms:
redirectUrl = "/2-StepSms";
break;
case LoginStatusEnum.EmailNotConfirmed:
redirectUrl = "/EmailNotConfirmed";
break;
default:
redirectUrl = "/404-Error";
break;
}
You could test the url via AJAX and read the status code - that is if the URL is in the same domain.
If it's a remote domain, you could have a server script on your own domain check out a remote URL.
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
_x000D_
the only way I know of is to use the Win32 exclusive lock API which isn't too speedy, but examples exist.
Most people, for a simple solution to this, simply to try/catch/sleep loops.
Use a dot or a pipe as the field separator:
awk -v FS='[.|]' '{
printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END
gives:
Emailclient [email protected]
Socialsite [email protected]
As an example of the difference -- if you have a task the does something with the UI thread (e.g. a task that represents an animation in a Storyboard) if you Task.WaitAll()
then the UI thread is blocked and the UI is never updated. if you use await Task.WhenAll()
then the UI thread is not blocked, and the UI will be updated.
Yes you need javascript. The simplest way is to just put this at the bottom of your HTML page:
<script type="text/javascript">
alert("Hello world");
</script>
There are more preferred methods, like using jQuery's ready function, but this method will work.
Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project
QuartzCore.framework
For the bug
Undefined symbols for architecture i386:
Assuming you're wanting to undo the effects of git rm <file>
or rm <file>
followed by git add -A
or something similar:
# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>
To undo git add <file>
, the first line above suffices, assuming you haven't committed yet.
My scenario may be a little obscure but it can cause the same error and someone may experience it, so:
When using the $controller service to instantiate a new controller (which was expecting '$scope' as it's first injected argument) I was passing the new controller's local scope into the $controller() function's second parameter. This lead to Angular trying to invoke a $scope service which doesn't exist (though, for a while, I actually thought that I'd some how deleted the '$scope' service from Angular's cache). The solution is to wrap the local scope in a locals object:
// Bad:
$controller('myController', newScope);
// Good:
$controller('myController, {$scope: newScope});
you can make a shell script with those commands, and then chmod +x <scriptname.sh>
, and then just run it by
./scriptname.sh
Its very simple to write a bash script
Mockup sh file:
#!/bin/sh
sudo command1
sudo command2
.
.
.
sudo commandn
Try this working fine....
SELECT computer.NAME, application.NAME,software.Version FROM computer LEFT JOIN software_computer ON(computer.ID = software_computer.ComputerID)
LEFT JOIN software ON(software_computer.SoftwareID = Software.ID) LEFT JOIN application ON(application.ID = software.ApplicationID)
where computer.id = 1 group by application.NAME UNION SELECT computer.NAME, application.NAME,
NULL as Version FROM computer, application WHERE application.ID not in ( SELECT s.applicationId FROM software_computer sc LEFT JOIN software s
on s.ID = sc.SoftwareId WHERE sc.ComputerId = 1 )
AND computer.id = 1
The solution you want is the one proposed here:
https://stackoverflow.com/a/542802/50776
Basically, you do this:
cast(floor(cast(@dateVariable as float)) as datetime)
There is a function definition in the link which will allow you to consolidate the functionality and call it anywhere (instead of having to remember it) if you wish.
Swift 4.0
self.messageLabel = UILabel(frame: CGRect(x: 70, y: 60, width:UIScreen.main.bounds.width - 80, height: 30)
messageLabel.text = message
messageLabel.lineBreakMode = .byWordWrapping //in versions below swift 3 (messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping)
messageLabel.numberOfLines = 0 //To write any number of lines within a label scope
messageLabel.textAlignment = .center
messageLabel.textColor = UIColor.white
messageLabel.font = messageLabel.font.withSize(12)
messageLabel.sizeToFit()
Blockquote NSParagraphStyle.LineBreakMode, apply to entire paragraphs, not words within paragraphs.This property is in effect both during normal drawing and in cases where the font size must be reduced to fit the label’s text in its bounding box. This property is set to byTruncatingTail by default.
You can use scipy
, which is pretty straight forward:
scipy.misc.derivative(func, x0, dx=1.0, n=1, args=(), order=3)
Find the nth derivative of a function at a point.
In your case:
from scipy.misc import derivative
def f(x):
return x**2 + 1
derivative(f, 5, dx=1e-6)
# 10.00000000139778
I suggest using:
command $(echo $(tr '\n' ' ' < parameters.cfg))
Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.
This should do the trick:
#include <stdio.h>
NSString *readLineAsNSString(FILE *file)
{
char buffer[4096];
// tune this capacity to your liking -- larger buffer sizes will be faster, but
// use more memory
NSMutableString *result = [NSMutableString stringWithCapacity:256];
// Read up to 4095 non-newline characters, then read and discard the newline
int charsRead;
do
{
if(fscanf(file, "%4095[^\n]%n%*c", buffer, &charsRead) == 1)
[result appendFormat:@"%s", buffer];
else
break;
} while(charsRead == 4095);
return result;
}
Use as follows:
FILE *file = fopen("myfile", "r");
// check for NULL
while(!feof(file))
{
NSString *line = readLineAsNSString(file);
// do stuff with line; line is autoreleased, so you should NOT release it (unless you also retain it beforehand)
}
fclose(file);
This code reads non-newline characters from the file, up to 4095 at a time. If you have a line that is longer than 4095 characters, it keeps reading until it hits a newline or end-of-file.
Note: I have not tested this code. Please test it before using it.
This is a simple way to identify the application related storage paths of a particular app.
Steps:
The "find ." command will list all the files with their paths in the terminal.
./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....
After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.
The variable $token
is not being retrieved from the session when it's in there
This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:
install webpack-dev-server
npm i -g webpack-dev-server
start webpack-dev-server with https
webpack-dev-server --https
Know the master key yourself. Don't hard code it.
Use py-bcrypt
(bcrypt), powerful hashing technique to generate a password yourself.
Basically you can do this (an idea...)
import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)
save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.
This is basically how login should work these days.
Try interface{}
instead. To cast back as slice, try
func foo(bar interface{}) {
s := bar.([]string)
// ...
}
Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.
For your purpose you can use this snnippet:
import org.apache.commons.lang3.StringUtils;
StringUtils.normalizeSpace(string);
This will normalize the spacing to single and will strip off the starting and trailing whitespaces as well.
String sampleString = "Hello world!";
sampleString.replaceAll("\\s{2}", " "); // replaces exactly two consecutive spaces
sampleString.replaceAll("\\s{2,}", " "); // replaces two or more consecutive white spaces
only variable/object declaration statement are written outside of method
public class details{
public static void main(String arg[]){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
here is example try to learn java book and see the syntax then try to develop the program
You just simply press Alt + Ins in Android Studio.
After declaring variables, you will get the getters and setters in the generated code.
You can use Vim in Ex mode:
ex -sc 'a|BRAVO' -cx file
a
append text
x
save and close
Using strtotime() function you can easily convert date to timestamp
<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');
//define date and time
$date = date("d M Y H:i:s");
// output
echo strtotime($date);
?>
More info: http://php.net/manual/en/function.strtotime.php
Online conversion tool: http://freeonlinetools24.com/
The easiest way is
find . | grep test
here find will list all the files in the (.) ie current directory, recursively. And then it is just a simple grep. all the files which name has "test" will appeared.
you can play with grep as per your requirement. Note : As the grep is generic string classification, It can result in giving you not only file names. but if a path has a directory ('/xyz_test_123/other.txt') would also comes to the result set. cheers
You can use stepi
or nexti
(which can be abbreviated to si
or ni
) to step through your machine code.
Call the function with => convertstring('10.00')
parseFloat(string) => It can be used to convert to float, toFixed(4) => to how much decimals
parseInt(str) => It can be used to convert to integer
convertstring(string){
let number_parsed: any = parseFloat(string).toFixed(4)
return number_parsed
}
select * into new_items from productDB.dbo.items
That pretty much is it. THis is the most efficient way to do it.
Use the text-transform CSS for the front-end and then use the toUpper method on your string server-side before you validate.
UPDATE: this only works from API 17 onwards...
To add to the other brilliant answers already given, you can only make the checkbox as small as the text size allows.
As per my answer on this question: - how can we reduce the size of checkbox please give me an idea
CheckBox
derives its height from the TEXT as well as the image.
Set these properties in your XML:
android:text=""
android:textSize="0sp"
Of course this only works if you want no text (worked for me).
Without these changes, the CheckBox
was giving me a big margin around my image, as mentioned by Joe
Here is the compressive in detailed explanation with the help of above posts:
1. Math.trunc() : It is used to remove those digits which are followed by dot. It converts implicitly. But, not supported in IE.
Example:
Math.trunc(10.5) // 10
Math.trunc(-10.5) // -10
Other Alternative way: Use of bitwise not operator:
Example:
x= 5.5
~~x // 5
2. Math.floor() : It is used to give the minimum integer value posiible. It is supported in all browsers.
Example:
Math.floor(10.5) // 10
Math.floor( -10.5) // -11
3. Math.ceil() : It is used to give the highest integer value possible. It is supported in all browsers.
Example:
Math.ceil(10.5) // 11
Math.ceil(-10.5) // -10
4. Math.round() : It is rounded to the nearest integer. It is supported in all browsers.
Example:
Math.round(10.5) // 11
Math.round(-10.5)// -10
Math.round(10.49) // 10
Math.round(-10.51) // -11
I used this FileSaver.js. In my case with csv files, i did this (in coffescript):
$.ajax
url: "url-to-server"
data: "data-to-send"
success: (csvData)->
blob = new Blob([csvData], { type: 'text/csv' })
saveAs(blob, "filename.csv")
I think for most complicated case, the data must be processed properly. Under the hood FileSaver.js implement the same approach of the answer of Jonathan Amend.
You can rewrite it to use the ELSE condition of a CASE
:
SELECT status,
CASE status
WHEN 'i' THEN 'Inactive'
WHEN 't' THEN 'Terminated'
ELSE 'Active'
END AS StatusText
FROM stage.tst
As you can see in mongo docs - since version 3.2 $text
index is case-insensitive by default: https://docs.mongodb.com/manual/core/index-text/#text-index-case-insensitivity
` Please include either of these:
`#include<sstream>`
using std::istringstream;
If you want to style the browsers standard music player in the CSS:
audio {
enter code here;
}
Chapter 5 of the Bash Cookbook by O'Reilly, discusses (at some length) the reasons for the requirement in a variable assignment that there be no spaces around the '=' sign
MYVAR="something"
The explanation has something to do with distinguishing between the name of a command and a variable (where '=' may be a valid argument).
This all seems a little like justifying after the event, but in any case there is no mention of a method of assigning to a list of variables.
Python 3 renamed the unicode
type to str
, the old str
type has been replaced by bytes
.
if isinstance(unicode_or_str, str):
text = unicode_or_str
decoded = False
else:
text = unicode_or_str.decode(encoding)
decoded = True
You may want to read the Python 3 porting HOWTO for more such details. There is also Lennart Regebro's Porting to Python 3: An in-depth guide, free online.
Last but not least, you could just try to use the 2to3
tool to see how that translates the code for you.
According to the definition of getchar()
, it reads a character from the standard input. Unfortunately stdin
is mistaken for keyboard which might not be the case for getchar
. getchar
uses a buffer as stdin
and reads a single character at a time. In your case since there is no EOF
, the getchar
and putchar
are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar
and buffered stdin
:
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar
is running are you entering any character? NO but still putchar
works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar
uses this buffer as stdin
.
My problem was that was missing a mime handler for svg
files in lighttpd configuration file. Adding these to your lighttpd.conf
could solve your problem:
mimetype.assign = (
".pdf" => "application/pdf",
".sig" => "application/pgp-signature",
".spl" => "application/futuresplash",
".class" => "application/octet-stream",
".ps" => "application/postscript",
".torrent" => "application/x-bittorrent",
".dvi" => "application/x-dvi",
".gz" => "application/x-gzip",
".pac" => "application/x-ns-proxy-autoconfig",
".swf" => "application/x-shockwave-flash",
".tar.gz" => "application/x-tgz",
".tgz" => "application/x-tgz",
".tar" => "application/x-tar",
".zip" => "application/zip",
".mp3" => "audio/mpeg",
".m3u" => "audio/x-mpegurl",
".wma" => "audio/x-ms-wma",
".wax" => "audio/x-ms-wax",
".ogg" => "application/ogg",
".wav" => "audio/x-wav",
".gif" => "image/gif",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".png" => "image/png",
".svg" => "image/svg+xml",
".xbm" => "image/x-xbitmap",
".xpm" => "image/x-xpixmap",
".xwd" => "image/x-xwindowdump",
".css" => "text/css",
".html" => "text/html",
".htm" => "text/html",
".js" => "text/javascript",
".asc" => "text/plain",
".c" => "text/plain",
".cpp" => "text/plain",
".log" => "text/plain",
".conf" => "text/plain",
".text" => "text/plain",
".txt" => "text/plain",
".spec" => "text/plain",
".dtd" => "text/xml",
".xml" => "text/xml",
".mpeg" => "video/mpeg",
".mpg" => "video/mpeg",
".mov" => "video/quicktime",
".qt" => "video/quicktime",
".avi" => "video/x-msvideo",
".asf" => "video/x-ms-asf",
".asx" => "video/x-ms-asf",
".wmv" => "video/x-ms-wmv",
".bz2" => "application/x-bzip",
".tbz" => "application/x-bzip-compressed-tar",
".tar.bz2" => "application/x-bzip-compressed-tar",
".odt" => "application/vnd.oasis.opendocument.text",
".ods" => "application/vnd.oasis.opendocument.spreadsheet",
".odp" => "application/vnd.oasis.opendocument.presentation",
".odg" => "application/vnd.oasis.opendocument.graphics",
".odc" => "application/vnd.oasis.opendocument.chart",
".odf" => "application/vnd.oasis.opendocument.formula",
".odi" => "application/vnd.oasis.opendocument.image",
".odm" => "application/vnd.oasis.opendocument.text-master",
".ott" => "application/vnd.oasis.opendocument.text-template",
".ots" => "application/vnd.oasis.opendocument.spreadsheet-template",
".otp" => "application/vnd.oasis.opendocument.presentation-template",
".otg" => "application/vnd.oasis.opendocument.graphics-template",
".otc" => "application/vnd.oasis.opendocument.chart-template",
".otf" => "application/vnd.oasis.opendocument.formula-template",
".oti" => "application/vnd.oasis.opendocument.image-template",
".oth" => "application/vnd.oasis.opendocument.text-web",
# make the default mime type application/octet-stream.
"" => "application/octet-stream",
)
The answer (I hope) no one ever wanted
Eval like behavior
getattr(locals().get("foo") or globals().get("foo"), "bar")()
Why not add auto-importing
getattr(
locals().get("foo") or
globals().get("foo") or
__import__("foo"),
"bar")()
In case we have extra dictionaries we want to check
getattr(next((x for x in (f("foo") for f in
[locals().get, globals().get,
self.__dict__.get, __import__])
if x)),
"bar")()
We need to go deeper
getattr(next((x for x in (f("foo") for f in
([locals().get, globals().get, self.__dict__.get] +
[d.get for d in (list(dd.values()) for dd in
[locals(),globals(),self.__dict__]
if isinstance(dd,dict))
if isinstance(d,dict)] +
[__import__]))
if x)),
"bar")()
# Write a Python program that accepts a string and calculate the number of digits
# andletters.
stre =input("enter the string-->")
countl = 0
countn = 0
counto = 0
for i in stre:
if i.isalpha():
countl += 1
elif i.isdigit():
countn += 1
else:
counto += 1
print("The number of letters are --", countl)
print("The number of numbers are --", countn)
print("The number of characters are --", counto)
Might be irrelevant for OP's Q, but I've tried all openssl statements with all the different flags, while trying to connect with PHP \SoapClient(...)
and after 3 days I finally found a solution that worked for me.
$ cd path/to/certificate/
$ openssl pkcs12 -in personal_certificate.pfx -out public_key.pem -clcerts
First you have to enter YOUR_CERT_PASSWORD
once, then DIFFERENT_PASSWORD!
twice. The latter will possibly be available to everyone with access to code.
<?php
$wsdlUrl = "https://example.com/service.svc?singlewsdl";
$publicKey = "rel/path/to/certificate/public_key.pem";
$password = "DIFFERENT_PASSWORD!";
$params = [
'local_cert' => $publicKey,
'passphrase' => $password,
'trace' => 1,
'exceptions' => 0
];
$soapClient = new \SoapClient($wsdlUrl, $params);
var_dump($soapClient->__getFunctions());
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
There are two ways to fix this:
1. Unix Way: In 4 simple steps
which git
in the terminal to know the location of your git
executable. Open that directory & locate gitk
inside the bin
folder. Copy the path --- typically /usr/local/git/bin
~/.bash_profile
to add the location of local git
& gitk
in the paths or, simply copy-pasta from the sample written below.Sample bash_profile
:
# enabling gitk
export PATH=/usr/local/git/bin:$PATH
If you don't have a bash_profile
want to learn how to create one, then click here.
gitk
executable (typically at /usr/local/bin/gitk
), take a backup & open it in a text editor. Find all occurences of lime
in the file & replace them with "#99FF00"
.source ~/.bash_profile
Now, run gitk
2. HomeBrew way
Updates - If you do not have homebrew
on your mac, get it installed first. It may require sudo
privileges.
brew update
brew doctor
brew link git
/usr/local/Cellar/git/2.4.0/bin
to path & then reload bash & run gitk
which git
& observe if git is still linked to /usr/bin/git
source ~/.bash_profile
Here is one version that works with filenames that may contain spaces, newlines, and glob characters as well:
find . -type f -printf "%T@ %p\0" | sort -zk1nr
find ... -printf
prints the file modification time (Epoch value) followed by a space and \0
terminated filenames.sort -zk1nr
reads NUL terminated data and sorts it reverse numericallyAs the question is tagged with Linux, I am assuming GNU Core Utilities are available.
You can pipe the above with:
xargs -0 printf "%s\n"
to print the modification time and filenames sorted by modification time (most recent first) terminated by newlines.
As now to day CKEditor 4+ launched we have to use it.ekeditor 4 setData documentation
CKEDITOR.instances['editor1'].setData(value);
Where editor1
is textarea Id.
Old methods such as insertHtml('html data')
and insertText('text data')
also works fine.
and to get data use
var ckdata = CKEDITOR.instances['editor1'].getData();
var data = CKEDITOR.instances.editor1.getData();
Byte is not a standard type in C or C++. Try char, which is usually and at least 8 bits long.
I know this question is 8 year old, however there was and is a better solution for this purpose. It's always been there, and still is: User32.dll!MessageBoxTimeout.
This is an undocumented function used by Microsoft Windows, and it does exactly what you want and even more. It supports different languages as well.
C# Import:
[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();
How to use it in C#:
uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/ 0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;
NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);
Work smarter, not harder.
Instead of converting the class to a function, an easy step would be to create a function to include the jsx for the component which uses the 'classes', in your case the <container></container>
and then call this function inside the return of the class render() as a tag. This way you are moving out the hook to a function from the class. It worked perfectly for me. In my case it was a <table>
which i moved to a function- TableStmt outside and called this function inside the render as <TableStmt/>
Working for me, just add className="nav-link"
and activeStyle{{textDecoration:'underline'}}
<NavLink className="nav-link" to="/" exact activeStyle=
{{textDecoration:'underline'}}>My Record</NavLink>
Not enough rep for a comment.
The getElementById()
based method in the selected answer won't work if the anchor has name
but not id
set (which is not recommended, but does happen in the wild).
Something to bare in mind if you don't have control of the document markup (e.g. webextension).
The location
based method in the selected answer can also be simplified with location.replace
:
function jump(hash) { location.replace("#" + hash) }
You can use the ES6 Destructuring Assignment feature with a rest operator. A comma indicates where you want to remove the element and the rest (...arr) operator to give you the remaining elements of the array.
const source = [1,2,3,5,6];_x000D_
_x000D_
function removeFirst(list) {_x000D_
var [, ...arr] = list;_x000D_
return arr;_x000D_
}_x000D_
const arr = removeFirst(source);_x000D_
console.log(arr); // [2, 3, 5, 6]_x000D_
console.log(source); // [1, 2, 3, 5, 6]
_x000D_
Inci framework you can do download like so:
function clubDownload($clubname)
{
$this->load->library("excel");
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$this->load->model('Members_student_model');
$query = $this->db->query("SELECT * FROM student WHERE $clubname!='' order by id desc");
$resultdatanew=$query->result_array();
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;
$object->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("B1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("C1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("D1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("E1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("F1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("G1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("H1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("I1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$headerStyle = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb'=>'CCE5FF'),
),
'font' => array(
'bold' => true,
)
);
$object->getActiveSheet()->getStyle('A1:'.'I1')->applyFromArray($headerStyle);
$table_columns = array("id", "studentid", "passport", "lastname", "firstname","university","commencing",$clubname,"added_date");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
$excel_row = 2;
foreach($resultdatanew as $row)
{
$id=$row['id'];
$studentid=$row['studentid'];
$passport=$row['passport'];
$lastname=$row['last_name'];
$firstname=$row['first_name'];
$passport=$row['university'];
$commencing=$row['commencing'];
$email_id=$row['email_id'];
$added_date=$row['added_date'];
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$id);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $studentid);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $lastname);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $firstname);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $commencing);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $email_id);
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $added_date);
$excel_row++;
}
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="club' .$clubname.'-'.date('Y-m-d') . '.xls');
$object_writer->save('php://output');
grep -A20 -B20 pattern file.txt
Search pattern and show 20 lines after and before pattern
If I understand your question correctly, is it the fact that the required
attribute appears to have default behaviour in Safari that's confusing you? If so, see: http://w3c.github.io/html/sec-forms.html#the-required-attribute
required
is not a custom attribute in HTML 5. It's defined in the spec, and is used in precisely the way you're presently using it.
EDIT: Well, not precisely. As ms2ger has pointed out, the required
attribute is a boolean attribute, and here's what the HTML 5 spec has to say about those:
Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
See: http://w3c.github.io/html/infrastructure.html#sec-boolean-attributes
I use WinSplit Revolution for the keyboard arrangement capability and I use bblean as a replacement for Explorer. It has multiple workspace capabilities built right in and it allows you to customize it exactly how you want it to look.
Have you read this :
Delegates are a useful construct in event-based systems. Essentially Delegates are objects that encode a method dispatch on a specified object. This document shows how java inner classes provide a more generic solution to such problems.
What is a Delegate? Really it is very similar to a pointer to member function as used in C++. But a delegate contains the target object alongwith the method to be invoked. Ideally it would be nice to be able to say:
obj.registerHandler(ano.methodOne);
..and that the method methodOne would be called on ano when some specific event was received.
This is what the Delegate structure achieves.
Java Inner Classes
It has been argued that Java provides this functionality via anonymous inner classes and thus does not need the additional Delegate construct.
obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
methodOne(ev);
}
} );
At first glance this seems correct but at the same time a nuisance. Because for many event processing examples the simplicity of the Delegates syntax is very attractive.
General Handler
However, if event-based programming is used in a more pervasive manner, say, for example, as a part of a general asynchronous programming environment, there is more at stake.
In such a general situation, it is not sufficient to include only the target method and target object instance. In general there may be other parameters required, that are determined within the context when the event handler is registered.
In this more general situation, the java approach can provide a very elegant solution, particularly when combined with use of final variables:
void processState(final T1 p1, final T2 dispatch) {
final int a1 = someCalculation();
m_obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
dispatch.methodOne(a1, ev, p1);
}
} );
}
final * final * final
Got your attention?
Note that the final variables are accessible from within the anonymous class method definitions. Be sure to study this code carefully to understand the ramifications. This is potentially a very powerful technique. For example, it can be used to good effect when registering handlers in MiniDOM and in more general situations.
By contrast, the Delegate construct does not provide a solution for this more general requirement, and as such should be rejected as an idiom on which designs can be based.
INSERT
syntax cannot have WHERE
clause. The only time you will find INSERT
has WHERE
clause is when you are using INSERT INTO...SELECT
statement.
The first syntax is already correct.
This is a simple JavaScript sound recorder and editor. You can try it.
https://www.danieldemmel.me/JSSoundRecorder/
Can download from here
As you are using SQL Server 2008, go with Martin's answer.
If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date
column type, I'd use:
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
For iPhone and iPod touch, create icons that measure:
57 X 57 pixels
114 X 114 pixels (high resolution @2X)
For iPad, create an icon that measures:
72 x 72 pixels
144 X 144 pixels (high resolution @2X)
:%s/\(^\s*\)\@<= /\t/g
Translation: Search for every instance of 4 consecutive spaces (after the = character), but only if the entire line up to that point is whitespace (this uses the zero-width look-behind assertion, \@<=
). Replace each found instance with a tab character.
You'll need to use a static
readonly
list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T>
rather than List<T>
.
private static readonly ReadOnlyCollection<string> _metrics =
new ReadOnlyCollection<string>(new[]
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
});
public static ReadOnlyCollection<string> Metrics
{
get { return _metrics; }
}
This is for my comment on Andrey's answer but I cant include code in the comments.
Is you preference activity being called from you main activity? you could place this in the on resume...
@Override
protected void onResume() {
if (!(PreferenceManager.getDefaultSharedPreferences(
getApplicationContext()).getString("listLanguage", "en")
.equals(langPreference))) {
refresh();
}
super.onResume();
}
private void refresh() {
finish();
Intent myIntent = new Intent(Main.this, Main.class);
startActivity(myIntent);
}
Using Python 3 and Python 2.6+ syntax:
with open(filepath, 'w') as file_handler:
for item in the_list:
file_handler.write("{}\n".format(item))
This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.
Starting with Python 3.6, "{}\n".format(item)
can be replaced with an f-string: f"{item}\n"
.
I am late to this question, but here is what you can do with MySQL (as I use MySQL). I am sharing my observations here:
1) SELECT COUNT(*) AS TOTAL_ROWS FROM <TABLE_NAME>
Result
Row Count: 508534
Console output: Affected rows: 0 Found rows: 1 Warnings: 0 Duration for 1 query: 0.125 sec.
Takes a while for a table with large number of rows, but the row count is very exact.
2) SHOW TABLE STATUS or SHOW TABLE STATUS WHERE NAME="<TABLE_NAME>"
Result
Row count: 511235
Console output: Affected rows: 0 Found rows: 1 Warnings: 0 Duration for 1 query: 0.250 sec
Summary: Row count is not exact.
3) SELECT * FROM information_schema.tables WHERE table_schema = DATABASE();
Result
Row count: 507806
Console output: Affected rows: 0 Found rows: 48 Warnings: 0 Duration for 1 query: 1.701 sec.
Row count is not exact.
I am not a MySQL or database expert, but I have found that for very large tables, you can use option 2 or 3 and get a 'fair idea' of how many rows are present.
I needed to get these row counts for displaying some stats on the UI. With the above queries, I knew that the total rows were more than 500,000, so I came up with showing stats like "More than 500,000 rows" without showing exact number of rows.
Maybe I have not really answered the OP's question, but I am sharing what I did in a situation where such statistics were needed. In my case, showing the approximate rows was acceptable and so the above worked for me.
Probably the easiest way would be use this app Hosts Editor . You need to have root
To avoid having to hardcode an absolute path, you can use the following method that will find and execute your script if it is in your root directory.
public static void runScript() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("./nameOfScript.sh");
//Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.
processBuilder.inheritIO();
Process process = processBuilder.start();
int exitValue = process.waitFor();
if (exitValue != 0) {
// check for errors
new BufferedInputStream(process.getErrorStream());
throw new RuntimeException("execution of script failed!");
}
}
Apart from what others have mentioned, I would like to add that, Linting will run through your source code to find
- formatting discrepancy
- non-adherence to coding standards and conventions
- pinpointing possible logical errors in your program
Running a Lint program over your source code, helps to ensure that source code is legible, readable, less polluted and easier to maintain.
In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.
As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.
With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.
Add the following code into your .vimrc
:
if has('clipboard')
if has('unnamedplus') " When possible use + register for copy-paste
set clipboard=unnamed,unnamedplus
else " On mac and Windows, use * register for copy-paste
set clipboard=unnamed
endif
endif
So I see many possibilities to achieve this.
string text = "Foobar-test";
Regex Match everything till the first "-"
Match result = Regex.Match(text, @"^.*?(?=-)");
^
match from the start of the string.*?
match any character (.
), zero or more times (*
) but as less as possible (?
)(?=-)
till the next character is a "-" (this is a positive look ahead)Regex Match anything that is not a "-" from the start of the string
Match result2 = Regex.Match(text, @"^[^-]*");
[^-]*
matches any character that is not a "-" zero or more timesRegex Match anything that is not a "-" from the start of the string till a "-"
Match result21 = Regex.Match(text, @"^([^-]*)-");
Will only match if there is a dash in the string, but the result is then found in capture group 1.
Split on "-"
string[] result3 = text.Split('-');
Result is an Array the part before the first "-" is the first item in the Array
Substring till the first "-"
string result4 = text.Substring(0, text.IndexOf("-"));
Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-")
)
You get then all the results (all the same) with this
Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result21.Groups[1]);
Console.WriteLine(result3[0]);
Console.WriteLine(result4);
I would prefer the first method.
You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-")
will be -1
. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.
Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius
void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for (i = 0; i <= triangleAmount; i++) {
glVertex2f(
x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.
Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.
You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.
You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.
ThreadLocal
variables are typically implemented as private static
.
In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.
C++20 offers a new way to achieve this by using std::source_location. This is currently accessible in gcc an clang as std::experimental::source_location
with #include <experimental/source_location>
.
The problem with macros like __LINE__
is that if you want to create for example a logging function that outputs the current line number along with a message, you always have to pass __LINE__
as a function argument, because it is expanded at the call site.
Something like this:
void log(const std::string msg) {
std::cout << __LINE__ << " " << msg << std::endl;
}
Will always output the line of the function declaration and not the line where log
was actually called from.
On the other hand, with std::source_location
you can write something like this:
#include <experimental/source_location>
using std::experimental::source_location;
void log(const std::string msg, const source_location loc = source_location::current())
{
std::cout << loc.line() << " " << msg << std::endl;
}
Here, loc
is initialized with the line number pointing to the location where log
was called.
You can try it online here.
You can get the user's WindowsIdentity object under Windows Authentication by:
WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;
and then you can get the information about the user like identity.Name.
Please note you need to have HttpContext for these code.
As you should know by now, purists say it's forbiden to run ordered tests. That might be true for unit tests. MSTest and other Unit Test frameworks are used to run pure unit test but also UI tests, full integration tests, you name it. Maybe we shouldn't call them Unit Test frameworks, or maybe we should and use them according to our needs. That's what most people do anyway.
I'm running VS2015 and I MUST run tests in a given order because I'm running UI tests (Selenium).
Priority - Doesn't do anything at all This attribute is not used by the test system. It is provided to the user for custom purposes.
orderedtest - it works but I don't recommend it because:
Other suggestions in this thread are interesting but you loose the ability to follow the test progress on Test Explorer.
You are left with the solution that purist will advise against, but in fact is the solution that works: sort by declaration order.
The MSTest executor uses an interop that manages to get the declaration order and this trick will work until Microsoft changes the test executor code.
This means the test method that is declared in the first place executes before the one that is declared in second place, etc.
To make your life easier, the declaration order should match the alphabetical order that is is shown in the Test Explorer.
I strongly suggest some old and tested rules:
VERY IMPORTANT
In order to execute the tests by the declaration order, you must use Run All in the Test Explorer.
Say you have 3 test classes (in my case tests for Chrome, Firefox and Edge). If you select a given class and right click Run Selected Tests it usually starts by executing the method declared in the last place.
Again, as I said before, declared order and listed order should match or else you'll in big trouble in no time.
don't forget to put a 'die' after your call to make the redirect happen before the rest of the code on the page is run threw. a. if you have header functions further down the page they will override the ones further up the code.
b: im assuming you dont want the rest of the code on the page to be run and that why your putting this redirect in in the first place [maybe].
example:
<?php
// do something here
header("Location: http://example.com/thankyou.php");
die();
//code down here now wont get run
?>
boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
if (Error == true)
{
System.out.print("Login unsuccessful");
}
else
{
System.out.print("Login successful");
}
Add environment variable for Android Home Targetting Platform Tools
echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
Restart Bash
source ~/.bash_profile
Now Check adb
Simply type
adb
on terminal
MVC
For an MVC project make the following changes (WebForms and Dot Net Core answer down below):
public static class WebApiConfig
{
public static string UrlPrefix { get { return "api"; } }
public static string UrlPrefixRelative { get { return "~/api"; } }
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class MvcApplication : System.Web.HttpApplication
{
...
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
}
}
This solution has the added bonus that we can fetch the base URL in javascript for making the AJAX calls:
<body>
@RenderBody()
<script type="text/javascript">
var apiBaseUrl = '@Url.Content(ProjectNameSpace.WebApiConfig.UrlPrefixRelative)';
</script>
@RenderSection("scripts", required: false)
and then within our Javascript files/code we can make our webapi calls that can access the session:
$.getJSON(apiBaseUrl + '/MyApi')
.done(function (data) {
alert('session data received: ' + data.whatever);
})
);
WebForms
Do the above but change the WebApiConfig.Register function to take a RouteCollection instead:
public static void Register(RouteCollection routes)
{
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
And then call the following in Application_Start:
WebApiConfig.Register(RouteTable.Routes);
Dot Net Core
Add the Microsoft.AspNetCore.Session NuGet package and then make the following code changes:
Call the AddDistributedMemoryCache and AddSession methods on the services object within the ConfigureServices function:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
...
services.AddDistributedMemoryCache();
services.AddSession();
and in the Configure function add a call to UseSession:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
app.UseSession();
app.UseMvc();
Within your controller, add a using statement at the top:
using Microsoft.AspNetCore.Http;
and then use the HttpContext.Session object within your code like so:
[HttpGet("set/{data}")]
public IActionResult setsession(string data)
{
HttpContext.Session.SetString("keyname", data);
return Ok("session data set");
}
[HttpGet("get")]
public IActionResult getsessiondata()
{
var sessionData = HttpContext.Session.GetString("keyname");
return Ok(sessionData);
}
you should now be able to hit:
http://localhost:1234/api/session/set/thisissomedata
and then going to this URL will pull it out:
http://localhost:1234/api/session/get
Plenty more info on accessing session data within dot net core here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state
Performance Concerns
Read Simon Weaver's answer below regarding performance. If you're accessing session data inside a WebApi project it can have very serious performance consequence - I have seen ASP.NET enforce a 200ms delay for concurrent requests. This could add up and become disastrous if you have many concurrent requests.
Security Concerns
Make sure you are locking down resources per user - an authenticated user shouldn't be able to retrieve data from your WebApi that they don't have access to.
Read Microsoft's article on Authentication and Authorization in ASP.NET Web API - https://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api
Read Microsoft's article on avoiding Cross-Site Request Forgery hack attacks. (In short, check out the AntiForgery.Validate method) - https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks
Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.
In short it works ok for a small data set or just key points from a data set.
For windows authentication
select your project.
Press F4
Disable "Anonymous Authentication" and enable "Windows Authentication"
Another option is using Google Guava's com.google.common.base.CaseFormat
George Hawkins left a comment with this example of usage:
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
I use join to separate the word in array with "and, or , / , &"
EXAMPLE
HTML
<p>London Mexico Canada</p>
<div></div>
JS
newText = $("p").text().split(" ").join(" or ");
$('div').text(newText);
Results
London or Mexico or Canada
A move from WebForms to MVC requires a complete sea-change in logic and brain processes. You're no longer interacting with the 'form' both server-side and client-side (and in fact even with WebForms you weren't interacting client-side). You've probably just mixed up a bit of thinking there, in that with WebForms and RUNAT="SERVER"
you were merely interacting with the building of the Web page.
MVC is somewhat similar in that you have server-side code in constructing the model (the data you need to build what your user will see), but once you have built the HTML you need to appreciate that the link between the server and the user no longer exists. They have a page of HTML, that's it.
So the HTML you are building is read-only. You pass the model through to the Razor page, which will build HTML appropriate to that model.
If you want to have a hidden element which sets true or false depending on whether this is the first view or not you need a bool in your model, and set it to True in the Action if it's in response to a follow up. This could be done by having different actions depending on whether the request is [HttpGet] or [HttpPost] (if that's appropriate for how you set up your form: a GET request for the first visit and a POST request if submitting a form).
Alternatively the model could be set to True when it's created (which will be the first time you visit the page), but after you check the value as being True or False (since a bool defaults to False when it's instantiated). Then using:
@Html.HiddenFor(x => x.HiddenPostBack)
in your form, which will put a hidden True. When the form is posted back to your server the model will now have that value set to True.
It's hard to give much more advice than that as your question isn't specific as to why you want to do this. It's perhaps vital that you read a good book on moving to MVC from WebForms, such as Steve Sanderson's Pro ASP.NET MVC.
I prefer the base name which is already answered by fge. Another way is :
ls /home/user/new/*.txt|awk -F"/" '{print $NF}'
one more ugly way is :
ls /home/user/new/*.txt| perl -pe 's/\//\n/g'|tail -1
Usually, you would do something like this:
$post_data = json_encode(array('item' => $post_data));
But, as it seems you want the output to be with "{}
", you better make sure to force json_encode()
to encode as object, by passing the JSON_FORCE_OBJECT
constant.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}
" brackets specify an object and "[]
" are used for arrays according to JSON specification.
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
Using sshpass works best. To just include your password in scp use the ' ':
scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
I'm using @foreach
when I send an entity that contains a list of entities ( for example to display 2 grids in 1 view )
For example if I'm sending as model the entity Foo that contains Foo1(List<Foo1>)
and Foo2(List<Foo2>)
I can refer to the first List with:
@foreach (var item in Model.Foo.Foo1)
{
@Html.DisplayFor(modelItem=> item.fooName)
}
Better documentation is now available and you can use both JSON and JavaScript based configurations: angular-cli documentation proxy
sample https proxy configuration
{
"/angular": {
"target": {
"host": "github.com",
"protocol": "https:",
"port": 443
},
"secure": false,
"changeOrigin": true,
"logLevel": "info"
}
}
To my knowledge with Angular 2.0 release setting up proxies using .ember-cli file is not recommended. official way is like below
edit "start"
of your package.json
to look below
"start": "ng serve --proxy-config proxy.conf.json",
create a new file called proxy.conf.json
in the root of the project and inside of that define your proxies like below
{
"/api": {
"target": "http://api.yourdomai.com",
"secure": false
}
}
Important thing is that you use npm start
instead of ng serve
Read more from here : Proxy Setup Angular 2 cli
I didn't see an answer that's clean and suitable for production-ready software, so here it goes:
/*
* Get current error_reporting value,
* so that we don't lose preferences set in php.ini and .htaccess
* and accidently reenable message types disabled in those.
*
* If you want to disable e.g. E_STRICT on a global level,
* use php.ini (or .htaccess for folder-level)
*/
$old_error_reporting = error_reporting();
/*
* Disable E_STRICT on top of current error_reporting.
*
* Note: do NOT use ^ for disabling error message types,
* as ^ will re-ENABLE the message type if it happens to be disabled already!
*/
error_reporting($old_error_reporting & ~E_STRICT);
// code that should not emit E_STRICT messages goes here
/*
* Optional, depending on if/what code comes after.
* Restore old settings.
*/
error_reporting($old_error_reporting);
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
I think except for disk space issuse, you should check the log in /var/log/mongodb
to know the details for why mongodb start failed.
cat /var/log/mongodb/mongod.log
2016-06-26T15:26:26.642+0800 I CONTROL [main] ***** SERVER RESTARTED *****
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] MongoDB starting : pid=8130 port=27017 dbpath=/var/lib/mongodb 64-bit host=hadoop-master
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] db version v3.2.7
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] git version: 4249c1d2b5999ebbf1fdf3bc0e0e3b3ff5c0aaf2
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1f 6 Jan 2014
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] allocator: tcmalloc
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] modules: none
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] build environment:
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] distmod: ubuntu1404
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] distarch: x86_64
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] target_arch: x86_64
2016-06-26T15:26:26.649+0800 I CONTROL [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1,192.168.3.10", port: 27017 }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2016-06-26T15:26:26.678+0800 E NETWORK [initandlisten] Failed to unlink socket file /tmp/mongodb-27017.sock errno:1 Operation not permitted
2016-06-26T15:26:26.678+0800 I - [initandlisten] Fatal Assertion 28578
2016-06-26T15:26:26.678+0800 I - [initandlisten]
***aborting after fassert() failure
So, here I need to rm all the files in the /tmp
. That works fine for me.
If you see this probably you are building in release mode. For production you should publish instead of building in release mode. For local development build in debug mode.
One thing you could try is using the following css:
.child-element {
padding-left: inherit;
padding-right: inherit;
position: absolute;
left: 0;
right: 0;
}
It lets the child element inherit the padding from the parent, then the child can be positioned to match the parents widht and padding.
Also, I am using box-sizing: border-box;
for the elements involved.
I have not tested this in all browsers, but it seems to be working in Chrome, Firefox and IE10.
Creating Custom ProgressBar like hotstar.
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/player_progressbar"
android:indeterminateDrawable="@drawable/custom_progress_bar"
/>
custom_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080" >
<shape
android:innerRadius="35dp"
android:shape="ring"
android:thickness="3dp"
android:useLevel="false" >
<size
android:height="80dp"
android:width="80dp" />
<gradient
android:centerColor="#80b7b4b2"
android:centerY="0.5"
android:endColor="#f4eef0"
android:startColor="#00938c87"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
Something like this should work
$code = "screen new file.css";
if (!preg_match("/^[-_a-zA-Z0-9.]+$/", $code))
{
echo "not valid";
}
This will echo "not valid"
In my project it was a trouble in:
android:text="@{safeUnbox(viewmodel.population)}"
So I've wrapped it in String.valueOf()
:
android:text="@{String.valueOf(safeUnbox(viewmodel.population))}"
And it was resolved
It's old question but just in case someone bump on this tread...
var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];
No need for regex, jQuery....
What about
Form1.textBox1.text = "change text";
note: 1. you have to "include" Form1 to your second form source file by using Form1;
This is a simple STL-only solution (~5 lines!) using std::find
and std::find_first_not_of
that handles repetitions of the delimiter (like spaces or periods for instance), as well leading and trailing delimiters:
#include <string>
#include <vector>
void tokenize(std::string str, std::vector<string> &token_v){
size_t start = str.find_first_not_of(DELIMITER), end=start;
while (start != std::string::npos){
// Find next occurence of delimiter
end = str.find(DELIMITER, start);
// Push back the token found into vector
token_v.push_back(str.substr(start, end-start));
// Skip all occurences of the delimiter to find new start
start = str.find_first_not_of(DELIMITER, end);
}
}
Try it out live!
I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
Addition to above all simplified responses.
If you are working with files in bash script, it's better to use file descriptor.
For example: If you want to read and write from/to the file "test.txt", use the file descriptor as show below:
FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor
# Reading from the file line by line using file descriptor
while read LINE; do
echo "$LINE"
done <&5
# Writing to the file using descriptor
echo "Adding the date: `date`" >&5
exec 5<&- # Closing a file descriptor
Make sure when you are trying to delete parent all children will cascade on delete. Or children have nullable foreign key.
If you have installed jdk8 on your Mac but now you want to remove it, just run below command "sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk"
In dotnet core QueryHelpers.AddQueryString() will accept an IDictionary<string,string> of key-value pairs. To save a few memory allocs and CPU cycles you can use SortedList<,> instead of Dictionary<,>, with an appropriate capacity and items added in sort order...
var queryParams = new SortedList<string,string>(2);
queryParams.Add("abc", "val1");
queryParams.Add("def", "val2");
string requestUri = QueryHelpers.AddQueryString("https://localhost/api", queryParams);
You need to set the text after the replace call:
$('.element span').each(function() {_x000D_
console.log($(this).text());_x000D_
var text = $(this).text().replace('N/A, ', '');_x000D_
$(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
<span>N/A, Category</span>_x000D_
</div>
_x000D_
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
2nd argument is where to start string and 3rd argument how many characters you need to show
$title = "This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string";
echo substr($title,0,50);
I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32
brew switch openssl 1.0.2s
worked for me on "macOS Mojave", "version 10.14.6".
WebSphere Application Server V7 does support Java Platform, Standard Edition (Java SE) 6 (see Specifications and API documentation in the Network Deployment (All operating systems), Version 7.0 Information Center) and it's since the release V8.5 when Java 7 has been supported.
I couldn't find the Java 6 SDK documentation, and could only consult IBM JVM Messages in Java 7 Windows documentation. Alas, I couldn't find the error message in the documentation either.
Since java.lang.UnsupportedClassVersionError is "Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.", you ran into an issue of building the application with more recent version of Java than the one supported by the runtime environment, i.e. WebSphere Application Server 7.0.
I may be mistaken, but I think that offset=6 in the message is to let you know what position caused the incompatibility issue to occur. It's irrelevant for you, for me, and for many other people, but some might find it useful, esp. when they generate bytecode themselves.
Run the versionInfo command to find out about the Installed Features of WebSphere Application Server V7, e.g.
C:\IBM\WebSphere\AppServer>.\bin\versionInfo.bat
WVER0010I: Copyright (c) IBM Corporation 2002, 2005, 2008; All rights reserved.
WVER0012I: VersionInfo reporter version 1.15.1.47, dated 10/18/11
--------------------------------------------------------------------------------
IBM WebSphere Product Installation Status Report
--------------------------------------------------------------------------------
Report at date and time February 19, 2013 8:07:20 AM EST
Installation
--------------------------------------------------------------------------------
Product Directory C:\IBM\WebSphere\AppServer
Version Directory C:\IBM\WebSphere\AppServer\properties\version
DTD Directory C:\IBM\WebSphere\AppServer\properties\version\dtd
Log Directory C:\ProgramData\IBM\Installation Manager\logs
Product List
--------------------------------------------------------------------------------
BPMPC installed
ND installed
WBM installed
Installed Product
--------------------------------------------------------------------------------
Name IBM Business Process Manager Advanced V8.0
Version 8.0.1.0
ID BPMPC
Build Level 20121102-1733
Build Date 11/2/12
Package com.ibm.bpm.ADV.V80_8.0.1000.20121102_2136
Architecture x86-64 (64 bit)
Installed Features Non-production
Business Process Manager Advanced - Client (always installed)
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
Installed Product
--------------------------------------------------------------------------------
Name IBM WebSphere Application Server Network Deployment
Version 8.0.0.5
ID ND
Build Level cf051243.01
Build Date 10/22/12
Package com.ibm.websphere.ND.v80_8.0.5.20121022_1902
Architecture x86-64 (64 bit)
Installed Features IBM 64-bit SDK for Java, Version 6
EJBDeploy tool for pre-EJB 3.0 modules
Embeddable EJB container
Sample applications
Stand-alone thin clients and resource adapters
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
Installed Product
--------------------------------------------------------------------------------
Name IBM Business Monitor
Version 8.0.1.0
ID WBM
Build Level 20121102-1733
Build Date 11/2/12
Package com.ibm.websphere.MON.V80_8.0.1000.20121102_2222
Architecture x86-64 (64 bit)
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
--------------------------------------------------------------------------------
End Installation Status Report
--------------------------------------------------------------------------------
I found the accepted answer does not work in all scenarios. To ensure it 100% works one must ALSO clear the npm cache. Either directly Goto the cache and clear locks, caches, anonymous-cli-metrics.json; or one can try npm cache clean
.
Since the author had cleared the cache before trying the recommended solution its possible that failed to make it part of the pre-requisites.
Specifying a VOLUME
line in a Dockerfile configures a bit of metadata on your image, but how that metadata is used is important.
First, what did these two lines do:
WORKDIR /usr/src/app
VOLUME . /usr/src/app
The WORKDIR
line there creates the directory if it doesn't exist, and updates some image metadata to specify all relative paths, along with the current directory for commands like RUN
will be in that location. The VOLUME
line there specifies two volumes, one is the relative path .
, and the other is /usr/src/app
, both just happen to be the same directory. Most often the VOLUME
line only contains a single directory, but it can contain multiple as you've done, or it can be a json formatted array.
You cannot specify a volume source in the Dockerfile: A common source of confusion when specifying volumes in a Dockerfile is trying to match the runtime syntax of a source and destination at image build time, this will not work. The Dockerfile can only specify the destination of the volume. It would be a trivial security exploit if someone could define the source of a volume since they could update a common image on the docker hub to mount the root directory into the container and then launch a background process inside the container as part of an entrypoint that adds logins to /etc/passwd, configures systemd to launch a bitcoin miner on next reboot, or searches the filesystem for credit cards, SSNs, and private keys to send off to a remote site.
What does the VOLUME line do? As mentioned, it sets some image metadata to say a directory inside the image is a volume. How is this metadata used? Every time you create a container from this image, docker will force that directory to be a volume. If you do not provide a volume in your run command, or compose file, the only option for docker is to create an anonymous volume. This is a local named volume with a long unique id for the name and no other indication for why it was created or what data it contains (anonymous volumes are were data goes to get lost). If you override the volume, pointing to a named or host volume, your data will go there instead.
VOLUME breaks things: You cannot disable a volume once defined in a Dockerfile. And more importantly, the RUN
command in docker is implemented with temporary containers. Those temporary containers will get a temporary anonymous volume. That anonymous volume will be initialized with the contents of your image. Any writes inside the container from your RUN
command will be made to that volume. When the RUN
command finishes, changes to the image are saved, and changes to the anonymous volume are discarded. Because of this, I strongly recommend against defining a VOLUME
inside the Dockerfile. It results in unexpected behavior for downstream users of your image that wish to extend the image with initial data in volume location.
How should you specify a volume? To specify where you want to include volumes with your image, provide a docker-compose.yml
. Users can modify that to adjust the volume location to their local environment, and it captures other runtime settings like publishing ports and networking.
Someone should document this! They have. Docker includes warnings on the VOLUME usage in their documentation on the Dockerfile along with advice to specify the source at runtime:
- Changing the volume from within the Dockerfile: If any build steps change the data within the volume after it has been declared, those changes will be discarded.
...
- The host directory is declared at container run-time: The host directory (the mountpoint) is, by its nature, host-dependent. This is to preserve image portability, since a given host directory can’t be guaranteed to be available on all hosts. For this reason, you can’t mount a host directory from within the Dockerfile. The
VOLUME
instruction does not support specifying ahost-dir
parameter. You must specify the mountpoint when you create or run the container.
Is the first line in your script:
#!/bin/bash
or
#!/bin/sh
the sh shell produces this error messages, not bash
make sure you call your setcookie function before any output happens on your site.
also, if your users are logging out, you should also delete/invalidate their session variables.
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
swift 2 version of the @MS AppTech answer
func handlePan(panGest : UIPanGestureRecognizer) {
let velocity : CGPoint = panGest.velocityInView(self.view);
let magnitude : CGFloat = CGFloat(sqrtf((Float(velocity.x) * Float(velocity.x)) + (Float(velocity.y) * Float(velocity.y))));
let slideMult :CGFloat = magnitude / 200;
//NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
let slideFactor : CGFloat = 0.1 * slideMult; // Increase for more of a slide
var finalPoint : CGPoint = CGPointMake(panGest.view!.center.x + (velocity.x * slideFactor),
panGest.view!.center.y + (velocity.y * slideFactor));
finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height);
UIView.animateWithDuration(Double(slideFactor*2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
panGest.view!.center = finalPoint;
}, completion: nil)
}
use this library : Print.JS
with this library you can print both HTML and PDF.
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
Many people have mentioned DecimalFormat
. But you can also use printf
if you have a recent version of Java:
System.out.printf("%1.2f", 3.14159D);
See the docs on the Formatter for more information about the printf format string.
You can call bringToFront() on the view you want to get in the front
This is an example:
yourView.bringToFront();
Nitpick:
You don't really escape the %
in the string that specifies the format for the printf()
(and scanf()
) family of functions.
The %
, in the printf()
(and scanf()
) family of functions, starts a conversion specification. One of the rules for conversion specification states that a %
as a conversion specifier (immediately following the %
that started the conversion specification) causes a '%'
character to be written with no argument converted.
The string really has 2 '%'
characters inside (as opposed to escaping characters: "a\bc"
is a string with 3 non null characters; "a%%b"
is a string with 4 non null characters).
There's actually a very good blog post that lists pro's and cons of three different approaches to this problem by Martyn Davies. You can read it at https://sendgrid.com/blog/embedding-images-emails-facts/.
I'd like to add a fourth approach using CSS background images.
Add
<div id="myImage"></div>
to your e-mail body and a css class like:
#myImage {
background-image: url('data:image/png;base64,iVBOR...[some more encoding]...rkggg==');
width: [the-actual-image-width];
height: [the-actual-image-height];
}
if you're using scala and know the generic type at compile time, but don't want to manually pass TypeReference everywhere in all your api l ayers, you can use the following code (with jackson 2.9.5):
def read[T](entityStream: InputStream)(implicit typeTag: WeakTypeTag[T]): T = {
//nathang: all of this *crazy* scala reflection allows us to handle List[Seq[Map[Int,Value]]]] without passing
// new TypeReference[List[Seq[Map[Int,Value]]]]](){} to the function
def recursiveFindGenericClasses(t: Type): JavaType = {
val current = typeTag.mirror.runtimeClass(t)
if (t.typeArgs.isEmpty) {
val noSubtypes = Seq.empty[Class[_]]
factory.constructParametricType(current, noSubtypes:_*)
}
else {
val genericSubtypes: Seq[JavaType] = t.typeArgs.map(recursiveFindGenericClasses)
factory.constructParametricType(current, genericSubtypes:_*)
}
}
val javaType = recursiveFindGenericClasses(typeTag.tpe)
json.readValue[T](entityStream, javaType)
}
which can be used like this:
read[List[Map[Int, SomethingToSerialize]]](inputStream)
document.documentElement.classList.add('myCssClass');
classList
is supported since ie10: https://caniuse.com/#search=classlist
In Javascript, for example, functions are treated as the same mixed type as everything else (int
, string
, float
, bool
). As such, you can create functions on the fly, assign them to things, and call them back later. It's useful but, not something you want to over use or you'll confuse everyone who has to maintain your code after you...
This is some code I was playing with to see how deep this rabbit hole goes:
var x = new Object;
x.thingy = new Array();
x.thingy[0] = function(){ return function(){ return function(){ alert('index 0 pressed'); }; }; }
x.thingy[1] = function(){ return function(){ return function(){ alert('index 1 pressed'); }; }; }
x.thingy[2] = function(){ return function(){ return function(){ alert('index 2 pressed'); }; }; }
for(var i=0 ;i<3; i++)
x.thingy[i]()()();
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
If return no correct AUTO_INCREMENT, try it:
ANALYZE TABLE `my_table`;
SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE (TABLE_NAME = 'my_table');
This clear cache for table, in BD
The + character occurring in a data URI should be encoded as %2B. This is like encoding any other string in a URI. For example, argument separators (? and &) must be encoded when a URI with an argument is sent as part of another URI.
Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.
For example if you delete a record using ORM, and your DELETE CASCADE
will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.
Following is the list of conversion characters that you may use in the printf:
%d – for signed decimal integer
%f – for the floating point
%o – octal number
%c – for a character
%s – a string
%i – use for integer base 10
%u – for unsigned decimal number
%x – hexadecimal number
%% – for writing % (percentage)
%n – for new line = \n
Had the exact same issue. I installed curl 7.19 to /opt/curl/ to make sure that I would not affect current curl on our production servers. Once I linked libcurl.so.4 to /usr/lib:
sudo ln -s /opt/curl/lib/libcurl.so /usr/lib/libcurl.so.4
I still got the same error! Durf.
But running ldconfig make the linkage for me and that worked. No need to set the LD_RUN_PATH or LD_LIBRARY_PATH at all. Just needed to run ldconfig.
After reading so many articles Stackoverflow posts and demo applications to check variable property attributes, I decided to put all the attributes information together:
Below is the detailed article link where you can find above mentioned all attributes, that will definitely help you. Many thanks to all the people who give best answers here!!
1.strong (iOS4 = retain )
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
2.weak -
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Strong & Weak Explanation, Thanks to BJ Homer:
Imagine our object is a dog, and that the dog wants to run away (be deallocated).
Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.
Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.
As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.
When we use weak?
The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).
3.retain = strong
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
4.assign
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
Here's the pattern I have used for creating plugins with additional methods. You would use it like:
$('selector').myplugin( { key: 'value' } );
or, to invoke a method directly,
$('selector').myplugin( 'mymethod1', 'argument' );
Example:
;(function($) {
$.fn.extend({
myplugin: function(options,arg) {
if (options && typeof(options) == 'object') {
options = $.extend( {}, $.myplugin.defaults, options );
}
// this creates a plugin for each element in
// the selector or runs the function once per
// selector. To have it do so for just the
// first element (once), return false after
// creating the plugin to stop the each iteration
this.each(function() {
new $.myplugin(this, options, arg );
});
return;
}
});
$.myplugin = function( elem, options, arg ) {
if (options && typeof(options) == 'string') {
if (options == 'mymethod1') {
myplugin_method1( arg );
}
else if (options == 'mymethod2') {
myplugin_method2( arg );
}
return;
}
...normal plugin actions...
function myplugin_method1(arg)
{
...do method1 with this and arg
}
function myplugin_method2(arg)
{
...do method2 with this and arg
}
};
$.myplugin.defaults = {
...
};
})(jQuery);
On Windows, search for Anaconda PowerShell Prompt. Right click the program and select Run as administrator. In the command prompt, execute the following command:
conda update -n base -c defaults conda
Your Anaconda should now update without admin related errors.
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
If you are using pm2, you can use it with autorestart
set to false
:
$ pm2 ecosystem
This will generate a sample ecosystem.config.js
:
module.exports = {
apps: [
{
script: './scripts/companies.js',
autorestart: false,
},
{
script: './scripts/domains.js',
autorestart: false,
},
{
script: './scripts/technologies.js',
autorestart: false,
},
],
}
$ pm2 start ecosystem.config.js
Here is C# version in Xamarin.iOS
var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();
cv::Mat
is the new type introduce in OpenCV2.X while the IplImage*
is the "legacy" image structure.
Although, cv::Mat
does support the usage of IplImage
in the constructor parameters, the default library does not provide function for the other way. You will need to extract the image header information manually. (Do remember that you need to allocate the IplImage structure, which is lack in your example).
Dates are stored in their timestamp format. If you want everything that belongs to a specific month, query for the start and the end of the month.
var start = new Date(2010, 11, 1);
var end = new Date(2010, 11, 30);
db.posts.find({created_on: {$gte: start, $lt: end}});
//taken from http://cookbook.mongodb.org/patterns/date_range/
I faced same issue in eclipse neon simple maven java project
But I add below details inside pom.xml file
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
After right click on project > maven > update project (checked force update)
Its resolve me to display error on project
Hope it's will helpful
Thansk
In my case, the parameter Persist Security Info=true
with the user and password in connection string is causing the problem.
Removing the parameter or set to false
solve the problem.
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');
sectionName, groupName and fieldName are present in etc/system.xml file of your module.
The above code will automatically fetch config value of currently viewed store.
If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig
function as below:
$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);
(update: 2018)
Note that pd.Timegrouper
is depreciated and will be removed. Use instead:
df.groupby(pd.Grouper(freq='M'))
Instead of using
response.sendRedirect("/demo.jsp");
Which does a permanent redirect to an absolute URL path,
Rather use RequestDispatcher
. Example:
RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);
To get dynamic tagging to work with ajax, here's what I did.
Select2 version 3.5
This is easy in version 3.5 because it offers the createSearchChoice
hook. It even works for multiple select, as long as multiple: true
and tags: true
are set.
HTML
<input type="hidden" name="locations" value="Whistler, BC" />
JS
$('input[name="locations"]').select2({
tags: true,
multiple: true,
createSearchChoice: function(term, data) {
if (!data.length)
return { id: term, text: term };
},
ajax: {
url: '/api/v1.1/locations',
dataType: 'json'
}
});
The idea here is to use select2's createSearchChoice
hook which passes you both the term
that the user entered and the ajax response (as data
). If ajax returns an empty list, then tell select2 to offer the user-entered term
as an option.
Demo: https://johnny.netlify.com/select2-examples/version3
Select2 version 4.X
Version 4.X doesn't have a createSearchChoice
hook anymore, but here's how I did the same thing.
HTML
<select name="locations" multiple>
<option value="Whistler, BC" selected>Whistler, BC</option>
</select>
JS
$('select[name="locations"]').select2({
ajax: {
url: '/api/v1.1/locations',
dataType: 'json',
data: function(params) {
this.data('term', params.term);
return params;
},
processResults: function(data) {
if (data.length)
return {
results: data
};
else
return {
results: [{ id: this.$element.data('term'), text: this.$element.data('term') }]
};
}
}
});
The ideas is to stash the term that the user typed into jQuery's data store inside select2's data
hook. Then in select2's processResults
hook, I check if the ajax response is empty. If it is, I grab the stashed term that the user typed and return it as an option to select2.
I was getting this problem when using IBM RSA 9.6.1 when building a brand new development machine. The problem for me ended up being because of HTTPS on the Global Maven repository. My solution was to create a Maven settings.xml that forced it to use HTTP.
The key to me was that the central repository was empty when I exploded it under Maven Repositories -- > Global Repositories
Using the following settings file worked for me:
<settings>
<activeProfiles>
<!--make the profile active all the time -->
<activeProfile>insecurecentral</activeProfile>
</activeProfiles>
<profiles>
<profile>
<id>insecurecentral</id>
<!--Override the repository (and pluginRepository) "central" from the Maven Super POM -->
<repositories>
<repository>
<id>central</id>
<url>http://repo.maven.apache.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://repo.maven.apache.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>
I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".
You would use it like this:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</td>
</tr>
</table>
Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:
<span isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</span>
Here is the directive's code:
angular.module('awesome', []).directive('isolateClick', function() {
return {
link: function(scope, elem) {
elem.on('click', function(e){
e.stopPropagation();
});
}
};
});
Checkout And Run The Following Code. It will help you...
$( function() {_x000D_
$.widget( "custom.iconselectmenu", $.ui.selectmenu, {_x000D_
_renderItem: function( ul, item ) {_x000D_
var li = $( "<li>" ),_x000D_
wrapper = $( "<div>", { text: item.label } );_x000D_
_x000D_
if ( item.disabled ) {_x000D_
li.addClass( "ui-state-disabled" );_x000D_
}_x000D_
_x000D_
$( "<span>", {_x000D_
style: item.element.attr( "data-style" ),_x000D_
"class": "ui-icon " + item.element.attr( "data-class" )_x000D_
})_x000D_
.appendTo( wrapper );_x000D_
_x000D_
return li.append( wrapper ).appendTo( ul );_x000D_
}_x000D_
});_x000D_
_x000D_
$( "#filesA" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons" );_x000D_
_x000D_
$( "#filesB" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget" )_x000D_
.addClass( "ui-menu-icons customicons" );_x000D_
_x000D_
$( "#people" )_x000D_
.iconselectmenu()_x000D_
.iconselectmenu( "menuWidget")_x000D_
.addClass( "ui-menu-icons avatar" );_x000D_
} );_x000D_
</script>_x000D_
<style>_x000D_
h2 {_x000D_
margin: 30px 0 0 0;_x000D_
}_x000D_
fieldset {_x000D_
border: 0;_x000D_
}_x000D_
label
_x000D_
{_x000D_
display: block;_x000D_
}_x000D_
_x000D_
/* select with custom icons */_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item-wrapper {_x000D_
padding: 0.5em 0 0.5em 3em;_x000D_
}_x000D_
.ui-selectmenu-menu .ui-menu.customicons .ui-menu-item .ui-icon {_x000D_
height: 24px;_x000D_
width: 24px;_x000D_
top: 0.1em;_x000D_
}_x000D_
.ui-icon.video {_x000D_
background: url("images/24-video-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.podcast {_x000D_
background: url("images/24-podcast-square.png") 0 0 no-repeat;_x000D_
}_x000D_
.ui-icon.rss {_x000D_
background: url("images/24-rss-square.png") 0 0 no-repeat;_x000D_
}_x000D_
_x000D_
/* select with CSS avatar icons */_x000D_
option.avatar {_x000D_
background-repeat: no-repeat !important;_x000D_
padding-left: 20px;_x000D_
}_x000D_
.avatar .ui-icon {_x000D_
background-position: left top;_x000D_
}
_x000D_
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<title>jQuery UI Selectmenu - Custom Rendering</title>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="demo">_x000D_
_x000D_
<form action="#">_x000D_
<h2>Selectmenu with framework icons</h2>_x000D_
<fieldset>_x000D_
<label for="filesA">Select a File:</label>_x000D_
<select name="filesA" id="filesA">_x000D_
<option value="jquery" data-class="ui-icon-script">jQuery.js</option>_x000D_
<option value="jquerylogo" data-class="ui-icon-image">jQuery Logo</option>_x000D_
<option value="jqueryui" data-class="ui-icon-script">ui.jQuery.js</option>_x000D_
<option value="jqueryuilogo" selected="selected" data-class="ui-icon-image">jQuery UI Logo</option>_x000D_
<option value="somefile" disabled="disabled" data-class="ui-icon-help">Some unknown file</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom icon images</h2>_x000D_
<fieldset>_x000D_
<label for="filesB">Select a podcast:</label>_x000D_
<select name="filesB" id="filesB">_x000D_
<option value="mypodcast" data-class="podcast">John Resig Podcast</option>_x000D_
<option value="myvideo" data-class="video">Scott González Video</option>_x000D_
<option value="myrss" data-class="rss">jQuery RSS XML</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
_x000D_
<h2>Selectmenu with custom avatar 16x16 images as CSS background</h2>_x000D_
<fieldset>_x000D_
<label for="people">Select a Person:</label>_x000D_
<select name="people" id="people">_x000D_
<option value="1" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16');">John Resig</option>_x000D_
<option value="2" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/e42b1e5c7cfd2be0933e696e292a4d5f?d=monsterid&r=g&s=16');">Tauren Mills</option>_x000D_
<option value="3" data-class="avatar" data-style="background-image: url('http://www.gravatar.com/avatar/bdeaec11dd663f26fa58ced0eb7facc8?d=monsterid&r=g&s=16');">Jane Doe</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080' ^^^^^
The https://
is wrong, it should be http://
. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.
You need to use multiple rules to implement OR-like semantics, since matches are always AND-ed together within a rule. Alternatively, you can do matching against port-indexing ipsets (ipset create blah bitmap:port
).
Just in case someone is looking to do the same using Reactive Forms:
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
</select>
<p>Selected Country: {{country?.name}}</p>
</form>
Check the working example here
I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:
from cx_Freeze import setup, Executable
import sys
productName = "ProductName"
if 'bdist_msi' in sys.argv:
sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
sys.argv += ['--install-script', 'install.py']
exe = Executable(
script="main.py",
base="Win32GUI",
targetName="Product.exe"
)
setup(
name="Product.exe",
version="1.0",
author="Me",
description="Copyright 2012",
executables=[exe],
scripts=[
'install.py'
]
)
The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:
data$new <- rowSums( data[,43:167] )
If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.
There is a method in php-intl extension:
locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE'])