I think you can simplify this by just adding the necessary CSS properties to your special scrollable menu class..
CSS:
.scrollable-menu {
height: auto;
max-height: 200px;
overflow-x: hidden;
}
HTML
<ul class="dropdown-menu scrollable-menu" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Action</a></li>
..
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
</ul>
Working example: https://www.bootply.com/86116
Bootstrap 4
XML - You can use android:scrollHorizontally
Attribute
Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally).
May be a boolean value, such as "true" or "false".
Prigramacaly - setHorizontallyScrolling(boolean)
var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
Here is what I used to call something I couldn't change using NSInvocation:
SEL theSelector = NSSelectorFromString(@"setOrientation:animated:");
NSInvocation *anInvocation = [NSInvocation
invocationWithMethodSignature:
[MPMoviePlayerController instanceMethodSignatureForSelector:theSelector]];
[anInvocation setSelector:theSelector];
[anInvocation setTarget:theMovie];
UIInterfaceOrientation val = UIInterfaceOrientationPortrait;
BOOL anim = NO;
[anInvocation setArgument:&val atIndex:2];
[anInvocation setArgument:&anim atIndex:3];
[anInvocation performSelector:@selector(invoke) withObject:nil afterDelay:1];
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex @Bergi mentioned just the string version for new RegExp constructor
Just do this:
$ git clone git://example.com/myproject
$ cd myproject
$ git checkout branchxyz
Branch branchxyz set up to track remote branch branchxyz from origin.
Switched to a new branch 'branchxyz'
$ git pull
Already up-to-date.
$ git branch
* branchxyz
master
$ git branch -a
* branchxyz
master
remotes/origin/HEAD -> origin/master
remotes/origin/branchxyz
remotes/origin/branch123
You see, 'git clone git://example.com/myprojectt' fetches everything, even the branches, you just have to checkout them, then your local branch will be created.
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
Info from http://w3schools.com/sql/sql_null_values.asp:
1) NULL values represent missing unknown data.
2) By default, a table column can hold NULL values.
3) NULL values are treated differently from other values
4) It is not possible to compare NULL and 0; they are not equivalent.
5) It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
6) We will have to use the IS NULL and IS NOT NULL operators instead
So in case of your problem:
SELECT pid FROM planets WHERE userid IS NULL
If you are using Multidex on Android 4.4 and prior, your issue might be that your activity class is located in the second dex file and therefore not found by the android system.
To keep your activity class in the main dex file, see this page:
https://developer.android.com/studio/build/multidex.html#keep
To find which classes are located in a dex file use Android Studio.
Simply drag n drop your apk into Android Studio. You should be able to see your dex files in the apk explorer.
Then select the dex file to see what classes are inside.
another alternative is dexdump:
You can check the content of your dex files contained in your apk by using the command dexdump which can be found in
android-sdk/build-tools/27.0.3/dexdump
For windows users see this tool I made to ease the process
The optimizer should be smart enough to give you the same result either way for normal queries. Check the execution plan and they should give you the same thing. If they don't, I would normally consider the JOIN to be faster. All systems are different, though, so you should profile the code on your system to be sure.
Click on the file and hover on Preferences. there you will find the first option as Settings and click on that. There search run code. and scroll and find the option code runner: Run in Terminal. now check the option below it
You can just call a method on your scope to reverse it for you, like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.0.5/angular.min.js"></script>
<script>
angular.module('myApp', []).controller('Ctrl', function($scope) {
$scope.items = [1, 2, 3, 4];
$scope.reverse = function(array) {
var copy = [].concat(array);
return copy.reverse();
}
});
</script>
</head>
<body ng-controller="Ctrl">
<ul>
<li ng-repeat="item in items">{{item}}</li>
</ul>
<ul>
<li ng-repeat="item in reverse(items)">{{item}}</li>
</ul>
</body>
</html>
Note that the $scope.reverse
creates a copy of the array since Array.prototype.reverse
modifies the original array.
Just wanted to contribute my version, using regex:
private static final String UNICODE_REGEX = "\\\\u([0-9a-f]{4})";
private static final Pattern UNICODE_PATTERN = Pattern.compile(UNICODE_REGEX);
...
String message = "\u0048\u0065\u006C\u006C\u006F World";
Matcher matcher = UNICODE_PATTERN.matcher(message);
StringBuffer decodedMessage = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(
decodedMessage, String.valueOf((char) Integer.parseInt(matcher.group(1), 16)));
}
matcher.appendTail(decodedMessage);
System.out.println(decodedMessage.toString());
With bootstrap you can use
<a href="#/new-page.html" class="btn btn-primary">
Click
</a>
Could use JSON2HTML to transform it to nicely formatted HTML list .. may be a little more powerful than you really need though
You missed out omniORB. This is a pretty full CORBA implementation, so you can also use it to talk to other languages that have CORBA support.
Pandas >= 0.25.0
, named aggregationsSince pandas version 0.25.0
or higher, we are moving away from the dictionary based aggregation and renaming, and moving towards named aggregations which accepts a tuple
. Now we can simultaneously aggregate + rename to a more informative column name:
Example:
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
a b c d group
0 0.521279 0.914988 0.054057 0.125668 0
1 0.426058 0.828890 0.784093 0.446211 0
2 0.363136 0.843751 0.184967 0.467351 1
3 0.241012 0.470053 0.358018 0.525032 1
Apply GroupBy.agg
with named aggregation:
df.groupby('group').agg(
a_sum=('a', 'sum'),
a_mean=('a', 'mean'),
b_mean=('b', 'mean'),
c_sum=('c', 'sum'),
d_range=('d', lambda x: x.max() - x.min())
)
a_sum a_mean b_mean c_sum d_range
group
0 0.947337 0.473668 0.871939 0.838150 0.320543
1 0.604149 0.302074 0.656902 0.542985 0.057681
You can enable GZIP compression entirely in your Web.config
file. This is particularly useful if you're on shared hosting and can't configure IIS directly, or you want your config to carry between all environments you target.
<system.webServer>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>
To test whether compression is working or not, use the developer tools in Chrome or Firebug for Firefox and ensure the HTTP response header is set:
Content-Encoding: gzip
Note that this header won't be present if the response code is 304 (Not Modified). If that's the case, do a full refresh (hold shift or control while you press the refresh button) and check again.
I would like to add to some of the other answers here, if you don't need the first item but say the second number for example you can use rownumber in a subquery and base your result set off of that.
SELECT * FROM
(
SELECT
ROW_NUM() OVER (PARTITION BY Id ORDER BY record_date, other_cols) as rownum,
*
FROM products P
) INNER
WHERE rownum = 2
This also allows you to order off multiple columns in the subquery which may help if two record_dates have identical values. You can also partition off of multiple columns if needed by delimiting them with a comma
I think that it should be:
$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
my jQuery powered solution is below :)
Text Element:
<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />
Javascript behind:
<script type="text/javascript" language="javascript">
function fnCheckValue() {
var myVal = $("#txtTextBox").val();
if (myVal == "") {
alert("Blank message");
return false;
}
else {
return true;
}
}
function EnterEvent(e) {
if (e.keyCode == 13) {
if (fnCheckValue()) {
$("#btnSubmitButton").trigger("click");
} else {
return false;
}
}
}
$("#btnSubmitButton").click(function () {
return fnCheckValue();
});
</script>
Issue Log: App Not Setup. This app is still in development mode. and you dont have access to it. register test user or ask an app admin for permission
HOW TO CHANGE TO LIVE MODE
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. toggle the switch from OFF to ON
HOW TO ADD AS TEST OR ADMIN
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. go to : Roles > Roles > Press Add for example administrator
4. Search your new admin/tester Facebook account.
5. admin must enter facebook password to confirm.then submit
the new admin must go to developer.facebook page and accept the request
6. go to : https://developers.facebook.com
7. Profile > Requests > Confirm
8. Congratulation you have been assign as new Admin
HOW TO GET AND SET HASHKEY FOR DEVELOPMENT
as Refer to Facebook Login Documentation
https://developers.facebook.com/docs/android/getting-started/#create_hash
The most preferable solution by me is by code ( Troubleshooting Sample Apps )
it will print out the hash key. you can update it on
https://developers.facebook.com/apps/yourFacebookappID/settings/basic/
on Android > Key Hashes section
a step by step process on how to get the hashKey.
step by step process on how Update on Facebook Developer.
Open Facebook Developer Page. You need access as to update the Facebook Developer page.
https://developers.facebook.com
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.
In C++ you can overload operator<<
for ostream
and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
In case your operator<<
wants to print out internals of class A
and really needs access to its private and protected members you could also declare it as a friend function:
class A {
private:
friend std::ostream& operator<<(std::ostream&, const A&);
int j;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.j << ")";
}
Short story: The 0
tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x
is an arbitrary choice.
Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).
The BCPL language used the syntax 8 1234
for octal numbers. When Ken Thompson created B from BCPL, he used the 0
prefix instead. This is great because
0
is the same in both bases),00005 == 05
), and#123
).When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x
was arbitrarily chosen (00
was probably ruled out as awkward).
C# is a descendant of C, so it inherits the syntax.
For people having this problem and coding for Xamarin Android in C#, this might also be a quick solution:
pager.ChildViewAdded += (sender, e) => {
e.Child.Measure ((int)MeasureSpecMode.Unspecified, (int)MeasureSpecMode.Unspecified);
e.Parent.LayoutParameters.Height = e.Child.MeasuredHeight;
};
This is mainly useful if your child views are of the same height. Otherwise, you would be required to store some kind of "minimumHeight" value over all children that you check against, and even then you might not want to have empty spaces visible beneath your smaller child views.
The solution itself is not sufficient for me though, but that is because my child items are listViews and their MeasuredHeight is not calculated correctly, it seems.
My favourite solution was the one by @EugenKonkov because it didn't imply the presence of other utilities (the coreutils package).
But it failed for the relative paths "." and "..", so here is a slightly improved version handling these special cases.
It still fails if the user doesn't have the permission to cd
into the parent directory of the relative path, though.
#! /bin/sh
# Takes a path argument and returns it as an absolute path.
# No-op if the path is already absolute.
function to-abs-path {
local target="$1"
if [ "$target" == "." ]; then
echo "$(pwd)"
elif [ "$target" == ".." ]; then
echo "$(dirname "$(pwd)")"
else
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
fi
}
A couple of suggestions:
.animate
method, like .animate({width: maxWidth})
, it should scale the other dimension for you automatically.The Underscore.String library has a function that does Insert
insert(string, index, substring) => string
like so
insert("Hello ", 6, "world");
// => "Hello world"
If you are using v2.2.0 then there is one more option available to detect changes in $routes.
To react to params changes in the same component, you can watch the $route object:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
Or, use the beforeRouteUpdate guard introduced in 2.2:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
Reference: https://router.vuejs.org/en/essentials/dynamic-matching.html
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
You need to be careful with inheritance:
>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
Check types more strictly, like this:
def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
Besides that, your approach will work fine, that's what special methods are there for.
It sounds like your site has CSS or JS that depends on running in quirks mode. Which is why you need garbage above your doctype to render "correctly". I suggest removing said garbage and then fixing your CSS+JS to actually work in standards mode; you'll save yourself a lot of pain in the long run.
I recommend you just use rubyinstaller
It is recommended by the official Ruby page - see https://www.ruby-lang.org/en/downloads/
Ways of Installing Ruby
We have several tools on each major platform to install Ruby:
- On Linux/UNIX, you can use the package management system of your distribution or third-party tools (rbenv and RVM).
- On OS X machines, you can use third-party tools (rbenv and RVM).
- On Windows machines, you can use RubyInstaller.
https://developers.google.com/chrome-developer-tools/docs/settings
A String is an immutable type. This means that whenever you start concatenating strings with each other you're creating new strings each time. If you do so many times you end up with a lot of heap overhead and the risk of running out of memory.
A StringBuilder instance is used to be able to append strings to the same instance, creating a string when you call the ToString method on it.
Due to the overhead of instantiating a StringBuilder object it's said by Microsoft that it's useful to use when you have more than 5-10 string concatenations.
For sample code I suggest you take a look here:
AH = 09 DS:DX = pointer to string ending in "$"
returns nothing
- outputs character string to STDOUT up to "$"
- backspace is treated as non-destructive
- if Ctrl-Break is detected, INT 23 is executed
ref: http://stanislavs.org/helppc/int_21-9.html
.data
string db 2 dup(' ')
.code
mov ax,@data
mov ds,ax
mov al,10
add al,15
mov si,offset string+1
mov bl,10
div bl
add ah,48
mov [si],ah
dec si
div bl
add ah,48
mov [si],ah
mov ah,9
mov dx,string
int 21h
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.
I'm a beginner too and I faced that issue a couple of times myself.
<ng-container>
to the rescueThe Angular
<ng-container>
is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.(...)
The
<ng-container>
is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:if (someCondition) { statement1; statement2; statement3; }
Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The
<ng-container>
satisfies a similar need in Angular templates.
According to this pull request :
<ng-container>
is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.
<ng-container>
is rendered as an HTML comment.
so this angular template :
<div>
<ng-container>foo</ng-container>
<div>
will produce this kind of output :
<div>
<!--template bindings={}-->foo
<div>
So ng-container
is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo"
) in your application but don't want to wrap them with another element.
<div>
<ng-container *ngIf="true">
<h2>Title</h2>
<div>Content</div>
</ng-container>
</div>
will then produce :
<div>
<h2>Title</h2>
<div>Content</div>
</div>
Or maybe
background: transparent !important;
color: #ffffff;
As others mentioned ~
just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.
One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3
as the number to which 3
should be added in order to get zero and you'll see that this number is 1101
, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.
1101 +
0011 // 3
=
10000
=
0000 // lose carry bit because integers have a constant number of bits.
Therefore 1101
is -3
, flip the bits you get 0010
which is two.
I tried all of the suggestions but was still unable to run msiexec.exe
with parameters that contained spaces. So my solution ended up using System.Diagnostics.ProcessStartInfo
:
# can have spaces here, no problems
$settings = @{
CONNECTION_STRING = "... ..."
ENTITY_CONTEXT = "... ..."
URL = "..."
}
$settingsJoined = ($settings.Keys | % { "$_=""$($settings[$_])""" }) -join " "
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.WorkingDirectory = $ScriptDirectory
$pinfo.FileName = "msiexec.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "/l* install.log /i installer.msi $settingsJoined"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
Use DateTime::diff
(aka date_diff
):
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
Or:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
You can then get the interval as a integer by calling $interval->days
.
The backdrop to my solution recommendation is the story of a friend who, well into the second week of his first job, wiped half a build-server clean. So the basic task is to figure out if a file exists, and if so, let's delete it. But there are a few treacherous rapids on this river:
Everything is a file.
Scripts have real power only if they solve general tasks
To be general, we use variables
We often use -f force in scripts to avoid manual intervention
And also love -r recursive to make sure we create, copy and destroy in a timely fashion.
Consider the following scenario:
We have the file we want to delete: filesexists.json
This filename is stored in a variable
<host>:~/Documents/thisfolderexists filevariable="filesexists.json"
We also hava a path variable to make things really flexible
<host>:~/Documents/thisfolderexists pathtofile=".."
<host>:~/Documents/thisfolderexists ls $pathtofile
filesexists.json history20170728 SE-Data-API.pem thisfolderexists
So let's see if -e
does what it is supposed to. Does the files exist?
<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?
0
It does. Magic.
However, what would happen, if the file variable got accidentally be evaluated to nuffin'
<host>:~/Documents/thisfolderexists filevariable=""
<host>:~/Documents/thisfolderexists [ -e $pathtofile/$filevariable ]; echo $?
0
What? It is supposed to return with an error... And this is the beginning of the story how that entire folder got deleted by accident
An alternative could be to test specifically for what we understand to be a 'file'
<host>:~/Documents/thisfolderexists filevariable="filesexists.json"
<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?
0
So the file exists...
<host>:~/Documents/thisfolderexists filevariable=""
<host>:~/Documents/thisfolderexists test -f $pathtofile/$filevariable; echo $?
1
So this is not a file and maybe, we do not want to delete that entire directory
man test
has the following to say:
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
...
-h FILE
FILE exists and is a symbolic link (same as -L)
You can use the ast module and write a NodeVisitor that verifies that the type of each node is part of a whitelist.
import ast, math
locals = {key: value for (key,value) in vars(math).items() if key[0] != '_'}
locals.update({"abs": abs, "complex": complex, "min": min, "max": max, "pow": pow, "round": round})
class Visitor(ast.NodeVisitor):
def visit(self, node):
if not isinstance(node, self.whitelist):
raise ValueError(node)
return super().visit(node)
whitelist = (ast.Module, ast.Expr, ast.Load, ast.Expression, ast.Add, ast.Sub, ast.UnaryOp, ast.Num, ast.BinOp,
ast.Mult, ast.Div, ast.Pow, ast.BitOr, ast.BitAnd, ast.BitXor, ast.USub, ast.UAdd, ast.FloorDiv, ast.Mod,
ast.LShift, ast.RShift, ast.Invert, ast.Call, ast.Name)
def evaluate(expr, locals = {}):
if any(elem in expr for elem in '\n#') : raise ValueError(expr)
try:
node = ast.parse(expr.strip(), mode='eval')
Visitor().visit(node)
return eval(compile(node, "<string>", "eval"), {'__builtins__': None}, locals)
except Exception: raise ValueError(expr)
Because it works via a whitelist rather than a blacklist, it is safe. The only functions and variables it can access are those you explicitly give it access to. I populated a dict with math-related functions so you can easily provide access to those if you want, but you have to explicitly use it.
If the string attempts to call functions that haven't been provided, or invoke any methods, an exception will be raised, and it will not be executed.
Because this uses Python's built in parser and evaluator, it also inherits Python's precedence and promotion rules as well.
>>> evaluate("7 + 9 * (2 << 2)")
79
>>> evaluate("6 // 2 + 0.0")
3.0
The above code has only been tested on Python 3.
If desired, you can add a timeout decorator on this function.
This is the accepted answer written in a decorative way:
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(
new StringSelection(txtMySQLScript.getText()),
null
);
This should work. But I have same problems on an Android phone.
<input type="number" /> <input type="tel" />
I found out, that if I didn't include the jquerymobile-framework, the keypad showed correctly on the two types of fields.
But I havn't found a solution to solve that problem, if you really need to use jquerymobile.
UPDATE: I found out, that if the form-tag is stored out of the
<div data-role="page">
The number keypad isn't shown. This must be a bug...
The first thing you may want to confirm is the internet connection. Though, internet issues mostly will say that the repo cannot be accessed.
Ensure you have set up ssh both locally and on your github. See how
Ensure you are using the ssh git remote. If you had cloned the https, just set the url to the ssh url, with this git command git remote set-url origin [email protected]:your-username/your-repo-name.git
If you have set up ssh properly but it just stopped working, do the following:
eval "$(ssh-agent -s)"
ssh-add
If you are still having the issue, check to ensure that you have not deleted the ssh from your github. In a case where the ssh has been deleted from github, you can add it back. Use pbcopy < ~/.ssh/id_rsa.pub
to copy the ssh key and then go to your github ssh setting and add it.
I will recommend you always use ssh. For most teams I've worked with, you can't access the repo (which are mostly private) except you use ssh. For a beginner, it may appear to be harder but later you'll find it quite easier and more secured.
"Casting" is different than conversion. In this case, window.location.hash
will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:
window.location.hash = ""+page_number;
window.location.hash = String(page_number);
These conversions are ideal if you don't want an error to be thrown when page_number
is null
or undefined
. Whereas page_number.toString()
and page_number.toLocaleString()
will throw when page_number
is null
or undefined
.
When you only need to cast, not convert, this is how to cast to a string in TypeScript:
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
The <string>
or as string
cast annotations tell the TypeScript compiler to treat page_number
as a string at compile time; it doesn't convert at run time.
However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>
, then to <string>
:
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
So it's easier to just convert, which handles the type at run time and compile time:
window.location.hash = String(page_number);
(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)
Another way is using a SQL Server built-in feature named Client Statistics
which is accessible through Menu > Query > Include Client Statistics.
You can run each query in separated query window and compare the results which is given in Client Statistics
tab just beside the Messages
tab.
For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.
You can read all 3 ways for acquiring execution time in here.
You may even need to display Estimated Execution Plan
ctrlL for further investigation about your query.
You could use the undocumented
DBCC LOG(databasename, typeofoutput)
where typeofoutput:
0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.
For example, DBCC LOG(database, 1)
You could also try fn_dblog.
For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.
I think that what you're after is DESCRIBE
DESCRIBE table;
You can also use SHOW TABLES
SHOW TABLES;
to get a list of the tables in your database.
The .get() method will return an array from a jQuery object. In addition you can use .map to project to something before calling get()
var idarray = $("#myDiv")
.find("span") //Find the spans
.map(function() { return this.id; }) //Project Ids
.get(); //ToArray
It's stored in the process (shell) and since you've exported it, any processes that process spawns.
Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.
I use latest CSS and "+" didn't work for me so I end up with
:first-child
I use []
.
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.
Read The official Docs of collection
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
The jar file is just an executable java program. If you want to modify the code, you have to open the .java files.
In the example you give, you're perfectly right, you have to set the title attribute.
If the aria-label
is one tool used by assistive technologies (like screen readers), it is not natively supported on browsers and has no effect on them. It won't be of any help to most of the people targetted by the WCAG (except screen reader users), for instance a person with intellectal disabilities.
The "X" is not sufficient enough to give information to the action led by the button (think about someone with no computer knowledge). It might mean "close", "delete", "cancel", "reduce", a strange cross, a doodle, nothing.
Despite the fact that the W3C seems to promote the aria-label
rather that the title
attribute here: http://www.w3.org/TR/2014/NOTE-WCAG20-TECHS-20140916/ARIA14 in a similar example, you can see that the technology support does not include standard browsers : http://www.w3.org/WAI/WCAG20/Techniques/ua-notes/aria#ARIA14
In fact aria-label
, in this exact situation might be used to give more context to an action:
For instance, blind people do not perceive popups like those of us with good vision, it's like a change of context. "Back to the page" will be a more convenient alternative for a screen reader, when "Close" is more significant for someone with no screen reader.
<button
aria-label="Back to the page"
title="Close" onclick="myDialog.close()">X</button>
You may be looking for the special HTML character,
.
You can use this to get a line break, and it can be inserted immediately following the last character in the current line. One place this is especially useful is if you want to include multiple lines in a list within a title or alt
label.
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {_x000D_
$(window).scroll(function fix_element() {_x000D_
$('#target').css(_x000D_
$(window).scrollTop() > 100_x000D_
? { 'position': 'fixed', 'top': '10px' }_x000D_
: { 'position': 'relative', 'top': 'auto' }_x000D_
);_x000D_
return fix_element;_x000D_
}());_x000D_
});
_x000D_
body {_x000D_
height: 2000px;_x000D_
padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
padding: 5px;_x000D_
background: #efefef;_x000D_
}_x000D_
#target {_x000D_
color: #c00;_x000D_
font: 15px arial;_x000D_
padding: 10px;_x000D_
margin: 10px;_x000D_
border: 1px solid #c00;_x000D_
width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
I tend to use /Library/Java/Home
. The way the preferences pane works this should be up to date with your preferred version.
Another method is to use the io/ioutil
and strings
libraries to read the entire file's bytes, convert them into a string and split them using a "\n
" (newline) character as the delimiter, for example:
import (
"io/ioutil"
"strings"
)
func main() {
bytesRead, _ := ioutil.ReadFile("something.txt")
file_content := string(bytesRead)
lines := strings.Split(file_content, "\n")
}
Technically you're not reading the file line-by-line, however you are able to parse each line using this technique. This method is applicable to smaller files. If you're attempting to parse a massive file use one of the techniques that reads line-by-line.
It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/
You need to use cat
to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.
test="$(cat DSC_0251.JPG | base64)"
However, base64
can read from the file itself:
test=$( base64 DSC_0251.JPG )
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result)
to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!
pkill -9 -u `id -u username`
Note: if you want to be nice remove -9, but it will not kill all kinds of processes.
INSERT INTO vendors (
name,
phone,
addressLine1,
addressLine2,
city,
state,
postalCode,
country,
customer_id
)
SELECT
name,
phone,
addressLine1,
addressLine2,
city,
state ,
postalCode,
country,
customer_id
FROM
customers;
Wouldn't List<ArrayList<String>> 2dlist = new ArrayList<ArrayList<String>>();
be a better (more efficient) implementation?
There is the instagram public API's tags section that can help you do this.
set
and get
API has been deprecated *The following code should only be used for version socket.io < 0.9
See: http://socket.io/docs/migrating-from-0-9/
It can be done through the handshake/authorization mechanism.
var cookie = require('cookie');
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
// if there is, parse the cookie
data.cookie = cookie.parse(data.headers.cookie);
// note that you will need to use the same key to grad the
// session id, as you specified in the Express setup.
data.sessionID = data.cookie['express.sid'];
} else {
// if there isn't, turn down the connection with a message
// and leave the function.
return accept('No cookie transmitted.', false);
}
// accept the incoming connection
accept(null, true);
});
All the attributes, that are assigned to the data object are now accessible through the handshake attribute of the socket.io connection object.
io.sockets.on('connection', function (socket) {
console.log('sessionID ' + socket.handshake.sessionID);
});
you can load images in your html somewhere using css display:none;
rule, then show them when you want with js or jquery
don't use js or jquery functions to preload is just a css rule Vs many lines of js to be executed
example: Html
<img src="someimg.png" class="hide" alt=""/>
Css:
.hide{
display:none;
}
jQuery:
//if want to show img
$('.hide').show();
//if want to hide
$('.hide').hide();
Preloading images by jquery/javascript is not good cause images takes few milliseconds to load in page + you have milliseconds for the script to be parsed and executed, expecially then if they are big images, so hiding them in hml is better also for performance, cause image is really preloaded without beeing visible at all, until you show that!
OAuth has two scenarios in real mode. The normal and default style of access is called online. In some cases, your application may need to access a Google API when the user is not present,It's offline scenarios . a refresh token is obtained in offline scenarios during the first authorization code exchange.
So you can get refersh_token is some scenarios ,not all.
you can have the content in https://developers.google.com/identity/protocols/OAuth2WebServer#offline .
Building up upon Manish Jain
's answer (which is meant for Web API 2 which simplifies things):
1) Use validation structures to response as many validation errors as possible. These structures can also be used to response to requests coming from forms.
public class FieldError
{
public String FieldName { get; set; }
public String FieldMessage { get; set; }
}
// a result will be able to inform API client about some general error/information and details information (related to invalid parameter values etc.)
public class ValidationResult<T>
{
public bool IsError { get; set; }
/// <summary>
/// validation message. It is used as a success message if IsError is false, otherwise it is an error message
/// </summary>
public string Message { get; set; } = string.Empty;
public List<FieldError> FieldErrors { get; set; } = new List<FieldError>();
public T Payload { get; set; }
public void AddFieldError(string fieldName, string fieldMessage)
{
if (string.IsNullOrWhiteSpace(fieldName))
throw new ArgumentException("Empty field name");
if (string.IsNullOrWhiteSpace(fieldMessage))
throw new ArgumentException("Empty field message");
// appending error to existing one, if field already contains a message
var existingFieldError = FieldErrors.FirstOrDefault(e => e.FieldName.Equals(fieldName));
if (existingFieldError == null)
FieldErrors.Add(new FieldError {FieldName = fieldName, FieldMessage = fieldMessage});
else
existingFieldError.FieldMessage = $"{existingFieldError.FieldMessage}. {fieldMessage}";
IsError = true;
}
public void AddEmptyFieldError(string fieldName, string contextInfo = null)
{
AddFieldError(fieldName, $"No value provided for field. Context info: {contextInfo}");
}
}
public class ValidationResult : ValidationResult<object>
{
}
2) Service layer will return ValidationResult
s, regardless of operation being successful or not. E.g:
public ValidationResult DoSomeAction(RequestFilters filters)
{
var ret = new ValidationResult();
if (filters.SomeProp1 == null) ret.AddEmptyFieldError(nameof(filters.SomeProp1));
if (filters.SomeOtherProp2 == null) ret.AddFieldError(nameof(filters.SomeOtherProp2 ), $"Failed to parse {filters.SomeOtherProp2} into integer list");
if (filters.MinProp == null) ret.AddEmptyFieldError(nameof(filters.MinProp));
if (filters.MaxProp == null) ret.AddEmptyFieldError(nameof(filters.MaxProp));
// validation affecting multiple input parameters
if (filters.MinProp > filters.MaxProp)
{
ret.AddFieldError(nameof(filters.MinProp, "Min prop cannot be greater than max prop"));
ret.AddFieldError(nameof(filters.MaxProp, "Check"));
}
// also specify a global error message, if we have at least one error
if (ret.IsError)
{
ret.Message = "Failed to perform DoSomeAction";
return ret;
}
ret.Message = "Successfully performed DoSomeAction";
return ret;
}
3) API Controller will construct the response based on service function result
One option is to put virtually all parameters as optional and perform custom validation which return a more meaningful response. Also, I am taking care not to allow any exception to go beyond the service boundary.
[Route("DoSomeAction")]
[HttpPost]
public HttpResponseMessage DoSomeAction(int? someProp1 = null, string someOtherProp2 = null, int? minProp = null, int? maxProp = null)
{
try
{
var filters = new RequestFilters
{
SomeProp1 = someProp1 ,
SomeOtherProp2 = someOtherProp2.TrySplitIntegerList() ,
MinProp = minProp,
MaxProp = maxProp
};
var result = theService.DoSomeAction(filters);
return !result.IsError ? Request.CreateResponse(HttpStatusCode.OK, result) : Request.CreateResponse(HttpStatusCode.BadRequest, result);
}
catch (Exception exc)
{
Logger.Log(LogLevel.Error, exc, "Failed to DoSomeAction");
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("Failed to DoSomeAction - internal error"));
}
}
I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:
1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers
2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded
hope it helps :)
It may be best to log onto the server directly instead of using SQL Management Studio
Ensure that the account you login as is dbowner for the database you want to set to MULTI_USER. Login as sa (using SQL server authentication) if you can
If your database is used by IIS, stop the website and the app pool that use it - this may be the process that's connected and blocking you from setting to MULTI_USER
USE MASTER
GO
-- see if any process are using *your* database specifically
SELECT * from master.sys.sysprocesses
WHERE spid > 50 -- process spids < 50 are reserved by SQL - we're not interested in these
AND dbid=DB_ID ('YourDbNameHere')
-- if so, kill the process:
KILL n -- where 'n' is the 'spid' of the connected process as identified using query above
-- setting database to read only isn't generally necessary, but may help:
ALTER DATABASE YourDbNameHere
SET READ_ONLY;
GO
-- should work now:
ALTER DATABASE Appswiz SET MULTI_USER WITH ROLLBACK IMMEDIATE
Refer here if you still have trouble:
AS A LAST ALTERNATIVE - If you've tried everything above and you're getting desperate you could try stopping the SQL server instance and start it again
You need to use event.stopPropagation()
$('#childDiv').click(function(event){
event.stopPropagation();
alert(event.target.id);
});?
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Dim
is short for Dimension and is used in VBA and VB6 to declare local variables.
Set on the other hand, has nothing to do with variable declarations. The Set
keyword is used to assign an object variable to a new object.
Hope that clarifies the difference for you.
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
var model = JSON.stringify({
'ID': 0,
'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
'VendorID': $('#Vendors').val()
})
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PartSourceAPI/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
var model = JSON.stringify({ 'ID': 0, ...': 5, 'PartNumber': 6, 'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}"
your data is something like this "{"model": "ID":0,"ProductID":6,"PartNumber":7,"VendorID":8}}" web api controller cannot bind it to Your model
Whereas @jbarrueta answer is perfect, in the 2.12 version of Jackson was introduced a new long-awaited type for the @JsonTypeInfo
annotation, DEDUCTION
.
It is useful for the cases when you have no way to change the incoming json or must not do so. I'd still recommend to use use = JsonTypeInfo.Id.NAME
, as the new way may throw an exception in complex cases when it has no way to determine which subtype to use.
Now you can simply write
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
@JsonSubTypes({
@JsonSubTypes.Type(Dog.class),
@JsonSubTypes.Type(Cat.class) }
)
public abstract class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And it will produce {"name":"ruffus", "breed":"english shepherd"}
and {"name":"goya", "favoriteToy":"mice"}
Once again, it's safer to use NAME
if some of the fields may be not present, like breed
or favoriteToy
.
None of the above answers worked for me. I kept getting this error:
Copy-Item : Access is denied
+ CategoryInfo : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
So this did it for me:
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes
Then from my host my machine in the Run box I just did this:
\\{IP address of nanoserver}\C$
The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.
You can run a small loop and change the dimension from 1xN to Nx1.
tmp=[]
for b in bus:
tmp.append([b])
bus=tmp
It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks
raw.githubusercontent.com/username/repo-name/branch-name/path
Replace username
with the username of the user that created the repo.
Replace repo-name
with the name of the repo.
Replace branch-name
with the name of the branch.
Replace path
with the path to the file.
To reverse to go to GitHub.com:
GitHub.com/username/repo-name/directory-path/blob/branch-name/filename
What about the shortcut CTRL+L?
It works for all shells e.g. Python, Bash, MySQL, MATLAB, etc.
List<Book> books_2 = new List<Book>(books_2.ToArray());
That should do exactly what you want. Demonstrated here.
Expanding on "splattered bits" answer, here is a complete script that does it:
@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
SET _baseDirQuery=SELECT SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) ^
FROM master.sys.master_files WHERE database_id = 1 AND file_id = 1;
ECHO.
SQLCMD.EXE -b -E -S localhost -d master -Q "%_baseDirQuery%" -W >data_dir.tmp
IF ERRORLEVEL 1 ECHO Error with automatically determining SQL data directory by querying your server&ECHO using Windows authentication.
CALL :getBaseDir data_dir.tmp _baseDir
IF "%_baseDir:~-1%"=="\" SET "_baseDir=%_baseDir:~0,-1%"
DEL /Q data_dir.tmp
echo DataDir: %_baseDir%
GOTO :END
::---------------------------------------------
:: Functions
::---------------------------------------------
:simplePrompt 1-question 2-Return-var 3-default-Val
SET input=%~3
IF "%~3" NEQ "" (
:askAgain
SET /p "input=%~1 [%~3]:"
IF "!input!" EQU "" (
GOTO :askAgain
)
) else (
SET /p "input=%~1 [null]: "
)
SET "%~2=%input%"
EXIT /B 0
:getBaseDir fileName var
FOR /F "tokens=*" %%i IN (%~1) DO (
SET "_line=%%i"
IF "!_line:~0,2!" == "c:" (
SET "_baseDir=!_line!"
EXIT /B 0
)
)
EXIT /B 1
:END
PAUSE
Update
Apparently, moment now provides its own type definitions (according to sivabudh at least from 2.14.1 upwards), thus you do not need typings
or @types
at all.
import * as moment from 'moment'
should load the type definitions provided with the npm package.
That said however, as said in moment/pull/3319#issuecomment-263752265 the moment team seems to have some issues in maintaining those definitions (they are still searching someone who maintains them).
You need to install moment
typings without the --ambient
flag.
Then include it using import * as moment from 'moment'
Thanks guys this really help me!
I found the perfert one really useful for database.
function numonly(root){
var reet = root.value;
var arr1=reet.length;
var ruut = reet.charAt(arr1-1);
if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
}
}
}
Then add the eventhandler:
onkeyup="numonly(this);"
It's very simple
self.navigationController?.view.semanticContentAttribute = .forceRightToLeft
Bitmasks are used when you want to encode multiple layers of information in a single number.
So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit.
rwx
---
110
110 in base 2 translates to 6 in base 10.
So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission.
Pseudocode:
PERM_READ = 4
PERM_WRITE = 2
PERM_EXEC = 1
user_permissions = 6
if (user_permissions & PERM_READ == TRUE) then
// this will be reached, as 6 & 4 is true
fi
You need a working understanding of binary representation of numbers and logical operators to understand bit fields.
My experience:
var text = $('#myInputField');
var myObj = {title: 'Some title', content: text};
$.post(myUrl, myObj, callback);
The problem is that I forgot to add .val() to the end of $('#myInputField'); this action makes me waste time trying to figure out what was wrong, causing Illegal Invocation Error, since $('#myInputField') was in a different file than that system pointed out incorrect code. Hope this answer help fellows in the same mistake to avoid to loose time.
Is this what you are looking for?
public function GetIndex(byref iaList() as integer, byval iInteger as integer) as integer
dim i as integer
for i=lbound(ialist) to ubound(ialist)
if iInteger=ialist(i) then
GetIndex=i
exit for
end if
next i
end function
Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.
Send stdout to a file
exec > file
with stderr
exec > file
exec 2>&1
append both stdout and stderr to file
exec >> file
exec 2>&1
As Jonathan Leffler mentioned in his comment:
exec
has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec
.
I posted a fix for this here
You can use this function to modify JSON.stringify
to encode arrays
, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Python doesn't have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line
counter += 1
implicitly makes counter
local to increment()
. Trying to execute this line, though, will try to read the value of the local variable counter
before it is assigned, resulting in an UnboundLocalError
.[2]
If counter
is a global variable, the global
keyword will help. If increment()
is a local function and counter
a local variable, you can use nonlocal
in Python 3.x.
Here you go this should give you the correct answers every time!
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # discriminant
if d < 0:
print ("This equation has no real solution")
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print ("This equation has one solutions: "), x
else:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
[edit on 2009-04-21]
As Micah pointed out, this only works when you have named that
particular range (hence .Name anyone?) Yeah, oops!
[/edit]
A little late to the party, I know, but in case anyone else catches this in a google search (as I just did), you could also try the following:
Dim cell as Range
Dim address as String
Set cell = Sheet1.Range("A1")
address = cell.Name
This should return the full address, something like "=Sheet1!$A$1".
Assuming you don't want the equal sign, you can strip it off with a Replace function:
address = Replace(address, "=", "")
In my case right after installing the MAMP accessing mysql from the terminal was giving the same socket error. At the end all it wanted was a restart and it's working.
newsource=[];newtarget=[]
for valueT in targetFiles:
for valueS in sourceFiles:
l1=len(valueS);l2=len(valueT);
j=0
while (j< l1):
if (str(valueT) == valueS[j:l1]) :
newsource.append(valueS)
newtarget.append(valueT)
j+=1
If you do the following, you will be able to use opencv build from OpenCV_INSTALL_PATH.
cmake_minimum_required(VERSION 2.8)
SET(OpenCV_INSTALL_PATH /home/user/opencv/opencv-2.4.13/release/)
SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")
SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib")
LINK_DIRECTORIES(${OpenCV_LIB_DIR})
set(OpenCV_LIBS opencv_core opencv_imgproc opencv_calib3d opencv_video opencv_features2d opencv_ml opencv_highgui opencv_objdetect opencv_contrib opencv_legacy opencv_gpu)
# find_package( OpenCV )
project(edge.cpp)
add_executable(edge edge.cpp)
function csvToArray($path)
{
try{
$csv = fopen($path, 'r');
$rows = [];
$header = [];
$index = 0;
while (($line = fgetcsv($csv)) !== FALSE) {
if ($index == 0) {
$header = $line;
$index = 1;
} else {
$row = [];
for ($i = 0; $i < count($header); $i++) {
$row[$header[$i]] = $line[$i];
}
array_push($rows, $row);
}
}
return $rows;
}catch (Exception $exception){
return false;
}
}
We can directly specify the destination file with the dest
option now. In the below example, the output json is stored into the /tmp/repo_version_file
- name: Get repository file repo_version model to set ambari_managed_repositories=false
uri:
url: 'http://<server IP>:8080/api/v1/stacks/HDP/versions/3.1/repository_versions/1?fields=operating_systems/*'
method: GET
force_basic_auth: yes
user: xxxxx
password: xxxxx
headers:
"X-Requested-By": "ambari"
"Content-type": "Application/json"
status_code: 200
dest: /tmp/repo_version_file
Using Bootstrap 3's grid system:
<div class="container">
<div class="row">
<div class="col-xs-4">Menu</div>
<div class="col-xs-8">
<div class="row">
<div class="col-md-4 col-md-push-8">Right Content</div>
<div class="col-md-8 col-md-pull-4">Content</div>
</div>
</div>
</div>
</div>
Working example: http://bootply.com/93614
First, we set two columns that will stay in place no matter the screen resolution (col-xs-*
).
Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*
).
Finally, we shift the display order using the matching class (col-md-[push|pull]-*
). You push the first column over by the amount of the second, and pull the second by the amount of the first.
If I'm not mistaken:
var jq = $.noConflict();
then you can call jquery function with jq.(whatever).
jq('#selector');
Creating local notifications are pretty easy. Just follow these steps.
On viewDidLoad() function ask user for permission that your apps want to display notifications. For this we can use the following code.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
})
Then you can create a button, and then in the action function you can write the following code to display a notification.
//creating the notification content
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = "Hey this is Simplified iOS"
content.subtitle = "iOS Development is fun"
content.body = "We are learning about iOS Local Notification"
content.badge = 1
//getting the notification trigger
//it will be called after 5 seconds
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
Notification will be displayed, just click on home button after tapping the notification button. As when the application is in foreground the notification is not displayed. But if you are using iPhone X. You can display notification even when the app is in foreground. For this you just need to add a delegate called UNUserNotificationCenterDelegate
For more details visit this blog post: iOS Local Notification Tutorial
I have change it little bit but still can not do few things.
I added that clicking on it close it - it was easy but very functional.
<div class="modal-dialog" data-dismiss="modal">
I also need different description under each photo. I added description in footer just to show what I need. It need to change with every photo.
HTML
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" data-dismiss="modal">
<div class="modal-content" >
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<img src="" class="imagepreview" style="width: 100%;" >
</div>
<div class="modal-footer">
<div class="col-xs-12">
<p class="text-left">1. line of description<br>2. line of description <br>3. line of description</p>
</div>
</div>
</div>
</div>
JavaScript:
$(function() {
$('.pop').on('click', function() {
$('.imagepreview').attr('src', $(this).find('img').attr('src'));
$('#imagemodal').modal('show');
});
});
Also it would be nice if this window will open only on 100% of screen. Here picture inside with description have more than 100% and in become scrollable... and if screen in much bigger than pictures it shoud stop only on orginal size. for ex. 900 px and no bigger in height.
This worked for me:
git remote set-url heroku <repo git>
This replacement old url heroku.
You can check with:
git remote -v
ObservableCollection<FacebookUser_WallFeed> result = new ObservableCollection<FacebookUser_WallFeed>(FacebookHelper.facebookWallFeeds);
echo "US/Central - 10:26 PM (CST)" | sed -n "s/^.*-\s*\(\S*\).*$/\1/p"
-n suppress printing
s substitute
^.* anything at the beginning
- up until the dash
\s* any space characters (any whitespace character)
\( start capture group
\S* any non-space characters
\) end capture group
.*$ anything at the end
\1 substitute 1st capture group for everything on line
p print it
Any user whose login shell setting in /etc/passwd
is an interactive shell can login. I don't think there's a totally reliable way to tell if a program is an interactive shell; checking whether it's in /etc/shells
is probably as good as you can get.
Other users can also login, but the program they run should not allow them to get much access to the system. And users that aren't allowed to login at all should have /etc/false
as their shell -- this will just log them out immediately.
Bear in mid, the MAX value will only be the maximum of committed values. It might return 1234, and you may need to consider that someone has already inserted 1235 but not committed.
Here is a concise breadth-first iterative solution, which I prefer to recursion:
const findCar = function(car) {
const carSearch = [cars];
while(carSearch.length) {
let item = carSearch.shift();
if (item.label === car) return true;
carSearch.push(...item.subs);
}
return false;
}
Escape sequences like "\n" work fine ! even with text area! I passed a java string with the "\n" to a html textarea and it worked fine as it works on consoles for java!
For returning multiple column indices, I recommend using the pandas.Index
method get_indexer
, if you have unique labels:
df = pd.DataFrame({"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]})
df.columns.get_indexer(['pear', 'apple'])
# Out: array([0, 1], dtype=int64)
If you have non-unique labels in the index (columns only support unique labels) get_indexer_for
. It takes the same args as get_indeder
:
df = pd.DataFrame(
{"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
index=[0, 1, 1])
df.index.get_indexer_for([0, 1])
# Out: array([0, 1, 2], dtype=int64)
Both methods also support non-exact indexing with, f.i. for float values taking the nearest value with a tolerance. If two indices have the same distance to the specified label or are duplicates, the index with the larger index value is selected:
df = pd.DataFrame(
{"pear": [1, 2, 3], "apple": [2, 3, 4], "orange": [3, 4, 5]},
index=[0, .9, 1.1])
df.index.get_indexer([0, 1])
# array([ 0, -1], dtype=int64)
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
Try it :Laravel 5.5
public function destroy($id){
$data = User::FindOrFail($id);
if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){
unlink('backend_assets/uploads/userPhoto/'.$data->photo);
}
try{
$data->delete();
$bug = 0;
}
catch(\Exception $e){
$bug = $e->errorInfo[1];
}
if($bug==0){
echo "success";
}else{
echo 'error';
}
}
The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc
, compile, then search for Swift.h
in your Derived Data folder. You should find the Swift header there.
I had the problem, that Xcode renamed my my-Project-Swift.h
to my_Project-Swift.h
Xcode doesn't like
"." "-"
etc. symbols. With the method above you can find the filename and import it to a Objective-C class.
Yes, a table row can slide up and down, but it's ugly, since it changes the shape of the table and makes everything jump. Instead, put and element in each td
... something that makes sense like a p
or h2
etc.
For how to implement a table slide toggle...
It's probably simplest to put the click handler on the entire table, .stopPropagation()
and check what was clicked.
If a td in a row with a colspan is clicked, close the p
in it. If it's not a td in a row with a colspan, then close then toggle the following row's p
.
It is essentially to wrap all your written content in an element inside the td
s, since you never want to slideUp
a td
or tr
or table shape will change!
Something like:
$(function() {
// Initially hide toggleable content
$("td[colspan=3]").find("p").hide();
// Click handler on entire table
$("table").click(function(event) {
// No bubbling up
event.stopPropagation();
var $target = $(event.target);
// Open and close the appropriate thing
if ( $target.closest("td").attr("colspan") > 1 ) {
$target.slideUp();
} else {
$target.closest("tr").next().find("p").slideToggle();
}
});
});?
... and try out this jsFiddle showing implementation of a +
- -
toggle.
The HTML just has to have alternating rows of several td
s and then a row with a td
of a colspan greater than 1. You can obviously adjust the specifics quite easily.
The HTML would look something like:
<table>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
<tr><td><p>Name</p></td><td><p>Age</p></td><td><p>Info</p></td></tr>
<tr><td colspan="3"><p>Blah blah blah blah blah blah blah.</p>
</td></tr>
</table>?
Going to provide a slightly different answer to those provided so far.
If you have a row for an anonymous user from localhost in your users table ''@'localhost'
then this will be treated as more specific than your user with wildcard'd host 'user'@'%'
. This is why it is necessary to also provide 'user'@'localhost'
.
You can see this explained in more detail at the bottom of this page.
You can know how many arguments were passed to your function and you can check if your second argument is a function or not:
function getData (id, parameters, callback) {
if (arguments.length == 2) { // if only two arguments were supplied
if (Object.prototype.toString.call(parameters) == "[object Function]") {
callback = parameters;
}
}
//...
}
You can also use the arguments object in this way:
function getData (/*id, parameters, callback*/) {
var id = arguments[0], parameters, callback;
if (arguments.length == 2) { // only two arguments supplied
if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
callback = arguments[1]; // if is a function, set as 'callback'
} else {
parameters = arguments[1]; // if not a function, set as 'parameters'
}
} else if (arguments.length == 3) { // three arguments supplied
parameters = arguments[1];
callback = arguments[2];
}
//...
}
If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.
I faced same error but in a different way.
When you curl a page with a specific SSL protocol.
curl --sslv3 https://example.com
If --sslv3 is not supported by the target server then the error will be
curl: (35) TCP connection reset by peer
With the supported protocol, error will be gone.
curl --tlsv1.2 https://example.com
Find the total size of both array and set array1and2 to the total size of both array added. Then loop array1 and then array2 and add the values into array1and2.
All of the previous answers are great. If it is a simple, one line sql command you wish to run, you could also use the -e option.
mysql -h <host> -u<user> -p<password> database -e \
"SELECT * FROM blah WHERE foo='bar';"
You can simply use a '+' to convert the result to a number.
var x = 22.032423;
x = +x.toFixed(2); // x = 22.03
Please check this out below sample code for semaphore implementation(Lock and unlock).
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include<string.h>
#include<malloc.h>
#include <sys/sem.h>
int main()
{
int key,share_id,num;
char *data;
int semid;
struct sembuf sb={0,-1,0};
key=ftok(".",'a');
if(key == -1 ) {
printf("\n\n Initialization Falied of shared memory \n\n");
return 1;
}
share_id=shmget(key,1024,IPC_CREAT|0744);
if(share_id == -1 ) {
printf("\n\n Error captured while share memory allocation\n\n");
return 1;
}
data=(char *)shmat(share_id,(void *)0,0);
strcpy(data,"Testing string\n");
if(!fork()) { //Child Porcess
sb.sem_op=-1; //Lock
semop(share_id,(struct sembuf *)&sb,1);
strncat(data,"feeding form child\n",20);
sb.sem_op=1;//Unlock
semop(share_id,(struct sembuf *)&sb,1);
_Exit(0);
} else { //Parent Process
sb.sem_op=-1; //Lock
semop(share_id,(struct sembuf *)&sb,1);
strncat(data,"feeding form parent\n",20);
sb.sem_op=1;//Unlock
semop(share_id,(struct sembuf *)&sb,1);
}
return 0;
}
if I got your question correct...
main() method is defined in the class below...
public class ToBeCalledClass{
public static void main (String args[ ]) {
System.out.println("I am being called");
}
}
you want to call this main method in another class.
public class CallClass{
public void call(){
ToBeCalledClass.main(null);
}
}
FireFox does not allow to open a local file. But if you want to use this for testing a different image (which is what I just needed to do), you can simply save the whole page locally, and then insert the url(file:///somewhere/file.png) - which works for me.
Unfortunately, No. You will you have to go through a loop and count them.
EDIT :
var arrLength = arr.filter(Number);
alert(arrLength);
none of above worked for me , i updated the appCompat - v7 version in my app gradle file from 23 to 25.3.1. helped to make it work for me
In your code:
$parts = array_map('trim', explode(':', $line_of_text, 2));
You have ":" as separator. If you use another separator in file, then you will get an "Undefined offset: 1" but not "Undefined offset: 0" All information will be in $parts[0] but no information in $parts[1] or [2] etc. Try to echo $part[0]; echo $part[1];
you will see the information.
As defined in the MySQL Glossary:
In MySQL, physically, a schema is synonymous with a database. You can substitute the keyword
SCHEMA
instead ofDATABASE
in MySQL SQL syntax, for example usingCREATE SCHEMA
instead ofCREATE DATABASE
.Some other database products draw a distinction. For example, in the Oracle Database product, a schema represents only a part of a database: the tables and other objects owned by a single user.
You can copy value of Parent Class to a Child class. For instance, you could use reflection if that is the case.
Here is how to use this in your program:
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Arrays.sort(array);
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}
As Felipe Alsacreations has already said, the first option is fine.
If you want to ensure that nothing below the list is interpreted as belonging to the heading, that's exactly what the HTML5 sectioning content elements are for. So, for instance you could do
<h2>About Fruits</h2>
<section>
<h3>Fruits I Like:</h3>
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Oranges</li>
</ul>
</section>
<!-- anything here is part of the "About Fruits" section but does not
belong to the "Fruits I Like" section. -->
Try this code:
HTML:
<div id="demo"></div>
JavaScript code:
<script>
(function(){
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
})();
</script>
I had a similar problems, till I got it working. Below is the full listing of the integration:
ssh-keygen -t rsa
Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console:
Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything:
run this command to test if you can get access to Bitbucket account:
ssh -T [email protected]
git clone [email protected]:username/repo_name.git
Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:
Add an authentication token inside the job/project you configure, it can be anything:
In Bitbucket hooks: choose jenkins hooks, and fill the fields as below:
Where:
**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project
Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.
To perform Email Validation we have many ways,but simple & easiest way are two methods.
1- Using EditText(....).addTextChangedListener
which keeps triggering on every input in an EditText box
i.e email_id is invalid or valid
/**
* Email Validation ex:- [email protected]
*/
final EditText emailValidate = (EditText)findViewById(R.id.textMessage);
final TextView textView = (TextView)findViewById(R.id.text);
String email = emailValidate.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
emailValidate .addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (email.matches(emailPattern) && s.length() > 0)
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
// or
textView.setText("valid email");
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address",Toast.LENGTH_SHORT).show();
//or
textView.setText("invalid email");
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// other stuffs
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// other stuffs
}
});
2- Simplest method using if-else
condition. Take the EditText box string using getText() and compare with pattern provided for email. If pattern doesn't match or macthes, onClick of button toast a message. It ll not trigger on every input of an character in EditText box . simple example shown below.
final EditText emailValidate = (EditText)findViewById(R.id.textMessage);
final TextView textView = (TextView)findViewById(R.id.text);
String email = emailValidate.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
// onClick of button perform this simplest code.
if (email.matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
The fetchSize
parameter is a hint to the JDBC driver as to many rows to fetch in one go from the database. But the driver is free to ignore this and do what it sees fit. Some drivers, like the Oracle one, fetch rows in chunks, so you can read very large result sets without needing lots of memory. Other drivers just read in the whole result set in one go, and I'm guessing that's what your driver is doing.
You can try upgrading your driver to the SQL Server 2008 version (which might be better), or the open-source jTDS driver.
Size of an array in C:
int a[10];
size_t size_of_array = sizeof(a); // Size of array a
int n = sizeof (a) / sizeof (a[0]); // Number of elements in array a
size_t size_of_element = sizeof(a[0]); // Size of each element in array a
// Size of each element = size of type
Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.
DECLARE @t1 TABLE (
ColID int IDENTITY,
Col2 int
)
DECLARE @t2 TABLE (
ColID int IDENTITY,
Col2 int
)
INSERT INTO @t1 (Col2) VALUES (123)
INSERT INTO @t1 (Col2) VALUES (234)
INSERT INTO @t1 (Col2) VALUES (456)
INSERT INTO @t1 (Col2) VALUES (1)
INSERT INTO @t2 (Col2) VALUES (123)
INSERT INTO @t2 (Col2) VALUES (345)
INSERT INTO @t2 (Col2) VALUES (456)
INSERT INTO @t2 (Col2) VALUES (2)
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
t1Col2 t2Col2 MyDesiredResult
----------- ----------- ---------------
123 123 1
234 345 234 <- Not a zero
456 456 1
1 2 1 <- Not a match
"kill" will only kill one screen window. To "kill" the complete session, use quit
.
$ screen -X -S [session # you want to kill] quit
For dead sessions use: $ screen -wipe
Please use the below mentioned URL to encrypt string using AES excryption with
key and IV values.
I shall try the solution with jQuery, for sure it should give a nice result. Of course you have to load jQuery ... What about a pop-up with something like this? Of course this is dependant on the user authorizing pop-ups.
<html>
<head>
<script language="javascript">
var ret;
function returnfunction()
{
alert(ret);
}
</script>
</head>
<body>
<form>
<label id="QuestionToAsk" name="QuestionToAsk">Here is talked.</label><br />
<input type="button" value="Yes" name="yes" onClick="ret=true;returnfunction()" />
<input type="button" value="No" onClick="ret=false;returnfunction()" />
</form>
</body>
</html>
Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.
What you typically use them for is create variables for that object like this:
>>> class testing:
... def __init__(self, init_value):
... self.some_value = init_value
So what you could do then is to create an object from this class like this:
>>> testobject = testing(5)
The testobject will then have an object called some_value
that in this sample will be 5.
>>> testobject.some_value
5
But you don't need to set a value for each object like i did in my sample. You can also do like this:
>>> class testing:
... def __init__(self):
... self.some_value = 5
then the value of some_value will be 5 and you don't have to set it when you create the object.
>>> testobject = testing()
>>> testobject.some_value
5
the >>> and ... in my sample is not what you write. It's how it would look in pyshell...
size: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
Learn more: Typechecking With PropTypes
Never got exist to work.
I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.
Never got batch files to work above Windows XP
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):
re.search(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group() ## returns 'TeSt'
put it in double quotes
echo "\t";
See: http://php.net/language.types.string#language.types.string.syntax.double
This error had come when your keyboard input type is Number Pad.I got same error than I change my Textfield keyboard input type to Default fix my issue.
I just wanted to mention that one can get the detailed GC log with the
-XX:+PrintGCDetails
parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.
Also -Xloggc:gc.log
seems to generate the same output like -verbose:gc
but you can specify an output file in the first.
Example usage:
java -Xloggc:./memory.log -XX:+PrintGCDetails Memory
To visualize the data better you can try gcviewer (a more recent version can be found on github).
Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!
There is a better way that is safer and will not slow down your application. How Excel is set up, a cell can have either a value or a formula; the formula can not refer to its own cell. Otherwise, You end up with an infinite loop, since the new value would cause another calculation... .
Use a helper column to calculate the value based on what you put in the other cell.
For Example:
Column A is a True or False, Column B contains a monetary value, Column C contains the following formula:
=B1
Now, to calculate that column B will be highlighted yellow in a conditional format only if Column A is True and Column B is greater than Zero...
=AND(A1=True,C1>0)
You can then choose to hide column C
As said in the comments, the problem lies in your script. Actually, there are 2 problems:
None
somewhere. Maybe due to the defaultdict ?show()
after each subplot. show()
should be called once at the end of your script. The alternative is to use interactive mode, look for ion
in matplotlib's documentation.something like this:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
const long max_rand = 1000000L;
double x1 = 12.33, x2 = 34.123, x;
srandom(time(NULL));
x = x1 + ( x2 - x1) * (random() % max_rand) / max_rand;
cout << x1 << " <= " << x << " <= " << x2 << endl;
return 0;
}
The following is more Drupal-ish:
url(current_path(), array('absolute' => true));
If you want to know the scroll position of a view, then you can use the following extension function on View class:
fun View?.onScroll(callback: (x: Int, y: Int) -> Unit) {
var oldX = 0
var oldY = 0
this?.viewTreeObserver?.addOnScrollChangedListener {
if (oldX != scrollX || oldY != scrollY) {
callback(scrollX, scrollY)
oldX = scrollX
oldY = scrollY
}
}
}
For those who came here looking for a find and remove an object from an array:
Swift 1
if let index = find(itemList, item) {
itemList.removeAtIndex(index)
}
Swift 2
if let index = itemList.indexOf(item) {
itemList.removeAtIndex(index)
}
Swift 3, 4
if let index = itemList.index(of: item) {
itemList.remove(at: index)
}
Swift 5.2
if let index = itemList.firstIndex(of: item) {
itemList.remove(at: index)
}
Run cmd as administrator. Type iisreset
. That's it.
The problem here starts with how you're creating the string in the first place.
a = "d:\stuff\morestuff\furtherdown\THEFILE.txt"
Done this way, Python is trying to special case these: \s
, \m
, \f
, and \T
. In your case, \f
is being treated as a formfeed (0x0C) while the other backslashes are handled correctly. What you need to do is one of these:
b = "d:\\stuff\\morestuff\\furtherdown\\THEFILE.txt" # doubled backslashes
c = r"d:\stuff\morestuff\furtherdown\THEFILE.txt" # raw string, no doubling necessary
Then once you split either of these, you'll get the result you want.
A simple way is to use tail(-n) to remove the first n rows
df=df.tail(-3)
1- Stop other applications that are using port 80. 2- run application with port 80 :
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
From the Google Font Directory examples:
@font-face {
font-family: 'Tangerine';
font-style: normal;
font-weight: normal;
src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
font-family: 'Tangerine', serif;
font-size: 48px;
}
This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf
Here are some good sites:
Good primer:
Other Info:
In C++11 you can use std::to_string:
std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);
With
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
Has
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
WhereHas
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
This is implementation of methods after decompiling.
public static bool IsNullOrEmpty(String value)
{
return (value == null || value.Length == 0);
}
public static bool IsNullOrWhiteSpace(String value)
{
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
So it is obvious that IsNullOrWhiteSpace method also checks if value that is being passed contain white spaces.
Whitespaces refer : https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
also a slightly different version. i just did a appllication.sheets.count to know how many worksheets i have additionallyl. well and put a little rename in aswell
Sub insertworksheet()
Dim worksh As Integer
Dim worksheetexists As Boolean
worksh = Application.Sheets.Count
worksheetexists = False
For x = 1 To worksh
If Worksheets(x).Name = "ENTERWROKSHEETNAME" Then
worksheetexists = True
'Debug.Print worksheetexists
Exit For
End If
Next x
If worksheetexists = False Then
Debug.Print "transformed exists"
Worksheets.Add after:=Worksheets(Worksheets.Count)
ActiveSheet.Name = "ENTERNAMEUWANTTHENEWONE"
End If
End Sub
In addition to the Carlos Heuberger's reply: if a different than the default (80) is needed, the 7 param constructor should be used:
URI uri = new URI(
"http",
null, // this is for userInfo
"www.google.com",
8080, // port number as int
"/ig/api",
"weather=São Paulo",
null);
String request = uri.toASCIIString();
As others have pointed to CSS specification, percentages aren't supported on borders:
'border-top-width',
'border-right-width',
'border-bottom-width',
'border-left-width'
Value: <border-width> | inherit
Initial: medium
Applies to: all elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: absolute length; '0' if the border style is 'none' or 'hidden'
As you can see it says Percentages: N/A.
You can simulate your percentage borders with a wrapper element where you would:
background-color
to your desired border colourpadding
in percentages (because they're supported)background-color
to white (or whatever it needs to be)This would somehow simulate your percentage borders. Here's an example of an element with 25% width side borders that uses this technique.
HTML used in the example
.faux-borders {_x000D_
background-color: #f00;_x000D_
padding: 1px 25%; /* set padding to simulate border */_x000D_
}_x000D_
.content {_x000D_
background-color: #fff;_x000D_
}
_x000D_
<div class="faux-borders">_x000D_
<div class="content">_x000D_
This is the element to have percentage borders._x000D_
</div>_x000D_
</div>
_x000D_
Issue: You have to be aware that this will be much more complicated when your element has some complex background applied to it... Especially if that background is inherited from ancestor DOM hierarchy. But if your UI is simple enough, you can do it this way.
@BoltClock mentioned scripted solution where you can programmaticaly calculate border width according to element size.
This is such an example with extremely simple script using jQuery.
var el = $(".content");_x000D_
var w = el.width() / 4 | 0; // calculate & trim decimals_x000D_
el.css("border-width", "1px " + w + "px");
_x000D_
.content { border: 1px solid #f00; }
_x000D_
<div class="content">_x000D_
This is the element to have percentage borders._x000D_
</div>
_x000D_
But you have to be aware that you will have to adjust border width every time your container size changes (i.e. browser window resize). My first workaround with wrapper element seems much simpler because it will automatically adjust width in these situations.
The positive side of scripted solution is that it doesn't suffer from background problems mentioned in my previous non-scripted solution.
If you have password for your dB then
mysql -u <username> -p <DBName> < yourfile.sql
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
gives the following error: Error: object 'bar' not found
.
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
In this case bar
is accessible from outside the function.
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
remains accessible after the if-else
statement.
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
Here you have a small example:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
Before abc was introduced you would see this frequently.
class Base(object):
def go(self):
raise NotImplementedError("Please Implement this method")
class Specialized(Base):
def go(self):
print "Consider me implemented"
This is some of the things you can put into a message box. Enjoy
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)
More information can be found here
The registry entries for MSBuild key worked fine to me. It's important to remember that it must be done for 64-bit or 32-bit branches depending on which version of MSBuild you run. I wouldn't recommend to use environment variables as it may cause problems in different versions of MSBuild.
This registry file fixes that for both cases:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\10.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\11.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\12.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\14.0\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\10.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\11.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\12.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0\14.0]
"VCTargetsPath"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
"VCTargetsPath10"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath10)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\'))"
"VCTargetsPath11"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath11)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V110\\'))"
"VCTargetsPath12"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath12)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V120\\'))"
"VCTargetsPath14"="$([MSBuild]::ValueOrDefault('$(VCTargetsPath14)','$(MSBuildExtensionsPath32)\\Microsoft.Cpp\\v4.0\\V140\\'))"
I believe you need your support package in both Library and application. However, to fix this, make sure you have same file at both locations (same checksum).
Simply copy the support-package file from one location and copy at another then clean+refresh your library/project and you should be good to go.
For sending the output to another file (I'm leaving out error checking to focus on the important details):
if (fork() == 0)
{
// child
int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
dup2(fd, 2); // make stderr go to file - you may choose to not do this
// or perhaps send stderr to another file
close(fd); // fd no longer needed - the dup'ed handles are sufficient
exec(...);
}
For sending the output to a pipe so you can then read the output into a buffer:
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
For those who are still trying, this link helped me out, too; it just puts it all together:
http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx
private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);
//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;
//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}
Signing is producing a "hash" with your private key that can be verified with your public key. The text is sent in the clear.
Encrypting uses the receiver's public key to encrypt the data; decoding is done with their private key.
So, the use of keys is not reversed (otherwise your private key wouldn't be private anymore!).
This is my LDAP Java login test application supporting LDAP:// and LDAPS:// self-signed test certificate. Code is taken from few SO posts, simplified implementation and removed legacy sun.java.* imports.
Usage
I have run this in Windows7 and Linux machines against WinAD directory service. Application prints username and member groups.
$ java -cp classes test.LoginLDAP url=ldap://1.2.3.4:389 [email protected] password=mypwd
$ java -cp classes test.LoginLDAP url=ldaps://1.2.3.4:636 [email protected] password=mypwd
Test application supports temporary self-signed test certificates for ldaps:// protocol, this DummySSLFactory accepts any server cert so man-in-the-middle is possible. Real life installation should import server certificate to a local JKS keystore file and not using dummy factory.
Application uses enduser's username+password for initial context and ldap queries, it works for WinAD but don't know if can be used for all ldap server implementations. You could create context with internal username+pwd then run queries to see if given enduser is found.
LoginLDAP.java
package test;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
public class LoginLDAP {
public static void main(String[] args) throws Exception {
Map<String,String> params = createParams(args);
String url = params.get("url"); // ldap://1.2.3.4:389 or ldaps://1.2.3.4:636
String principalName = params.get("username"); // [email protected]
String domainName = params.get("domain"); // mydomain.com or empty
if (domainName==null || "".equals(domainName)) {
int delim = principalName.indexOf('@');
domainName = principalName.substring(delim+1);
}
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, url);
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS, params.get("password")); // secretpwd
if (url.toUpperCase().startsWith("LDAPS://")) {
props.put(Context.SECURITY_PROTOCOL, "ssl");
props.put(Context.SECURITY_AUTHENTICATION, "simple");
props.put("java.naming.ldap.factory.socket", "test.DummySSLSocketFactory");
}
InitialDirContext context = new InitialDirContext(props);
try {
SearchControls ctrls = new SearchControls();
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", ctrls);
if(!results.hasMore())
throw new AuthenticationException("Principal name not found");
SearchResult result = results.next();
System.out.println("distinguisedName: " + result.getNameInNamespace() ); // CN=Firstname Lastname,OU=Mycity,DC=mydomain,DC=com
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {
for(int idx=0; idx<memberOf.size(); idx++) {
System.out.println("memberOf: " + memberOf.get(idx).toString() ); // CN=Mygroup,CN=Users,DC=mydomain,DC=com
//Attribute att = context.getAttributes(memberOf.get(idx).toString(), new String[]{"CN"}).get("CN");
//System.out.println( att.get().toString() ); // CN part of groupname
}
}
} finally {
try { context.close(); } catch(Exception ex) { }
}
}
/**
* Create "DC=sub,DC=mydomain,DC=com" string
* @param domainName sub.mydomain.com
* @return
*/
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue;
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static Map<String,String> createParams(String[] args) {
Map<String,String> params = new HashMap<String,String>();
for(String str : args) {
int delim = str.indexOf('=');
if (delim>0) params.put(str.substring(0, delim).trim(), str.substring(delim+1).trim());
else if (delim==0) params.put("", str.substring(1).trim());
else params.put(str, null);
}
return params;
}
}
And SSL helper class.
package test;
import java.io.*;
import java.net.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.*;
import javax.net.ssl.*;
public class DummySSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory socketFactory;
public DummySSLSocketFactory() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{ new DummyTrustManager()}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
} catch ( Exception ex ){ throw new IllegalArgumentException(ex); }
}
public static SocketFactory getDefault() { return new DummySSLSocketFactory(); }
@Override public String[] getDefaultCipherSuites() { return socketFactory.getDefaultCipherSuites(); }
@Override public String[] getSupportedCipherSuites() { return socketFactory.getSupportedCipherSuites(); }
@Override public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException {
return socketFactory.createSocket(socket, string, i, bln);
}
@Override public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i);
}
@Override public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException, UnknownHostException {
return socketFactory.createSocket(string, i, ia, i1);
}
@Override public Socket createSocket(InetAddress ia, int i) throws IOException {
return socketFactory.createSocket(ia, i);
}
@Override public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
return socketFactory.createSocket(ia, i, ia1, i1);
}
}
class DummyTrustManager implements X509TrustManager {
@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {
// do nothing
}
@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {
/*System.out.println("checkServerTrusted for authType: " + str); // RSA
for(int idx=0; idx<xcs.length; idx++) {
X509Certificate cert = xcs[idx];
System.out.println("X500Principal: " + cert.getSubjectX500Principal().getName());
}*/
}
@Override public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
You don't need to specify PropertyConfigurator.configure("log4j.properties");
in your Log4J class, If you have already defined the log4j.properties in your project structure.
In case of Web Dynamic Project: -
You need to save your log4j.properties under WebContent -> WEB-INF -> log4j.properties
I hope this may help you.
It turns out that there is a float: left
property by default on all navbar-nav>li
elements, which is why they were all scrunching up to the left. Once I added the code below, it made the navbar
both centered and not scrunched up.
.navbar-nav>li {
float: none;
}
Hope this helps someone else who's looking to center a navbar
.
I followed these steps (for Mac).
In /etc/ssh/sshd_config
change
#ChallengeResponseAuthentication yes
#PasswordAuthentication yes
to
ChallengeResponseAuthentication no
PasswordAuthentication no
Now generate the RSA key:
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
(For me an RSA key worked. A DSA key did not work.)
A private key will be generated in ~/.ssh/id_rsa
along with ~/.ssh/id_rsa.pub
(public key).
Now move to the .ssh folder: cd ~/.ssh
Enter rm -rf authorized_keys
(sometimes multiple keys lead to an error).
Enter vi authorized_keys
Enter :wq
to save this empty file
Enter cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Restart the SSH:
sudo launchctl stop com.openssh.sshd
sudo launchctl start com.openssh.sshd
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
As Nora suggests, you can use the python simple server.
Navigate to the folder from which you want to serve your html page, then execute python -m SimpleHTTPServer
.
Now you can use your web-browser and navigate to http://localhost:8000/ where your page is being served.
If your page is named index.html then the server automatically loads that for you. If you want to access any other page, you'll need to browse to http://localhost:8000/{your page name}
Just clear your project and build again.
./gradlew app:clean app:assembleDebug
But it not works when targetSdkVersion or compileSdkVersion is 25.
import jquery within <script> tag in your vue file.
I think this is the easiest way.
For example,
<script>
import $ from "jquery";
export default {
name: 'welcome',
mounted: function() {
window.setTimeout(function() {
$('.logo').css('opacity', 0);
}, 1000);
}
}
</script>
I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL
values while using UNIQUE
?" Or "How to only allow one UNIQUE
NULL
value?"
The question has already been answered, yes you can have duplicate NULL
values while using the UNIQUE
index.
Since I stumbled upon this answer while searching for "how to allow one UNIQUE
NULL
value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...
In MySQL you can not have one UNIQUE
NULL
value, however you can have one UNIQUE
empty value by inserting with the value of an empty string.
Warning: Numeric and types other than string may default to 0 or another default value.
if(document.readyState === 'complete') {
DoStuffFunction();
} else {
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
The reason you function doesn't work when lol
is defined outside it, is because the DOM isn't loaded yet when the JavaScript is first run. Because of that, getElementById
will return null
(see MDN).
You've already found the most obvious solution: by calling getElementById
inside the function, the DOM will be loaded and ready by the time the function is called, and the element will be found like you expect it to.
There are a few other solutions. One is to wait until the entire document is loaded, like this:
<script type="text/javascript">
var lolz;
function onload() {
lolz = document.getElementById('lolz');
}
function kk(){
alert(lolz.value);
}
</script>
<body onload="onload();">
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" onclick="kk();"/>
</body>
Note the onload
attribute of the <body>
tag. (On a side note: the language
attribute of the <script>
tag is deprecated. Don't use it.)
There is, however, a problem with onload
: it waits until everything (including images, etc.) is loaded.
The other option is to wait until the DOM is ready (which is usually much earlier than onload
). This can be done with "plain" JavaScript, but it's much easier to use a DOM library like jQuery.
For example:
<script type="text/javascript">
$(document).ready(function() {
var lolz = $('#lolz');
var kk = $('#kk');
kk.click(function() {
alert(lolz.val());
});
});
</script>
<body>
<input type="text" name="enter" class="enter" value="" id="lolz"/>
<input type="button" value="click" id="kk" />
</body>
jQuery's .ready() takes a function as an argument. The function will be run as soon as the DOM is ready. This second example also uses .click() to bind kk's onclick
handler, instead of doing that inline in the HTML.
Use these commands
$('#rates').DataTable({
"scrollX": true,
"sScrollXInner": "100%",
});
ConcurrentLinkedQueue is lock-free, LinkedBlockingQueue is not. Every time you invoke LinkedBlockingQueue.put() or LinkedBlockingQueue.take(), you need acquire the lock first. In other word, LinkedBlockingQueue has poor concurrency. If you care performance, try ConcurrentLinkedQueue + LockSupport.
Alternatively to the suggested 3 methods you can try let
which carries out arithmetic operations on variables as follows:
let COUNT=$FIRSTV-$SECONDV
or
let COUNT=FIRSTV-SECONDV
Instant i = Instant.ofEpochSecond(cal.getTime);
Read more here and here
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
For specifying the interesting JSON result, you add "application/json" in your request header like below:
"Accept:application/json" is a desired response format.
"Content-Type:application/json" specifies the content format of your request, but sometimes you specify both application/json
and application/xml
, but the quality of these might be different. Which server will send back the different response formats, look at the example:
Accept:application/json;q=0.4,application/xml;q=8
This will return XML, because XML has higher quality.
Like this:
dataGridView1.Columns[0].Name = "column2";
dataGridView1.Columns[1].Name = "column6";
string[] row1 = new string[] { "column2 value", "column6 value" };
dataGridView1.Rows.Add(row1);
Or you need to set there values individually use the propery .Rows()
, like this:
dataGridView1.Rows[1].Cells[0].Value = "cell value";
//Get
var p = $("#elementId");
var offset = p.offset();
//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});
This is what I do when I need Initialized Global Constants:
1. Add a module called Globals
2. Add Properties like this into the Globals
module:
Property Get PSIStartRow() As Integer
PSIStartRow = Sheets("FOB Prices").Range("F1").Value
End Property
Property Get PSIStartCell() As String
PSIStartCell = "B" & PSIStartRow
End Property
User-specific settings should be written to HKCU\Software, machine-specific settings to HKLM\Software. Under these keys, structure [software vendor name]\[application name]
(e.g. HKLM\Software\Microsoft\Internet Explorer
) may be the most common, but that's just a convention, not a law of nature.
Many (most?) applications also add their uninstall entries to HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\[app name]
, but again, not all applications do this.
These are the most important keys; however, contents of the registry do not have to represent the installed software exactly - maybe the application was installed once, but then was manually deleted, or maybe the uninstaller didn't remove all traces of it. If you want to be sure, check the filesystem to see if the application still exists where its registry entries say it is.
Edit:
If you're a member of the group Administrators, you can check the HKEY_USERS
hive - each user's HKCU actually resides there (you'll need to know the user SID, or go through all of them).
Note: As @Brian Ensink says, "installed" is a bit of a vague concept - are we trying to find what the user could run? Some software doesn't even write to the Registry at all: search for "portable apps" to see apps that have been specifically modified to run directly from media (CD/USB) and not to leave any traces on the computer. We may also have to scan the disks, and network disks, and anything the user downloads, and world-accessible Windows shares in the Internet (yes, such things exist legitimately - \\live.sysinternals.com\tools
comes to mind). In this direction, there's no real limit of what the user can run, unless prevented by system policies.