For Antlr 4 the java code generation process is below:-
java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g
Update your jar name in classpath accordingly.
For rstudio, you can automatically set your working directory to the script directory using rstudioapi like that:
library(rstudioapi)
# Getting the path of your current open file
current_path = rstudioapi::getActiveDocumentContext()$path
setwd(dirname(current_path ))
print( getwd() )
This works when Running or Sourceing your file.
You need to install the package rstudioapi first. Notice I print the path to be 100% sure I'm at the right place, but this is optional.
HTML: Use names as
<input name="levels[level][]">
<input name="levels[build_time][]">
PHP:
$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
foreach ($array[$fieldKey] as $key=>$value) {
$newArray[$key][$fieldKey] = $value;
}
}
$newArray will hold data as you want
Array (
[0] => Array ( [level] => 1 [build_time] => 123 )
[1] => Array ( [level] => 2 [build_time] => 456 )
)
Have you tried plugin called " Youtube Live Stream Auto Embed"
Its seems to be working. Check it once.
If you want to remove the default value constraint, you can do:
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
It is General sibling combinator
and is explained in @Salaman's answer very well.
What I did miss is Adjacent sibling combinator
which is +
and is closely related to ~
.
example would be
.a + .b {
background-color: #ff0000;
}
<ul>
<li class="a">1st</li>
<li class="b">2nd</li>
<li>3rd</li>
<li class="b">4th</li>
<li class="a">5th</li>
</ul>
.b
.a
.a
in HTMLIn example above it will mark 2nd li
but not 4th.
.a + .b {_x000D_
background-color: #ff0000;_x000D_
}
_x000D_
<ul>_x000D_
<li class="a">1st</li>_x000D_
<li class="b">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="a">5th</li>_x000D_
</ul>
_x000D_
Another alternative solution, that is recommended in the github help pages:
pbcopy < ~/.ssh/id_rsa.pub
Should this fail, I recommend using their docs to trouble shoot or generate a new key - if not already done.
Another possible solution is that the project name is not acceptable. For example, creating a project with spaces in the name does not block the project creation but the proper sources are not marked and when those are marked manually, I still was unable to create classes. Recreating the project with hyphens (-) instead of spaces corrected the problem for me.
Try adding this code to your config. I had a similar issue once, and this workaround did the trick.
app.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
It sounds like the application isn't signed. Download ldid from Cydia and then use it like so: ldid -S /Applications/AccelerometerGraph.app/AccelerometerGraph
Also be sure that the binary is marked as executable: chmod +x /Applications/AccelerometerGraph.app/AccelerometerGraph
I solved the problem by simply connecting to a different network. That is one of the possible problems.
As discussed above, ECONNRESET means that the TCP conversation abruptly closed its end of the connection.
Your internet connection might be blocking you from connecting to some servers. In my case, I was trying to connect to mLab ( cloud database service that hosts MongoDB databases). And my ISP is blocking it.
There is no such thing as "SOAP protocol". SOAP is an XML schema.
It usually runs over HTTP (port 80), however.
This is common error, make sure that your file.war is built correctly. Just open .war file and check that your WebApplicationInitializer is there.
If you can use apache.commons.lang in your project, the easiest way would be just to use the method provided there:
public static boolean containsWhitespace(CharSequence seq)
Check whether the given CharSequence contains any whitespace characters.
Parameters:
seq - the CharSequence to check (may be null)
Returns:
true if the CharSequence is not empty and contains at least 1 whitespace character
It handles empty and null parameters and provides the functionality at a central place.
I have come up with a simpler solution.
Get the returned value of the page name from wp_title(). If empty, print homepage name, otherwise echo the wp_title() value.
<?php $title = wp_title('', false); ?>
Remember to remove the separation with the first argument and then set display to false to use as an input to the variable. Then just bung the code between your heading, etc. tags.
<?php if ( $title == "" ) : echo "Home"; else : echo $title; endif; ?>
It worked a treat for me and ensuring that the first is declared in the section where you wish to extract the $title
, this can be tuned to return different variables.
All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray
, and you need to retain the shape of array.
I have compare just two, but it will retain the shape of ndarray
. I have used the array with 1 million entries for comparison. Here I use square function. I am presenting the general case for n dimensional array. For two dimensional just make iter
for 2D.
import numpy, time
def A(e):
return e * e
def timeit():
y = numpy.arange(1000000)
now = time.time()
numpy.array([A(x) for x in y.reshape(-1)]).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.fromiter((A(x) for x in y.reshape(-1)), y.dtype).reshape(y.shape)
print(time.time() - now)
now = time.time()
numpy.square(y)
print(time.time() - now)
Output
>>> timeit()
1.162431240081787 # list comprehension and then building numpy array
1.0775556564331055 # from numpy.fromiter
0.002948284149169922 # using inbuilt function
here you can clearly see numpy.fromiter
user square function, use any of your choice. If you function is dependent on i, j
that is indices of array, iterate on size of array like for ind in range(arr.size)
, use numpy.unravel_index
to get i, j, ..
based on your 1D index and shape of array numpy.unravel_index
This answers is inspired by my answer on other question here
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
This is more of a rare issue but I have seen this if someone has copied the entire /var/lib/mysql directory as a way of migrating their DB to another server. The reason it doesn't work is because the database was running and using log files. It doesn't work sometimes if there are logs in /var/log/mysql. The solution is to copy the /var/log/mysql files as well.
Re: using icon in :before
–
recent Font Awesome builds include the .fa-icon()
mixin for SASS and LESS. This will automatically include the font-family
as well as some rendering tweaks (e.g. -webkit-font-smoothing
). Thus you can do, e.g.:
// Add "?" icon to header.
h1:before {
.fa-icon();
content: "\f059";
}
If you want to copy something from one directory into the current directory, do this:
cp dir1/* .
This assumes you're not trying to copy hidden files.
If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.
You would connect through PDO, like this:
try {
$db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
(Of course replace databasename, username and password above)
You can then query the database like this:
$result = $db->query("select * from tablename");
foreach ($result as $row) {
echo $row['foo'] . "\n";
}
Or, if you have variables:
$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();
If you need multiple connections open at once, you can simply create multiple instances of PDO:
try {
$db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
$db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
echo 'Connection failed: ' . $ex->getMessage();
}
For me rollbackFor was not enough, so I had to put this and it works as expected:
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
I hope it helps :-)
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
If you are dealing with images, use getimagesize. Unlike file_exists, this built-in function supports remote files. It will return an array that contains the image information (width, height, type..etc). All you have to do is to check the first element in the array (the width). use print_r to output the content of the array
$imageArray = getimagesize("http://www.example.com/image.jpg");
if($imageArray[0])
{
echo "it's an image and here is the image's info<br>";
print_r($imageArray);
}
else
{
echo "invalid image";
}
If you completely want to clear the session you can use this:
session_unset();
session_destroy();
Actually both are not neccessary but it does not hurt.
If you want to clear only a specific part I think you need this:
unset($_SESSION['Products']);
//or
$_SESSION['Products'] = "";
depending on what you need.
In my case I had to add the public key to my repo (at Bitbucket) AND use git clone once via ssh to answer yes to the "known host" question the first time.
None of the configuration above worked for me with a Spring application.
Implementing this code in the main application class (the one annotated with @SpringBootApplication) did the trick.
@Bean
EmbeddedServletContainerCustomizer containerCustomizer() throws Exception {
return (ConfigurableEmbeddedServletContainer container) -> {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;
tomcat.addConnectorCustomizers(
(connector) -> {
connector.setMaxPostSize(10000000);//10MB
}
);
}
};
}
You can change the accepted size in the statement:
connector.setMaxPostSize(10000000);//10MB
MacOS 10.15: Android Studio 3.5.1:
The solution that works for me was to use the Java Environment tool jenv
(installed via homebrew). This tool changes the $JAVA_HOME when one switches between java versions.
In my case I have multiple Java versions installed and the current global version in use was the default. I also found it necessary to comment out the $JAVA_HOME environment variable in my .bash_profile
when using this tool.
In Terminal, I entered jenv global 1.8
to get java 1.8 running instead of a later version (I have multiple versions installed).
After that:
flutter doctor --android-licenses
OR
sdkmanager --licenses
both work fine.
Note: You may need to exit and reopen your Terminal shell if you have to redefine the $JAVA_HOME environment variable.
If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.
The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
To clarify, using extern int x;
tells the compiler that an object of type int
called x
exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x
to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x
variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static
keyword.
#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
extern int global_x;
void print_global_x();
#endif
#include "header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;
int main()
{
//set global_x here:
global_x = 5;
print_global_x();
}
#include <iostream>
#include "header.h"
void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}
I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.
I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.
Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.
I generally do something like this:
public static class FakeHttpContext
{
public static void SetFakeContext(this Controller controller)
{
var httpContext = MakeFakeContext();
ControllerContext context =
new ControllerContext(
new RequestContext(httpContext,
new RouteData()), controller);
controller.ControllerContext = context;
}
private static HttpContextBase MakeFakeContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Setup(c=> c.Request).Returns(request.Object);
context.Setup(c=> c.Response).Returns(response.Object);
context.Setup(c=> c.Session).Returns(session.Object);
context.Setup(c=> c.Server).Returns(server.Object);
context.Setup(c=> c.User).Returns(user.Object);
user.Setup(c=> c.Identity).Returns(identity.Object);
identity.Setup(i => i.IsAuthenticated).Returns(true);
identity.Setup(i => i.Name).Returns("admin");
return context.Object;
}
}
And initiating the context like this
FakeHttpContext.SetFakeContext(moController);
And calling the Method in the controller straight forward
long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);
there is also http://ideone.com/ (supports many languages)
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
Without using a library you can use eval
- the only time you should use. It's safer to use a library though.
eg...
var response = '{"result":true , "count":1}';
var parsedJSON = eval('('+response+')');
var result=parsedJSON.result;
var count=parsedJSON.count;
alert('result:'+result+' count:'+count);
For a standard shell (without bashisms) using only builtins:
uppers=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lowers=abcdefghijklmnopqrstuvwxyz
lc(){ #usage: lc "SOME STRING" -> "some string"
i=0
while ([ $i -lt ${#1} ]) do
CUR=${1:$i:1}
case $uppers in
*$CUR*)CUR=${uppers%$CUR*};OUTPUT="${OUTPUT}${lowers:${#CUR}:1}";;
*)OUTPUT="${OUTPUT}$CUR";;
esac
i=$((i+1))
done
echo "${OUTPUT}"
}
And for upper case:
uc(){ #usage: uc "some string" -> "SOME STRING"
i=0
while ([ $i -lt ${#1} ]) do
CUR=${1:$i:1}
case $lowers in
*$CUR*)CUR=${lowers%$CUR*};OUTPUT="${OUTPUT}${uppers:${#CUR}:1}";;
*)OUTPUT="${OUTPUT}$CUR";;
esac
i=$((i+1))
done
echo "${OUTPUT}"
}
"Then" is a command in bash, thus it needs a ";" or a newline before it.
#!/bin/bash
echo "start\n"
for f in *.jpg
do
fname=$(basename "$f")
echo "fname is $fname\n"
fname="${filename%.*}"
echo "fname is $fname\n"
if [$[fname%2] -eq 1 ]
then
echo "removing $fname\n"
rm $f
fi
done
Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".
One can use this to pretty print a request, like so:
import requests
req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()
def pretty_print_POST(req):
"""
At this point it is completely built and ready
to be fired; it is "prepared".
However pay attention at the formatting used in
this function because it is programmed to be pretty
printed and may differ from the actual request.
"""
print('{}\n{}\r\n{}\r\n\r\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
pretty_print_POST(prepared)
which produces:
-----------START-----------
POST http://stackoverflow.com/
Content-Length: 7
X-Custom: Test
a=1&b=2
Then you can send the actual request with this:
s = requests.Session()
s.send(prepared)
These links are to the latest documentation available, so they might change in content: Advanced - Prepared requests and API - Lower level classes
Refer to the "undo" and "redo" part of Vim document.
:red[o] (Redo one change which was undone) and {count} Ctrl+r (Redo {count} changes which were undone) are both ok.
Also, the :earlier {count} (go to older text state {count} times) could always be a substitute for undo and redo.
If you already know the indices:
list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]
Note that we're adding +1 to the end to make the range inclusive...
Connection Count by ClientIP, with Total
We use this to view the number of connections by IPAddress with a total connection count. This was really helpful in debugging an issue... just get there before hit max connections!
For Mongo Shell:
db.currentOp(true).inprog.reduce((accumulator, connection) => { ipaddress = connection.client ? connection.client.split(":")[0] : "Internal"; accumulator[ipaddress] = (accumulator[ipaddress] || 0) + 1; accumulator["TOTAL_CONNECTION_COUNT"]++; return accumulator; }, { TOTAL_CONNECTION_COUNT: 0 })
Formatted:
db.currentOp(true).inprog.reduce(
(accumulator, connection) => {
ipaddress = connection.client ? connection.client.split(":")[0] : "Internal";
accumulator[ipaddress] = (accumulator[ipaddress] || 0) + 1;
accumulator["TOTAL_CONNECTION_COUNT"]++;
return accumulator;
},
{ TOTAL_CONNECTION_COUNT: 0 }
)
Example return:
{
"TOTAL_CONNECTION_COUNT" : 331,
"192.168.253.72" : 8,
"192.168.254.42" : 17,
"127.0.0.1" : 3,
"192.168.248.66" : 2,
"11.178.12.244" : 2,
"Internal" : 41,
"3.100.12.33" : 86,
"11.148.23.34" : 168,
"81.127.34.11" : 1,
"84.147.25.17" : 3
}
(the 192.x.x.x addresses at Atlas internal monitoring)
"Internal" are internal processes that don't have an external client. You can view a list of these with this:
db.currentOp(true).inprog.filter(connection => !connection.client).map(connection => connection.desc);
One of the best well-documented example I found.
http://www.fampennings.nl/maarten/android/09keyboard/index.htm
KeyboardView
related XML file and source code are provided.
cin.get()
seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).
Your __autoload
function will receive the full class-name, including the namespace name.
This means, in your case, the __autoload
function will receive 'Person\Barnes\David\Class1
', and not only 'Class1
'.
So, you have to modify your autoloading code, to deal with that kind of "more-complicated" name ; a solution often used is to organize your files using one level of directory per "level" of namespaces, and, when autoloading, replace '\
' in the namespace name by DIRECTORY_SEPARATOR
.
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
It depends on if you want the literal for a comparison, or for assignment.
If you want to make an existing set empty, you can use the .clear()
metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set()
or check if the length is 0.
example:
#create a new set
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}
#create an empty set
a=set()
#or, use the clear method
a.clear()
#comparison to a new blank set
if a==set():
#do something
#length-checking comparison
if len(a)==0:
#do something
You can use javascript dedicate string compare method string1.localeCompare(string2). it will five you -1 if the string not equals, 0 for strings equal and 1 if string1 is sorted after string2.
<script>
var to_check=$(this).val();
var cur_string=$("#0").text();
var to_chk = "that";
var cur_str= "that";
if(to_chk.localeCompare(cur_str) == 0){
alert("both are equal");
$("#0").attr("class","correct");
} else {
alert("both are not equal");
$("#0").attr("class","incorrect");
}
</script>
If the IE example doesn't work use this one. Anyway this should be faster than starting up an instance of IE.
Here is a complete solution based on
http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
Note, if your innerHTML is all numbers eg '12345', HTML formatting dosen't fully work in excel as it treats number differently? but add a character eg a trailing space at the end eg. 12345 + "& nbsp;" formats ok.
Sub test()
Cells(1, 1).Value = "<HTML>1<font color=blue>a</font>" & _
"23<font color=red>4</font></HTML>"
Dim rng As Range
Set rng = ActiveSheet.Cells(1, 1)
Worksheet_Change rng, ActiveSheet
End Sub
Private Sub Worksheet_Change(ByVal Target As Range, ByVal sht As Worksheet)
Dim objData As DataObject ' Set a reference to MS Forms 2.0
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
Target.Select
sht.PasteSpecial Format:="Unicode Text"
End If
Application.EnableEvents = True
End Sub
Is NDEBUG standard?
Yes it is a standard macro with the semantic "Not Debug" for C89, C99, C++98, C++2003, C++2011, C++2014 standards. There are no _DEBUG
macros in the standards.
C++2003 standard send the reader at "page 326" at "17.4.2.1 Headers" to standard C.
That NDEBUG is similar as This is the same as the Standard C library.
In C89 (C programmers called this standard as standard C) in "4.2 DIAGNOSTICS" section it was said
http://port70.net/~nsz/c/c89/c89-draft.html
If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as
#define assert(ignore) ((void)0)
If look at the meaning of _DEBUG
macros in Visual Studio
https://msdn.microsoft.com/en-us/library/b0084kay.aspx
then it will be seen, that this macro is automatically defined by your ?hoice of language runtime library version.
Updated for RC.5
With Angular 2 we can debounce using RxJS operator debounceTime()
on a form control's valueChanges
observable:
import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
@Component({
selector: 'my-app',
template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
firstNameControl = new FormControl();
formCtrlSub: Subscription;
resizeSub: Subscription;
ngOnInit() {
// debounce keystroke events
this.formCtrlSub = this.firstNameControl.valueChanges
.debounceTime(1000)
.subscribe(newValue => this.firstName = newValue);
// throttle resize events
this.resizeSub = Observable.fromEvent(window, 'resize')
.throttleTime(200)
.subscribe(e => {
console.log('resize event', e);
this.firstName += '*'; // change something to show it worked
});
}
ngDoCheck() { console.log('change detection'); }
ngOnDestroy() {
this.formCtrlSub.unsubscribe();
this.resizeSub .unsubscribe();
}
}
The code above also includes an example of how to throttle window resize events, as asked by @albanx in a comment below.
Although the above code is probably the Angular-way of doing it, it is not efficient. Every keystroke and every resize event, even though they are debounced and throttled, results in change detection running. In other words, debouncing and throttling do not affect how often change detection runs. (I found a GitHub comment by Tobias Bosch that confirms this.) You can see this when you run the plunker and you see how many times ngDoCheck()
is being called when you type into the input box or resize the window. (Use the blue "x" button to run the plunker in a separate window to see the resize events.)
A more efficient technique is to create RxJS Observables yourself from the events, outside of Angular's "zone". This way, change detection is not called each time an event fires. Then, in your subscribe callback methods, manually trigger change detection – i.e., you control when change detection is called:
import {Component, NgZone, ChangeDetectorRef, ApplicationRef,
ViewChild, ElementRef} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';
@Component({
selector: 'my-app',
template: `<input #input type=text [value]="firstName">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
keyupSub: Subscription;
resizeSub: Subscription;
@ViewChild('input') inputElRef: ElementRef;
constructor(private ngzone: NgZone, private cdref: ChangeDetectorRef,
private appref: ApplicationRef) {}
ngAfterViewInit() {
this.ngzone.runOutsideAngular( () => {
this.keyupSub = Observable.fromEvent(this.inputElRef.nativeElement, 'keyup')
.debounceTime(1000)
.subscribe(keyboardEvent => {
this.firstName = keyboardEvent.target.value;
this.cdref.detectChanges();
});
this.resizeSub = Observable.fromEvent(window, 'resize')
.throttleTime(200)
.subscribe(e => {
console.log('resize event', e);
this.firstName += '*'; // change something to show it worked
this.cdref.detectChanges();
});
});
}
ngDoCheck() { console.log('cd'); }
ngOnDestroy() {
this.keyupSub .unsubscribe();
this.resizeSub.unsubscribe();
}
}
I use ngAfterViewInit()
instead of ngOnInit()
to ensure that inputElRef
is defined.
detectChanges()
will run change detection on this component and its children. If you would rather run change detection from the root component (i.e., run a full change detection check) then use ApplicationRef.tick()
instead. (I put a call to ApplicationRef.tick()
in comments in the plunker.) Note that calling tick()
will cause ngDoCheck()
to be called.
server {
index index.html index.htm;
server_name test.example.com;
location / {
root /web/test.example.com/www;
}
location /static {
root /web/test.example.com;
}
}
Executive summary: Don't do that.
j_random_hacker's answer tells you how to do this. However, I would also like to point out that you should not do this. The whole point of templates is that they can accept any compatible type, and Java style type constraints break that.
Java's type constraints are a bug not a feature. They are there because Java does type erasure on generics, so Java can't figure out how to call methods based on the value of type parameters alone.
C++ on the other hand has no such restriction. Template parameter types can be any type compatible with the operations they are used with. There doesn't have to be a common base class. This is similar to Python's "Duck Typing," but done at compile time.
A simple example showing the power of templates:
// Sum a vector of some type.
// Example:
// int total = sum({1,2,3,4,5});
template <typename T>
T sum(const vector<T>& vec) {
T total = T();
for (const T& x : vec) {
total += x;
}
return total;
}
This sum function can sum a vector of any type that support the correct operations. It works with both primitives like int/long/float/double, and user defined numeric types that overload the += operator. Heck, you can even use this function to join strings, since they support +=.
No boxing/unboxing of primitives is necessary.
Note that it also constructs new instances of T using T(). This is trivial in C++ using implicit interfaces, but not really possible in Java with type constraints.
While C++ templates don't have explicit type constraints, they are still type safe, and will not compile with code that does not support the correct operations.
Hint: actively refused
sounds like somewhat deeper technical trouble, but...
...actually, this response (and also specifically errno:10061
) is also given, if one calls the bin/mongo executable and the mongodb service is simply not running on the target machine. This even applies to local machine instances (all happening on localhost).
? Always rule out for this trivial possibility first, i.e. simply by using the command line client to access your db.
I searched for hours, and I tried almost everything suggested.
This worked for almost every entity :
$input = "ažškunrukiš ? àéò ??? ©€ ?? ? ?? ? R?";
echo htmlentities($input, ENT_HTML5 , 'UTF-8');
result :
āžšķūņrūķīš ○ àéò ∀∂∋ ©€ ♣♦ ↠ ↔↛ ↙ ℜ℞rx;
If you declared different variables then use following simple method:
Int salary=2000;
String abc="I Love Pakistan";
Double pi=3.14;
Console.Writeline=salary+"/n"+abc+"/n"+pi;
Console.readkey();
Yes, the list of keyboard shortcuts for Android Studio is at https://developer.android.com/studio/intro/keyboard-shortcuts.html.
Here are a few that I know.
Check :File ->Settings ->Keymap -> <Choose Eclipse from Keymaps dropdown> or
Add unimplemented methods: CTRL + I
Override methods: CTRL + O
Format code: CTRL + ALT + L
Show project: ALT + 1
Show logcat: ALT + 6
Hide project - logcat: SHIFT + ESC
Build: CTRL + F9
Build and Run: CTRL + F10
Expand all: CTRL + SHIFT + NumPad +
Collapse all: CTRL + SHIFT + NumPad -
Find and replace: CTRL + R
Find: CTRL + F
In case I'm missing any shortcut that you need you can ask here and for more check implink!! or link!!:)
select case
when exists (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Tags' AND COLUMN_NAME = 'ModifiedByUser')
then 0
else 1
end
This will give you the desired result
#!/usr/bin/python
import os
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
print((len(path) - 1) * '---', os.path.basename(root))
for file in files:
print(len(path) * '---', file)
$ git remote add origin https://github.com/git/git.git
--- You will run this command to link your github project to origin. Here origin is user-defined.
You can rename it by $ git remote rename old-name new-name
$ git fetch origin
- Downloads objects and refs from remote repository to your local computer [origin/master]. That means it will not affect your local master branch unless you merge them using $ git merge origin/master
. Remember to checkout the correct branch where you need to merge before run this command
Note: Fetched content is represented as a remote branch. Fetch gives you a chance to review changes before integrating them into your copy of the project. To show changes between yours and remote $git diff master..origin/master
There are three types of variables:
The default values for instance and static variables are the same and depends on the type:
An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.
Once the array is created all of its elements are assiged with the default type value. For example:
private boolean[] list; // default value is null
private Boolean[] list; // default value is null
once is initialized:
private boolean[] list = new boolean[10]; // all ten elements are assigned to false
private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)
One of the important things to take into account is the "zoom" level of your projection (for Google Maps in particular).
As Google explains it:
At zoom level 1, the map consists of 4 256x256 pixels tiles, resulting in a pixel space from 512x512. At zoom level 19, each x and y pixel on the map can be referenced using a value between 0 and 256 * 2^19
( See https://developers.google.com/maps/documentation/javascript/maptypes?hl=en#MapCoordinates)
To factor in the "zoom" value, I recommend the simple and effective deltaLonPerDeltaX and deltaLatPerDeltaY functions below. While x-pixels and longitudes are strictly proportional, this is not the case for y-pixels and latitudes, for which the formula requires the initial latitude.
// Adapted from : http://blog.cppse.nl/x-y-to-lat-lon-for-google-maps
window.geo = {
glOffset: Math.pow(2,28), //268435456,
glRadius: Math.pow(2,28) / Math.PI,
a: Math.pow(2,28),
b: 85445659.4471,
c: 0.017453292519943,
d: 0.0000006705522537,
e: Math.E, //2.7182818284590452353602875,
p: Math.PI / 180,
lonToX: function(lon) {
return Math.round(this.glOffset + this.glRadius * lon * this.p);
},
XtoLon: function(x) {
return -180 + this.d * x;
},
latToY: function(lat) {
return Math.round(this.glOffset - this.glRadius *
Math.log((1 + Math.sin(lat * this.p)) /
(1 - Math.sin(lat * this.p))) / 2);
},
YtoLat: function(y) {
return Math.asin(Math.pow(this.e,(2*this.a/this.b - 2*y/this.b)) /
(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1) -
1/(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1)
) / this.c;
},
deltaLonPerDeltaX: function(deltaX, zoom) {
// 2^(7+zoom) pixels <---> 180 degrees
return deltaX * 180 / Math.pow(2, 7+zoom);
},
deltaLatPerDeltaY: function(deltaY, zoom, startLat) {
// more complex because of the curvature, we calculte it by difference
var startY = this.latToY(startLat),
endY = startY + deltaY * Math.pow(2, 28-7-zoom),
endLat = this.YtoLat(endY);
return ( endLat - startLat ); // = deltaLat
}
}
The second. The first is invalid.
A browser will handle it like so:
<p>tetxtextextete
<!-- Start of paragraph -->
<ol>
<!-- Start of ordered list. Paragraphs cannot contain lists. Insert </p> -->
<li>first element</li></ol>
<!-- A list item element. End of list -->
</p>
<!-- End of paragraph, but not inside paragraph, discard this tag to recover from the error -->
<p>other textetxet</p>
<!-- Another paragraph -->
"currently yes but i think it might cause problems at peak moments" I can confirm, that I had a problem where I got timeouts because of peak requests. After I set the max pool size, the application ran without any problems. IIS 7.5 / ASP.Net
You'll have to pass the new ordinal position to insert
using len
in this case:
In [62]:
a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]
Recently I import my project into Android studio, a part of R are marked in red with the error meesage "cannot resolve symbol R",but the compilation succeeds and the application runs.
Develop evirment:
Find the configuration file for Android studio
My path:
/Applications/Android Studio.app/Contents/bin/idea.properties
Change 2500:
idea.max.intellisense.filesize=2500
to 5000 or more:
idea.max.intellisense.filesize=5000
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
First off, see How Big can a Python Array Get? and Numpy, problem with long arrays
Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:
If you really want to create an array rather than a list use either
String[] names = ["lucas", "Fred", "Mary"]
or
def names = ["lucas", "Fred", "Mary"].toArray()
I tried the other solutions, but I didn't find that c.NotebookApp.notebook_dir
setting in the config...
#jupyter_notebook_config.json
{
"NotebookApp": {
"nbserver_extensions": {
"jupyter_nbextensions_configurator": true
}
}
}
So, what I do is:
cd
into the directory where I want the notebooks and checkpoints
savedjupyter-lab
# ipython cell
import os
# change where notebooks are stored
os.chdir('/Users/me/Project')
os.getcwd()
Actually windows way to use service, from the official documentation:
Find out where is your executable is installed, path may be like this:
"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe"
Create config file with such content (yaml format), path may be like this:
"C:\Program Files\MongoDB\Server\3.4\mongod.cfg"
systemLog:
destination: file
path: c:\data\log\mongod.log
storage:
dbPath: c:\data\db
C:\...\mongod.exe --config C:\...\mongod.cfg --install
Where paths is reduced with dots, see above.
The key --install
say to mongo to install itself as windows service.
Now you can start, stop, restart mongo server as usual windows service choose your favorite way from this:
Control Panel
-> Administration
-> Services
-> MongoDB
net start MongoDB
)Check log file specified in config file if any problems.
These all are ways:
String imageUri = "drawable://" + R.drawable.image;
Other ways I tested
Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");
String path = path.toString();
String path = otherPath .toString();
Create Proc[usp_mquestions]
(
@title nvarchar(500), --0
@tags nvarchar(max), --1
@category nvarchar(200), --2
@ispoll char(1), --3
@descriptions nvarchar(max), --4
)
AS
BEGIN TRY
BEGIN
DECLARE @message varchar(1000);
DECLARE @tempid bigint;
IF((SELECT count(id) from [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN
if @id=0
begin
select @tempid =id from [xyz] where id=@id;
if @tempid is null
BEGIN
INSERT INTO xyz
(entrydate,updatedate)
VALUES
(GETDATE(),GETDATE())
SET @tempid=@@IDENTITY;
END
END
ELSE
BEGIN
set @tempid=@id
END
if @tempid>0
BEGIN
-- Updation of table begin--
UPDATE tab_questions
set title=@title, --0
tags=@tags, --1
category=@category, --2
ispoll=@ispoll, --3
descriptions=@descriptions, --4
status=@status, --5
WHERE id=@tempid ; --9 ;
IF @id=0
BEGIN
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END
ELSE
BEGIN
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)
END
END
ELSE
BEGIN
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END
END
END
END TRY
BEGIN CATCH
SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;
Even though I think this answer is the best for Maven projects, It can be achieved via reflect as well (tested in Java 8):
public class TestClass {
private static final Map<String, String> DEFAULTS = new HashMap<>(System.getenv());
private static Map<String, String> envMap;
@Test
public void aTest() {
assertEquals("6", System.getenv("NUMBER_OF_PROCESSORS"));
System.getenv().put("NUMBER_OF_PROCESSORS", "155");
assertEquals("155", System.getenv("NUMBER_OF_PROCESSORS"));
}
@Test
public void anotherTest() {
assertEquals("6", System.getenv("NUMBER_OF_PROCESSORS"));
System.getenv().put("NUMBER_OF_PROCESSORS", "77");
assertEquals("77", System.getenv("NUMBER_OF_PROCESSORS"));
}
/*
* Restore default variables for each test
*/
@BeforeEach
public void initEnvMap() {
envMap.clear();
envMap.putAll(DEFAULTS);
}
@BeforeAll
public static void accessFields() throws Exception {
envMap = new HashMap<>();
Class<?> clazz = Class.forName("java.lang.ProcessEnvironment");
Field theCaseInsensitiveEnvironmentField = clazz.getDeclaredField("theCaseInsensitiveEnvironment");
Field theUnmodifiableEnvironmentField = clazz.getDeclaredField("theUnmodifiableEnvironment");
removeStaticFinalAndSetValue(theCaseInsensitiveEnvironmentField, envMap);
removeStaticFinalAndSetValue(theUnmodifiableEnvironmentField, envMap);
}
private static void removeStaticFinalAndSetValue(Field field, Object value) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, value);
}
}
I'm all for good names, and I often write about the importance of taking great care when choosing names for things. For this very same reason, I am wary of metaphors when naming things. In the original question, "factory" and "synchronizer" look like good names for what they seem to mean. However, "shepherd" and "nanny" are not, because they are based on metaphors. A class in your code can't be literally a nanny; you call it a nanny because it looks after some other things very much like a real-life nanny looks after babies or kids. That's OK in informal speech, but not OK (in my opinion) for naming classes in code that will have to be maintained by who knows whom who knows when.
Why? Because metaphors are culture dependent and often individual dependent as well. To you, naming a class "nanny" can be very clear, but maybe it's not that clear to somebody else. We shouldn't rely on that, unless you're writing code that is only for personal use.
In any case, convention can make or break a metaphor. The use of "factory" itself is based on a metaphor, but one that has been around for quite a while and is currently fairly well known in the programming world, so I would say it's safe to use. However, "nanny" and "shepherd" are unacceptable.
Normally yes, .gitignore
is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG
or something. In those cases you probably don't want to force that on anyone else.
EventArgs e
is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.
Object Sender
is a parameter called Sender that contains a reference to the control/object that raised the event.
Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
Example:
protected void btn_Click (object sender, EventArgs e){
Button btn = sender as Button;
btn.Text = "clicked!";
}
Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked
Step-1 Need to find user details by using below query
SQL> select username, account_status from dba_users where username='BOB';
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
BOB EXPIRED
Step-2 Get users password by using below query.
SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';
ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
Step -3 Run Above alter query
SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.
Step-4 :Check users account status
SQL> select username, account_status from dba_users where username='BOB';
USERNAME ACCOUNT_STATUS
------------------------------ --------------------------------
BOB OPEN
You should execute the command on every loop instead of building a huge command Text(btw,StringBuilder is made for this) The underlying Connection will not close and re-open for each loop, let the connection pool manager handle this. Have a look at this link for further informations: Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
If you want to ensure that every command is executed successfully you can use a Transaction and Rollback if needed,
For the relative path (i.e. the direct equivalent of Windows' %~dp0
):
MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"
For the absolute, normalized path:
MY_PATH="`dirname \"$0\"`" # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`" # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
# error; for some reason, the path is not accessible
# to the script (e.g. permissions re-evaled after suid)
exit 1 # fail
fi
echo "$MY_PATH"
Turns out I will missing a class called mysql-connector-java-5.1.2.jar, I added it this folder (C:\Program Files\pentaho\design-tools\data-integration\lib) and it worked with a MySQL connection and my data and tables appear.
I wasn't able to ever accomplish this but rather used view html source apps available on the Play Store to simply look for the element.
This issue can occur when there is a .git
directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.
<!DOCTYPE html>
<html>
<body>
<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>
</body>
</html>
I've been in a situation like you (JPA/Hibernate sequence for non @Id field) and I ended up creating a trigger in my db schema that add a unique sequence number on insert. I just never got it to work with JPA/Hibernate
I am surprised that no one mentioned NSTextStorageDelegate
. UITextViewDelegate
's methods will only be triggered by user interaction, but not programmatically. E.g. when you set a text view's text
property programmatically, you'll have to set the placeholder's visibility yourself, because the delegate methods will not be called.
However, with NSTextStorageDelegate
's textStorage(_:didProcessEditing:range:changeInLength:)
method, you'll be notified of any change to the text, even if it's done programmatically. Just assign it like this:
textView.textStorage.delegate = self
(In UITextView
, this delegate property is nil
by default, so it won't affect any default behaviour.)
Combine it with the UILabel
technique @clearlight demonstrates, one can easily wrap the whole UITextView
's placeholder
implementation into an extension.
extension UITextView {
private class PlaceholderLabel: UILabel { }
private var placeholderLabel: PlaceholderLabel {
if let label = subviews.compactMap( { $0 as? PlaceholderLabel }).first {
return label
} else {
let label = PlaceholderLabel(frame: .zero)
label.font = font
addSubview(label)
return label
}
}
@IBInspectable
var placeholder: String {
get {
return subviews.compactMap( { $0 as? PlaceholderLabel }).first?.text ?? ""
}
set {
let placeholderLabel = self.placeholderLabel
placeholderLabel.text = newValue
placeholderLabel.numberOfLines = 0
let width = frame.width - textContainer.lineFragmentPadding * 2
let size = placeholderLabel.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude))
placeholderLabel.frame.size.height = size.height
placeholderLabel.frame.size.width = width
placeholderLabel.frame.origin = CGPoint(x: textContainer.lineFragmentPadding, y: textContainerInset.top)
textStorage.delegate = self
}
}
}
extension UITextView: NSTextStorageDelegate {
public func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) {
if editedMask.contains(.editedCharacters) {
placeholderLabel.isHidden = !text.isEmpty
}
}
}
Note that the use of a private (nested) class called PlaceholderLabel
. It has no implementation at all, but it provides us a way to identify the placeholder label, which is far more 'swifty' than using the tag
property.
With this approach, you can still assign the delegate of the UITextView
to someone else.
You don't even have to change your text views' classes. Just add the extension(s) and you will be able to assign a placeholder string to every UITextView
in your project, even in the Interface Builder.
I left out the implementation of a placeholderColor
property for clarity reasons, but it can be implemented for just a few more lines with a similar computed variable to placeholder
.
# Open the file
f = open('morseCode.txt', 'r')
# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
if not Line.strip(): break
letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
letters.append((letter.lower(), code))
f.close()
# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ")
# Convert the codes to morse code
out = []
for c in i:
found = False
for letter, code in letters:
if letter == c.lower():
found = True
out.append(code)
break
if not found:
raise Exception('invalid character: %s' % c)
# Print the output
print ' '.join(out)
TCP (Transmission Control Protocol) is the most commonly used protocol on the Internet. The reason for this is because TCP offers error correction. When the TCP protocol is used there is a "guaranteed delivery." This is due largely in part to a method called "flow control." Flow control determines when data needs to be re-sent, and stops the flow of data until previous packets are successfully transferred. This works because if a packet of data is sent, a collision may occur. When this happens, the client re-requests the packet from the server until the whole packet is complete and is identical to its original.1) TCP is connection oriented and reliable where as UDP is connection less and unreliable.UDP (User Datagram Protocol) is anther commonly used protocol on the Internet. However, UDP is never used to send important data such as webpages, database information, etc; UDP is commonly used for streaming audio and video. Streaming media such as Windows Media audio files (.WMA) , Real Player (.RM), and others use UDP because it offers speed! The reason UDP is faster than TCP is because there is no form of flow control or error correction. The data sent over the Internet is affected by collisions, and errors will be present. Remember that UDP is only concerned with speed. This is the main reason why streaming media is not high quality.
2) TCP needs more processing at network interface level where as in UDP it’s not.
3) TCP uses, 3 way handshake, congestion control, flow control and other mechanism to make sure the reliable transmission.
4) UDP is mostly used in cases where the packet delay is more serious than packet loss.
Josh Lee's answer works, but you can use the "&&" operator for better readability like this:
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
According to ISO 8601:1988 that is used in Sweden the first week of the year is the first week that has at least four days within the new year.
So if your week starts on a Monday the first Thursday any year is within the first week. You can DateAdd or DateDiff from that.
Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$
. In words: "part 1 or part2 or both"
This is how I do it:
using System.IO;
using System.Security.Cryptography;
public string checkMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return Encoding.Default.GetString(md5.ComputeHash(stream));
}
}
}
Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.
Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):
if (matchMedia('handheld').matches) {
//...
} else {
//...
}
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
Mount the certs onto the Docker container using -v
:
docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"
I'm sorry to say, I don't have a precise answer for you. But I did encounter this problem as well, and, at least in my case, found a way around it. So maybe it'll offer some clues to someone else who knows more about Php under the hood.
The scenario is, I have an array passed to a function. The content of this array is being used to produce an HTML string to be sent back to the browser, by placing it all inside a global variable that's later printed. (This function isn't actually returning anything. Sloppy, I know, but that's beside the point.) Inside this array, among other things, are a couple of elements carrying, by reference, nested associative arrays that were defined outside of this function. By process-of-elimination, I found that manipulation of any element inside this array within this function, referenced or not, including an attempt to unset those referenced elements, results in Chrome throwing a net::ERR_INCOMPLETE_CHUNKED_ENCODING error and displaying no content. This is despite the fact that the HTML string in the global variable is exactly what it should be.
Only by re-tooling the script to not apply references to the array elements in the first place did things start working normally again. I suspect this is actually a Php bug having something to do with the presence of the referenced elements throwing off the content-length headers, but I really don't know enough about this to say for sure.
alnafie has a great answer for this question. I wanted to give an example of his code for reference:
var childNumber = 3;_x000D_
_x000D_
function addChild() {_x000D_
var parent = document.getElementById('i-want-more-children');_x000D_
var newChild = '<p>Child ' + childNumber + '</p>';_x000D_
parent.insertAdjacentHTML('beforeend', newChild);_x000D_
childNumber++;_x000D_
}
_x000D_
body {_x000D_
text-align: center;_x000D_
}_x000D_
button {_x000D_
background: rgba(7, 99, 53, .1);_x000D_
border: 3px solid rgba(7, 99, 53, 1);_x000D_
border-radius: 5px;_x000D_
color: rgba(7, 99, 53, 1);_x000D_
cursor: pointer;_x000D_
line-height: 40px;_x000D_
font-size: 30px;_x000D_
outline: none;_x000D_
padding: 0 20px;_x000D_
transition: all .3s;_x000D_
}_x000D_
button:hover {_x000D_
background: rgba(7, 99, 53, 1);_x000D_
color: rgba(255,255,255,1);_x000D_
}_x000D_
p {_x000D_
font-size: 20px;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<button type="button" onclick="addChild()">Append Child</button>_x000D_
<div id="i-want-more-children">_x000D_
<p>Child 1</p>_x000D_
<p>Child 2</p>_x000D_
</div>
_x000D_
Hopefully this is helpful to others.
The backslash \
is reserved for use as an escape character in Javascript.
To use a backslash literally you need to use two backslashes
\\
I think this link is pretty good.
Sample output from that link:
mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
-> FROM book_mast
-> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001 | 2 | 264.33 |
| CA002 | 1 | 433.33 |
| CA003 | 2 | 256.67 |
| CA004 | 3 | 246.67 |
| CA005 | 3 | 245.75 |
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)
You can register two event listeners for click event like this
document.getElementById("some-area")
.addEventListener("click", function(e){
alert("You clicked on the area!");
e.stopPropagation();// this will stop propagation of this event to upper level
}
);
document.body.addEventListener("click",
function(e) {
alert("You clicked outside the area!");
}
);
Iggy's answer was the easiest for me to follow, but I got the following error when doing a subsequent subplot
command that was not there when I was just doing show
:
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
In order to avoid this error, it helps to close (or clear) the plot after the user hits enter.
Here's the code that worked for me:
def plt_show():
'''Text-blocking version of plt.show()
Use this instead of plt.show()'''
plt.draw()
plt.pause(0.001)
input("Press enter to continue...")
plt.close()
Added shortcut Ctrl+Shift+X C to Keybindings (Window -> Preferences -> filter for Keys) when 'Editing Java Source' for 'Remove Active Session'.
Using .on()
you can define your function once, and it will execute for any dynamically added elements.
for example
$('#staticDiv').on('click', 'yourSelector', function() {
//do something
});
This is another great change from Google ... The suggested modification: replace onAttach(Activity activity)
with onAttach(Context context)
crashed my apps on older APIs since onAttach(Context context)
will not be called on native fragments.
I am using the native fragments (android.app.Fragment) so I had to do the following to make it work again on older APIs (< 23).
Here is what I did:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Code here
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Code here
}
}
Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:
import datetime
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())
today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))
schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)
The output:
Timestamp: 2014-10-18 21:31:12
Timestamp: 2014-Oct-18 21:31:12
Date now: 2014-10-18 21:31:12.318340
Date today: 2014-10-18
Today's date is Oct, 18 2014
Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific
Maintenance: October, 18 2014 - 1 PM to 6 PM Central
Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);
Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.
As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.
long unixTime = System.currentTimeMillis() / 1000L;
Yes.
$array[] = new stdClass;
$array[] = new stdClass;
print_r($array);
Results in:
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
)
)
Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.
<object data="html/stuff_to_include.html">
Your browser doesn’t support the object tag.
</object>
more info at http://www.w3schools.com/tags/tag_object.asp
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
It's fastest way:
public static unsafe void ToUpperFirst(this string str)
{
if (str == null) return;
fixed (char* ptr = str)
*ptr = char.ToUpper(*ptr);
}
Without changing original string:
public static unsafe string ToUpperFirst(this string str)
{
if (str == null) return null;
string ret = string.Copy(str);
fixed (char* ptr = ret)
*ptr = char.ToUpper(*ptr);
return ret;
}
You could run the Dotnet CLI with full diagnostic verbosity to help find the issue.
dotnet run --verbosity diagnostic >> full_build.log
Once the build is complete you can search through the log file (full_build.log) for the error. Searching for "a conflict" for example, should take you right to the problem.
I had some issues that this didn't address in getting this environment set up on OSX. It had to do with the solution that I was maintaining having additional dependencies on some of the Google APIs. It wasn't enough to just download and install the items listed in the first response.
You have to download these.
The other answers here are correct - use reverse DNS lookups. If you want to do it via a scripting language (Python, Perl) you could use the gethostbyaddr API.
string number = "123.456789"; // Convert to string
int length = number.Substring(number.IndexOf(".") + 1).Length; // 6
Delete the .git
directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).
If you want to delete everything (git-data, code, etc), just delete the whole directory.
.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.
just delete the app and try again, it happens to me when i try to launch over a device that has the same app but generated by an ipa file.
Rephrasing one of the answers in this post, instead of using cmd.split(). Try to use:
import shlex
args = shlex.split(cmd)
Then feed args to subprocess.Popen.
Check this doc for more info: https://docs.python.org/2/library/subprocess.html#popen-constructor
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
final
means that the value cannot be changed after initialization, that's what makes it a constant. static
means that instead of having space allocated for the field in each object, only one instance is created for the class.
So, static final
means only one instance of the variable no matter how many objects are created and the value of that variable can never change.
Unfortunately, ggplot2 does not offer a way to do this (easily) without transforming your data into long format. You can try to fight it but it will just be easier to do the data transformation. Here all the methods, including melt
from reshape2, gather
from tidyr, and pivot_longer
from tidyr: Reshaping data.frame from wide to long format
Here's a simple example using pivot_longer
:
> df <- data.frame(time = 1:5, a = 1:5, b = 3:7)
> df
time a b
1 1 1 3
2 2 2 4
3 3 3 5
4 4 4 6
5 5 5 7
> df_wide <- df %>% pivot_longer(c(a, b), names_to = "colname", values_to = "val")
> df_wide
# A tibble: 10 x 3
time colname val
<int> <chr> <int>
1 1 a 1
2 1 b 3
3 2 a 2
4 2 b 4
5 3 a 3
6 3 b 5
7 4 a 4
8 4 b 6
9 5 a 5
10 5 b 7
As you can see, pivot_longer
puts the selected column names in whatever is specified by names_to
(default "name"), and puts the long values into whatever is specified by values_to
(default "value"). If I'm ok with the default names, I can use use df %>% pivot_longer(c("a", "b"))
.
Now you can plot as normal, ex.
ggplot(df_wide, aes(x = time, y = val, color = colname)) + geom_line()
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;
List<Address> addList=new ArrayList<Address>();
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
return addList;
}
public void setAddList(List<Address> addList) {
this.addList = addList;
}
}
We have two entities Employee and Address with One to Many relationship.
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="address")
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private int address_id;
private String address;
Employee employee;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
return address_id;
}
public void setAddress_id(int address_id) {
this.address_id = address_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
By this way we can implement inner join between two tables
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
saveEmployee();
retrieveEmployee();
}
private static void saveEmployee() {
Employee employee=new Employee();
Employee employee1=new Employee();
Employee employee2=new Employee();
Employee employee3=new Employee();
Address address=new Address();
Address address1=new Address();
Address address2=new Address();
Address address3=new Address();
address.setAddress("1485,Sector 42 b");
address1.setAddress("1485,Sector 42 c");
address2.setAddress("1485,Sector 42 d");
address3.setAddress("1485,Sector 42 a");
employee.setEmpName("Varun");
employee1.setEmpName("Krishan");
employee2.setEmpName("Aasif");
employee3.setEmpName("Dut");
address.setEmployee(employee);
address1.setEmployee(employee1);
address2.setEmployee(employee2);
address3.setEmployee(employee3);
employee.getAddList().add(address);
employee1.getAddList().add(address1);
employee2.getAddList().add(address2);
employee3.getAddList().add(address3);
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(employee);
session.save(employee1);
session.save(employee2);
session.save(employee3);
session.getTransaction().commit();
session.close();
}
private static void retrieveEmployee() {
try{
String sqlQuery="select e from Employee e inner join e.addList";
Session session=HibernateUtil.getSessionFactory().openSession();
Query query=session.createQuery(sqlQuery);
List<Employee> list=query.list();
list.stream().forEach((p)->{System.out.println(p.getEmpName());});
session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Address.class);
configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty(" hibernate.connection.pool_size", "10");
// configuration
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Similar to Ray's answer above, Hive View 2.0 in Hortonworks Data Platform also allows you to run a Hive query and then save the output as csv.
Given that IPV6 has a size of 1500, I would assert that carriers would not provide separate paths for IPV4 and IPV6 (they are both IP with different types), forcing them to equipment for ipv4 that would be old, redundant, more costly to maintain and less reliable. It wouldn't make any sense. Besides, doing so might easily be considered providing preferential treatment for some traffic -- a no no under rules they probably don't care much about (unless they get caught).
So 1472 should be safe for external use (though that doesn't mean an app like DNS that doesn't know about EDNS will accept it), and if you are talking internal nets, you can more likely know your network layout in which case jumbo packet sizes apply for for non-fragmented packets so for 4096 - 4068 bytes, and for intel's cards with 9014 byte buffers, a package size of ... wait...8086 bytes, would be the max...coincidence? snicker
****UPDATE****
Various answers give maximum values allowed by 1 SW vendor or various answers assuming encapsulation. The user didn't ask for the lowest value possible (like "0" for a safe UDP size), but the largest safe packet size.
Encapsulation values for various layers can be included multiple times. Since once you've encapsulated a stream -- there is nothing prohibiting, say, a VPN layer below that and a complete duplication of encapsulation layers above that.
Since the question was about maximum safe values, I'm assuming that they are talking about the maximum safe value for a UDP packet that can be received. Since no UDP packet is guaranteed, if you receive a UDP packet, the largest safe size would be 1 packet over IPv4 or 1472 bytes.
Note -- if you are using IPv6, the maximum size would be 1452 bytes, as IPv6's header size is 40 bytes vs. IPv4's 20 byte size (and either way, one must still allow 8 bytes for the UDP header).
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
You can add the following lines to Preferences / Key Bindings - User:
{ "keys": ["control+keypad_divide"],"command": "toggle_comment", "args": {"block": false} },
{ "keys": ["shift+control+keypad_divide"],"command": "toggle_comment", "args": {"block": true}}
This is how I sorted the problem out - replacing "ctrl" with "control" and "/" with "keypad_divide".
My take on this issue also includes a concern with the body width, as the page seems to dance a little when we hide the scroll bar with overflow = "hidden"
.
The following code works perfectly for me, and is based on an Angular approach.
element.bind('mouseenter', function() {
var w = document.body.offsetWidth;
document.body.style.overflow = 'hidden';
document.body.style.width = w + 'px';
});
element.bind('mouseleave', function() {
document.body.style.overflow = 'initial';
document.body.style.width = 'auto';
});
You can order by a selected column or other expressions.
Here an example, how to order by the result of a case-statement:
SELECT col1
, col2
FROM tbl_Bill
WHERE col1 = 0
ORDER BY -- order by case-statement
CASE WHEN tbl_Bill.IsGen = 0 THEN 0
WHEN tbl_Bill.IsGen = 1 THEN 1
ELSE 2 END
The result will be a List starting with "IsGen = 0" rows, followed by "IsGen = 1" rows and all other rows a the end.
You could add more order-parameters at the end:
SELECT col1
, col2
FROM tbl_Bill
WHERE col1 = 0
ORDER BY -- order by case-statement
CASE WHEN tbl_Bill.IsGen = 0 THEN 0
WHEN tbl_Bill.IsGen = 1 THEN 1
ELSE 2 END,
col1,
col2
You have to use the date part fetching method:
SELECT * FROM testbed WHERE start_date ::date >= to_date('2012-09-08' ,'YYYY-MM-DD') and date::date <= to_date('2012-10-09' ,'YYYY-MM-DD')
Use FOR XML PATH('')
- which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result
SELECT STUFF((SELECT ',' + INSTITUTIONNAME
FROM EDUCATION EE
WHERE EE.STUDENTNUMBER=E.STUDENTNUMBER
ORDER BY sortOrder
FOR XML PATH('')), 1, 1, '') AS listStr
FROM EDUCATION E
GROUP BY E.STUDENTNUMBER
Here is the FIDDLE
Edit: Advise: This answer is old and a better solution can be found in this same page. This answer referred to MySQL Workbench 6.3 and is outdated. If you are using a new version (8.0 as today) look for @VSingh comment in this very page.
Original answer:
Just a copy of Gaston's answer, but with Monokai theme colors.
<!--
dark-gray: #282828;
brown-gray: #49483E;
gray: #888888;
light-gray: #CCCCCC;
ghost-white: #F8F8F0;
light-ghost-white: #F8F8F2;
yellow: #E6DB74;
blue: #66D9EF;
pink: #F92672;
purple: #AE81FF;
brown: #75715E;
orange: #FD971F;
light-orange: #FFD569;
green: #A6E22E;
sea-green: #529B2F;
-->
<style id="32" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- STYLE_DEFAULT !BACKGROUND! -->
<style id="33" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- STYLE_LINENUMBER -->
<style id= "0" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DEFAULT -->
<style id= "1" fore-color="#999999" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id= "2" fore-color="#999999" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id= "3" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id= "4" fore-color="#66D9EF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id= "5" fore-color="#66D9EF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id= "6" fore-color="#AE81FF" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id= "7" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id= "8" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id= "9" fore-color="#9B859D" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="10" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="11" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="12" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="13" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="14" fore-color="#F92672" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="15" fore-color="#9B859D" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="16" fore-color="#DDDDDD" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="17" fore-color="#E6DB74" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="18" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="19" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="20" fore-color="#529B2F" back-color="#282828" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="21" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="22" fore-color="#909090" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color="#999999" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENT -->
<style id="66" fore-color="#999999" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_COMMENTLINE -->
<style id="67" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_VARIABLE -->
<style id="68" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_SYSTEMVARIABLE -->
<style id="69" fore-color="#66D9EF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE -->
<style id="70" fore-color="#AE81FF" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_NUMBER -->
<style id="71" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_MAJORKEYWORD -->
<style id="72" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_KEYWORD -->
<style id="73" fore-color="#9B859D" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_DATABASEOBJECT -->
<style id="74" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_PROCEDUREKEYWORD -->
<style id="75" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_STRING -->
<style id="76" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_SQSTRING -->
<style id="77" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_DQSTRING -->
<style id="78" fore-color="#F92672" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_OPERATOR -->
<style id="79" fore-color="#9B859D" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_FUNCTION -->
<style id="80" fore-color="#DDDDDD" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_IDENTIFIER -->
<style id="81" fore-color="#E6DB74" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_QUOTEDIDENTIFIER -->
<style id="82" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER1 -->
<style id="83" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER2 -->
<style id="84" fore-color="#529B2F" back-color="#49483E" bold="No" /> <!-- SCE_MYSQL_USER3 -->
<style id="85" fore-color="#66D9EF" back-color="#888888" bold="No" /> <!-- SCE_MYSQL_HIDDENCOMMAND -->
<style id="86" fore-color="#AAAAAA" back-color="#888888" bold="No" /> <!-- SCE_MYSQL_PLACEHOLDER -->
Here is my answer using the group by clause.
SELECT *
FROM feeds f
LEFT JOIN
(
SELECT artist_id, feed_id
FROM feeds_artists
GROUP BY artist_id, feed_id
) fa ON fa.feed_id = f.id
LEFT JOIN artists a ON a.artist_id = fa.artist_id
select * from my_table where my_field Like '[a-z][a-z]%'
You can use any selector with not
p:not(:first-child){}
p:not(:first-of-type){}
p:not(:checked){}
p:not(:last-child){}
p:not(:last-of-type){}
p:not(:first-of-type){}
p:not(:nth-last-of-type(2)){}
p:not(nth-last-child(2)){}
p:not(:nth-child(2)){}
Solution that will work for multiple scopes and multiple variables within those scopes
This service was based off of Anton's answer, but is more extensible and will work across multiple scopes and allows the selection of multiple scope variables in the same scope. It uses the route path to index each scope, and then the scope variable names to index one level deeper.
Create service with this code:
angular.module('restoreScope', []).factory('restoreScope', ['$rootScope', '$route', function ($rootScope, $route) {
var getOrRegisterScopeVariable = function (scope, name, defaultValue, storedScope) {
if (storedScope[name] == null) {
storedScope[name] = defaultValue;
}
scope[name] = storedScope[name];
}
var service = {
GetOrRegisterScopeVariables: function (names, defaultValues) {
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
if (storedBaseScope == null) {
storedBaseScope = {};
}
// stored scope is indexed by route name
var storedScope = storedBaseScope[$route.current.$$route.originalPath];
if (storedScope == null) {
storedScope = {};
}
if (typeof names === "string") {
getOrRegisterScopeVariable(scope, names, defaultValues, storedScope);
} else if (Array.isArray(names)) {
angular.forEach(names, function (name, i) {
getOrRegisterScopeVariable(scope, name, defaultValues[i], storedScope);
});
} else {
console.error("First argument to GetOrRegisterScopeVariables is not a string or array");
}
// save stored scope back off
storedBaseScope[$route.current.$$route.originalPath] = storedScope;
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
},
SaveState: function () {
// get current scope
var scope = $route.current.locals.$scope;
var storedBaseScope = angular.fromJson(sessionStorage.restoreScope);
// save off scope based on registered indexes
angular.forEach(storedBaseScope[$route.current.$$route.originalPath], function (item, i) {
storedBaseScope[$route.current.$$route.originalPath][i] = scope[i];
});
sessionStorage.restoreScope = angular.toJson(storedBaseScope);
}
}
$rootScope.$on("savestate", service.SaveState);
return service;
}]);
Add this code to your run function in your app module:
$rootScope.$on('$locationChangeStart', function (event, next, current) {
$rootScope.$broadcast('savestate');
});
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
Inject the restoreScope service into your controller (example below):
function My1Ctrl($scope, restoreScope) {
restoreScope.GetOrRegisterScopeVariables([
// scope variable name(s)
'user',
'anotherUser'
],[
// default value(s)
{ name: 'user name', email: '[email protected]' },
{ name: 'another user name', email: '[email protected]' }
]);
}
The above example will initialize $scope.user to the stored value, otherwise will default to the provided value and save that off. If the page is closed, refreshed, or the route is changed, the current values of all registered scope variables will be saved off, and will be restored the next time the route/page is visited.
I am assuming this is a custom font. For any custom font this is what you do.
First download and add your font files to your project in Xcode (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).
In your Info.plist file add the key “Fonts provided by application” with type “Array”.
For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. HelveticaNeue-UltraLight.ttf). Save your “Info.plist” file.
label.font = UIFont (name: "HelveticaNeue-UltraLight", size: 30)
Try this :
Set the width of the form as 20% by:
width : 20%;
now if the entire canvas is 100 %, the centre is at 50%. So to align the centre of the form at the centre, 50-(20/2) = 40.
therefore set your left margin as 40% by doing this :
left : 40%;
As per PEP-20 by Tim Peters, "Explicit is better than implicit" and "Readability counts". If all you need from the os
module is under os.path
, import os.path
would be more explicit and let others know what you really care about.
Likewise, PEP-20 also says "Simple is better than complex", so if you also need stuff that resides under the more-general os
umbrella, import os
would be preferred.
$request->offsetSet(key, value);
Check that there isn't a firewall that is ending the connection after certain period of time (this was the cause of a similar problem we had)
protected void Page_Load(object sender, EventArgs e)
{
DropDownTitle();
}
protected void DropDownTitle()
{
if (!Page.IsPostBack)
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Normally you can use None
, but you can also use objc.NULL
, e.g.
import objc
val = objc.NULL
Especially useful when working with C code in Python.
Also see: Python objc.NULL Examples
[HttpPost]
public JsonResult PostImage(HttpPostedFileBase file)
{
try
{
if (file != null && file.ContentLength > 0 && file.ContentLength<=10485760)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/") + "HisloImages" + "\\", fileName);
file.SaveAs(path);
#region MyRegion
////save imag in Db
//using (MemoryStream ms = new MemoryStream())
//{
// file.InputStream.CopyTo(ms);
// byte[] array = ms.GetBuffer();
//}
#endregion
return Json(JsonResponseFactory.SuccessResponse("Status:0 ,Message: OK"), JsonRequestBehavior.AllowGet);
}
else
{
return Json(JsonResponseFactory.ErrorResponse("Status:1 , Message: Upload Again and File Size Should be Less Than 10MB"), JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(JsonResponseFactory.ErrorResponse(ex.Message), JsonRequestBehavior.AllowGet);
}
}
The compiler doesn't know it's an array, it's trusting the programmer. Deleting a pointer to a single int
with delete []
would result in undefined behavior. Your second main()
example is unsafe, even if it doesn't immediately crash.
The compiler does have to keep track of how many objects need to be deleted somehow. It may do this by over-allocating enough to store the array size. For more details, see the C++ Super FAQ.
$('#message').val('');
Explanation (from @BalusC):
textarea
is an input
element with a value. You actually want to "empty" the value. So as for every other input
element (input
, select
, textarea
) you need to use element.val('');
.
Also see docs
For Ruby Mine users on Windows:
Open file in editor Select the block and press Ctrl+forward slash, you will have selected block starting with #.
Now if you want to un-comment the commented block, press same key combination Ctrl+forward slash again
I used this below if this is what you are thinking. It it worked well for me.
<?php
include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>
What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.
Try below approach,
$('#bfCaptchaEntry').on('click', myfunction);
or in case jQuery is not an absolute necessaity then try below,
document.getElementById('bfCaptchaEntry').onclick = myfunction;
However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...
Read more on this post https://stackoverflow.com/a/6348597/297641
SELECT * FROM NOTES ORDER BY UPPER(title)
You can use functools.partial
for this (as you suspected):
from functools import partial
def target(lock, iterable_item):
for item in iterable_item:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
l = multiprocessing.Lock()
func = partial(target, l)
pool.map(func, iterable)
pool.close()
pool.join()
Example:
def f(a, b, c):
print("{} {} {}".format(a, b, c))
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
a = "hi"
b = "there"
func = partial(f, a, b)
pool.map(func, iterable)
pool.close()
pool.join()
if __name__ == "__main__":
main()
Output:
hi there 1
hi there 2
hi there 3
hi there 4
hi there 5
What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.
I have the same problem bu no solution yet. page-break-inside does not work on browsers but Opera. An alternative might be to use page-break-after: avoid; on all child elements of the div to keep togehter ... but in my tests, the avoid-Attribute does not work eg. in Firefox ...
What works in all ppular browsers are forced page breaks using eg. page-break-after: always
In Eclipse:
Project -> properties -> java Build Path -> libraries
Remove existing JRE System Library, then Add Library -> JRE System library -> next -> ok
Error will be removed.
Who ever also stumbles over this post.
I belive is the correct way:
<div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;">
<div>{{ appointment }}</div>
</div>
I'm finding out that the location of the log4j.properties file depends on the type of Eclipse project.
Specifically, for an Eclipse Dynamic Web Project, most of the answers that involve adding the log4j.properties to the war file do not actually add the properties file in the correct location, especially for Tomcat/Apache.
Here is some of my research and my solution to the issue (again specifically for a Dynamic Web Project running on Tomcat/Apache 6.0)
Please refer to this article around how Tomcat will load classes. It's different than the normal class loader for Java. (https://www.mulesoft.com/tcat/tomcat-classpath) Note that it only looks in two places in the war file, WEB-INF/classes and WEB-INF/lib.
Note that with a Dynamic Web Project, it is not wise to store your .properties file in the build/../classes directory, as this directory is wiped whenever you clean-build your project.
Tomcat does not handle .property files in the WEB-INF/lib location.
You cannot store the log4j.properties file in the src directory, as Eclipse abstracts that directory away from your view.
The one way I have found to resolve this is to alter the build and add an additional directory that will eventually load into the WEB-INF/classes directory in the war file. Specifically....
(1) Right click your project in the project explorer, select 'New'->'Folder'. You can name the folder anything, but the standard in this case is 'resources'. The new folder should appear at the root level of your project.
(2) Move the log4j.properties file into this new folder.
(3) Right click the project again, and select 'Build-Path'->'Configure Build Path'. Select the 'Sources' tab. Click the 'Add Folder' button. Browse to find your new folder you created in step (1) above. Select 'OK'.
(4) Once back to the eclipse Project Explorer view, note that the folder has now moved to the 'Java Resources' area (ie it's no longer at the root due to eclipse presentation abstraction).
(5) Clean build your project.
(6) To validate that the .properties file now exists in WEB-INF/classes in your war file, export a war file to an easy location (right click Project -> Export -> War file) and checkout the contents. Note that the log4j.properties file now appears in the WEB-INF/classes.
(7) Promote your project to Tomcat/Apache and note that log4j now works.
Now that log4j works, start logging, solve world problems, take some time off, and enjoy a tasty adult beverage.
To view the stdout, you can start the docker container with -i
. This of course does not enable you to leave the started process and explore the container.
docker start -i containerid
Alternatively you can view the filesystem of the container at
/var/lib/docker/containers/containerid/root/
However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v
switch when you use docker run
. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.
in exemple if you want to compile sources but have objects in an different directory :
You need to do :
gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...
but with most of macros the result will be all objects followed by all sources, like :
gcc -c -o <all OBJ path> <all SRC path>
so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(
the solution is to use these special macros
$@ $<
this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)
$(OBJ):$(SRC)
gcc -c -o $@ $< $(HEADERS) $(FLAGS)
it means :
$@ = $(OBJ)
$< = $(SRC)
but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC
I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:
var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();
Cross posting my answer from this SO question for another simple, pip version proof solution.
try: # for pip >= 10
from pip._internal.req import parse_requirements
from pip._internal.download import PipSession
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
from pip.download import PipSession
requirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())
if __name__ == '__main__':
setup(
...
install_requires=[str(requirement.req) for requirement in requirements],
...
)
Then just throw in all your requirements under requirements.txt
under project root directory.
Since Windows doesn't have a grep
command, this worked for me in PowerShell:
git log --find-renames --diff-filter=D --summary | Select-String -Pattern "delete mode" | sort -u > deletions.txt
You can use a list comprehension:
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]
Use &
:
foreach($arr as &$value) {
$value = $newVal;
}
&
passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.
PHP documentation for Passing by Reference
Edit 2018
This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach
(or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.
Loops in PHP don't have their own scope. - @Mark Amery
This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.
Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.
Foreach performance.
In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach
would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.
Code readability.
Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about &
operator take a look at this guide: Reference — What does this symbol mean in PHP?
For those who want to learn more about this part of PHP language: PHP References Explained
A very nice technical explanation by @NikiC of the internal logic of PHP foreach
loops:
How does PHP 'foreach' actually work?
shorter version:
found = Value1.StartsWith("abc");
sorry, but I am a stickler for 'less' code.
Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith
public static class StackOverflowExtensions
{
public static bool StartsWith(this String val, string findString, int count)
{
return val.Substring(0, count).Contains(findString);
}
}
always returns a valid RGB color:
`rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
let c= `rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
console.log(c);
document.body.style.background=c
_x000D_
I got this error while implementing a subclass without the necessary framework added (MPMoviePlayerController without the MediaPlayer framework, in this example)
Here is a variation of Yuda Prawira answer:
flush()
and all the file attributesstderr
also.
import contextlib, sys
@contextlib.contextmanager
def log_print(file):
# capture all outputs to a log file while still printing it
class Logger:
def __init__(self, file):
self.terminal = sys.stdout
self.log = file
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def __getattr__(self, attr):
return getattr(self.terminal, attr)
logger = Logger(file)
_stdout = sys.stdout
_stderr = sys.stderr
sys.stdout = logger
sys.stderr = logger
try:
yield logger.log
finally:
sys.stdout = _stdout
sys.stderr = _stderr
with log_print(open('mylogfile.log', 'w')):
print('hello world')
print('hello world on stderr', file=sys.stderr)
# you can capture the output to a string with:
# with log_print(io.StringIO()) as log:
# ....
# print('[captured output]', log.getvalue())
Delete the local.properties
from the android folder in your react project and try it.
I've done this and succeeded.
Just had a very similar problem and solved it by adding
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
Apparently the site I'm fetching redirects to another location and php-curl doesn't follow redirects by default.
First, as for your Athlete class, you can remove your Getter and Setter
methods since you have declared your instance variables with an access modifier of public
. You can access the variables via <ClassName>.<variableName>
.
However, if you really want to use that Getter and Setter
, change the public
modifier to private
instead.
Second, for the constructor, you're trying to do a simple technique called shadowing
. Shadowing
is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing
:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person
class as follow:
Person person = new Person("theolc");
Variable name
will be equal to "theolc"
.
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter
. Remove your parameters on your constructor
.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the
removeEventListener
method.
If you need to return the table's total row count, you can use an alternative way to the SELECT COUNT(*)
statement.
Because SELECT COUNT(*)
makes a full table scan to return the row count, it can take very long time for a large table. You can use the sysindexes
system table instead in this case. There is a ROWS
column that contains the total row count for each table in your database. You can use the following select statement:
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2
This will drastically reduce the time your query takes.
If the file is a .dll then you can use the TaskList command line app to see whose got it open:
TaskList /M nameof.dll
In SQL Server 2008 in addition to the above two options you have a third option to make this setting through SQL Server Management Studio.
1.Start Management Studio and connect to Report Server Instance (make sure you select 'Reporting Services' server type).
2.Right click on the ReportServer and Select Properties
3.Click Advanced
4.In EnableRemoteErrors, select True.
5.Click OK.
SELECT
name, email, COUNT(*)
FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
Simply group on both of the columns.
Note: the older ANSI standard is to have all non-aggregated columns in the GROUP BY but this has changed with the idea of "functional dependency":
In relational database theory, a functional dependency is a constraint between two sets of attributes in a relation from a database. In other words, functional dependency is a constraint that describes the relationship between attributes in a relation.
Support is not consistent:
sql_mode=only_full_group_by
:
Is this any good at all (will it do what I want?)
You can do so. Another feasible way is using java.net.Socket
.
public static boolean pingHost(String host, int port, int timeout) {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(host, port), timeout);
return true;
} catch (IOException e) {
return false; // Either timeout or unreachable or failed DNS lookup.
}
}
There's also the InetAddress#isReachable()
:
boolean reachable = InetAddress.getByName(hostname).isReachable();
This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.
Do I have to somehow close the connection?
No, you don't explicitly need. It's handled and pooled under the hoods.
I suppose this is a GET request. Is there a way to send HEAD instead?
You can cast the obtained URLConnection
to HttpURLConnection
and then use setRequestMethod()
to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.
Testing the server for availability is not enough in my case, I need to test the URL (the webapp may not be deployed)
Indeed, connecting a host only informs if the host is available, not if the content is available. It can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. You can determine that by checking if the HTTP response code is 200.
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
// Not OK.
}
// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error
For more detail about response status codes see RFC 2616 section 10. Calling connect()
is by the way not needed if you're determining the response data. It will implicitly connect.
For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:
/**
* Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code is in
* the 200-399 range.
* @param url The HTTP URL to be pinged.
* @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
* the total timeout is effectively two times the given timeout.
* @return <code>true</code> if the given HTTP URL has returned response code 200-399 on a HEAD request within the
* given timeout, otherwise <code>false</code>.
*/
public static boolean pingURL(String url, int timeout) {
url = url.replaceFirst("^https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
return (200 <= responseCode && responseCode <= 399);
} catch (IOException exception) {
return false;
}
}
If you want to do multiple commands, you could use:
for I in `ls *.sql`
do
grep "foo" $I >> foo.log
grep "bar" $I >> bar.log
done
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
What you have should work, unless ${STATUS}
is empty. It would probably be better to do:
if ! [ "${STATUS}" -eq 200 ] 2> /dev/null && [ "${STRING}" != "${VALUE}" ]; then
or
if [ "${STATUS}" != 200 ] && [ "${STRING}" != "${VALUE}" ]; then
It's hard to say, since you haven't shown us exactly what is going wrong with your script.
Personal opinion: never use [[
. It suppresses important error messages and is not portable to different shells.
document.getElementById('youridhere').click()
This is not strictly true as the NTFS filesystem supports paths up to 32k characters. You can use the win32 api and "\\?\
" prefix the path to use greater than 260 characters.
A detailed explanation of long path from the .Net BCL team blog.
A small excerpt highlights the issue with long paths
Another concern is inconsistent behavior that would result by exposing long path support. Long paths with the
\\?\
prefix can be used in most of the file-related Windows APIs, but not all Windows APIs. For example, LoadLibrary, which maps a module into the address of the calling process, fails if the file name is longer than MAX_PATH. So this means MoveFile will let you move a DLL to a location such that its path is longer than 260 characters, but when you try to load the DLL, it would fail. There are similar examples throughout the Windows APIs; some workarounds exist, but they are on a case-by-case basis.
You can use the global keyword to solve this.
Assume that you want to declare a variable called isFromManageUserAccount as a global variable you can use the following code.
global.isFromManageUserAccount=false;
After declaring like this you can use this variable anywhere in the application.
For my application i made a helper function:
function message( $message , $status = 'success', $redirectPath = null )
{
$redirectPath = $redirectPath == null ? back() : redirect( $redirectPath );
return $redirectPath->with([
'message' => $message,
'status' => $status,
]);
}
message layout, main.layouts.message
:
@if($status)
<div class="center-block affix alert alert-{{$status}}">
<i class="fa fa-{{ $status == 'success' ? 'check' : $status}}"></i>
<span>
{{ $message }}
</span>
</div>
@endif
and import every where to show message:
@include('main.layouts.message', [
'status' => session('status'),
'message' => session('message'),
])
Solution is to change Delimiter.
Content of the csv file -> Note .. Also space and , in value
Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan
Col1;Col2;Col3
a,ap;noo,t;mi es
P,iet;G ,ijs;Ja ,n
$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';'
Answer:
Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}
It is possible to read a CSV file and use other Delimiter to separate each column.
It worked for my script :-)
You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
manage_pages
permission (you may need the user_events
permission too, not sure)me/accounts
connection and copy your page's access_token
access_token
to the GET fieldsPAGE_ID/events
)Just wanted to add something to Kamil's answer
After following the steps, I still got an error,
error Could not find device with the name: "....'s Xr"
After removing special characters from the device name (Go to Settings -> General -> About -> Name)
Eg: '
It Worked !
Hope this will help someone who faced similar issue.
Tested with - react-native-cli: 2.0.1 | react-native: 0.59.8 | VSCode 1.32 | Xcode 10.2.1 | iOS 12.3
You change default value in MySQL configuration file (option connect_timeout in mysqld section) -
[mysqld]
connect_timeout=100
If this file is not accessible for you, then you can set this value using this statement -
SET GLOBAL connect_timeout=100;
Most of the answers on this thread are either complex or will result in deadlock.
Following method is simple and it will avoid deadlock because we are waiting for the task to finish and only then getting its result-
var task = Task.Run(() => GenerateCodeAsync());
task.Wait();
string code = task.Result;
Furthermore, here is a reference to MSDN article that talks about exactly same thing- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
Try this.
Note: Here many answers for Linux is just Ctrl + Alt + L which is wrong. In Linux, doing Ctrl + Alt + L locks the system.
i have tested that and it worked
val x = 9
def printType[T](x:T) :Unit = {println(x.getClass.toString())}
Giving such permission can be dangerous, especially if your web application uses that same username.
Now the web user (and the whole world wide web) also has the permission to create and drop objects within your database. Think SQL Injection!
I recommend granting Execute privileges only to the specific user on the given object as follows:
grant execute on storedProcedureNameNoquotes to myusernameNoquotes
Now the user myusernameNoquotes can execute procedure storedProcedureNameNoquotes without other unnecessary permissions to your valuable data.
it doesn't work that way. the work around is to manually check the coordinates of the mouse click against the area occupied by each element.
area occupied by an element can found found by 1. getting the location of the element with respect to the top left of the page, and 2. the width and the height. a library like jQuery makes this pretty simple, although it can be done in plain js. adding an event handler for mousemove
on the document
object will provide continuous updates of the mouse position from the top and left of the page. deciding if the mouse is over any given object consists of checking if the mouse position is between the left, right, top and bottom edges of an element.
int height(Node* root) {
if(root==NULL) return -1;
return max(height(root->left),height(root->right))+1;
}
Take of maximum height from left and right subtree and add 1 to it.This also handles the base case(height of Tree with 1 node is 0).
If you're looking to use powerful, higher level tools rather than building everything yourself, going through the projects and readings for this course is a pretty good option. It's a languages course by the author of the Java parser engine ANTLR. You can get the book for the course as a PDF from the Pragmatic Programmers.
The course goes over the standard compiler compiler stuff that you'd see elsewhere: parsing, types and type checking, polymorphism, symbol tables, and code generation. Pretty much the only thing that isn't covered is optimizations. The final project is a program that compiles a subset of C. Because you use tools like ANTLR and LLVM, it's feasible to write the entire compiler in a single day (I have an existence proof of this, though I do mean ~24 hours). It's heavy on practical engineering using modern tools, a bit lighter on theory.
LLVM, by the way, is simply fantastic. Many situations where you might normally compile down to assembly, you'd be much better off compiling to LLVM's Intermediate Representation instead. It's higher level, cross platform, and LLVM is quite good at generating optimized assembly from it.
why don't u try using an absolute xPath
//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment
or since u know that it is a payment and payment doesn't have any attributes just select directly from payment
//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment/*
Otherwise for old version, if '--show-item' is not recognize, you can use the following command :
svn log -r HEAD | grep -o -E "^r[0-9]{1,}" | sed 's/r//g'
Hope it helps.
In Internet Explorer 9 (and 8), the console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console
object to be exposed.
The console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object
, nor its methods from Function
, like native ECMAScript functions and objects do. This is the reason apply
and call
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.
For what it's worth, you can still use some Function.prototype
methods on console
methods with a little bind()
magic:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
http://jsfiddle.net/qVGwh/6/ Check this
$("#MadonwebTest").click(function () {
var id = $("#MadonwebTest").closest("div").attr("id");
alert(id);
});
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
Groupby A:
In [0]: grp = df.groupby('A')
Within each group, sum over B and broadcast the values using transform. Then sort by B:
In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
B
2 -2.829710
5 -2.829710
1 0.253651
4 0.253651
0 0.551377
3 0.551377
Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:
In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]
In [3]: sort1
Out[3]:
A B C
2 baz -0.528172 False
5 baz -2.301539 True
1 bar -0.611756 True
4 bar 0.865408 False
0 foo 1.624345 False
3 foo -1.072969 True
Finally, sort the 'C' values within groups of 'A' using the sort=False
option to preserve the A sort order from step 1:
In [4]: f = lambda x: x.sort('C', ascending=False)
In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)
In [6]: sort2
Out[6]:
A B C
A
baz 5 baz -2.301539 True
2 baz -0.528172 False
bar 1 bar -0.611756 True
4 bar 0.865408 False
foo 3 foo -1.072969 True
0 foo 1.624345 False
Clean up the df index by using reset_index
with drop=True
:
In [7]: sort2.reset_index(0, drop=True)
Out[7]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False