Well, why this exists in general is probably different than why it exists in your example.
It all started half a century ago with repurposing hardcopy communication terminals as computer user interfaces. In the initial Unix and C era that was the ASR-33 Teletype.
This device was slow (10 cps) and noisy and ugly and its view of the ASCII character set ended at 0x5f, so it had (look closely at the pic) none of the keys:
{ | } ~
The trigraphs were defined to fix a specific problem. The idea was that C programs could use the ASCII subset found on the ASR-33 and in other environments missing the high ASCII values.
Your example is actually two of
??!
, each meaning|
, so the result is||
.
However, people writing C code almost by definition had modern equipment,1 so my guess is: someone showing off or amusing themself, leaving a kind of Easter egg in the code for you to find.
It sure worked, it led to a wildly popular SO question.
ASR-33 Teletype
git difftool -d HEAD filename.txt
This shows a comparison using VI slit window in the terminal.
Use this: $newDate = $dateInDB->format('Y-m-d');
In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.
Many developers will mistakenly use for
loop or foreach
and leave the SqlCommand
to execute outside the loop, to avoid that make sure that you have like this code sample for example:
public static void Save(List<myClass> listMyClass)
{
using (var Scope = new System.Transactions.TransactionScope())
{
if (listMyClass.Count > 0)
{
for (int i = 0; i < listMyClass.Count; i++)
{
SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);
try
{
myConnection.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException sqe)
{
throw new Exception(sqe.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
myConnection.Close();
}
}
}
else
{
throw new Exception("List is empty");
}
Scope.Complete();
}
}
Socks4 is a very simple protocol to implement. You listen for the initial connection, connect to the host/port that was requested by the client, send the success code to the client then forward the outgoing and incoming streams across sockets.
If you go with HTTP you'll have to read and possibly set/remove some HTTP headers so that's a little more work.
If I remember correctly, SSL will work across HTTP and Socks proxies. For a HTTP proxy you implement the CONNECT verb, which works much like the socks4 as described above, then the client opens the SSL connection across the proxied tcp stream.
or what you could do in your Form Request is (for Laravel 5.3+)
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user, //here user is users/{user} from resource's route url
];
}
i've done it in Laravel 5.6 and it worked.
After looking at your method, I used this method to solve it.
class Register(forms.Form):
username = forms.CharField(label='???', max_length=32)
email = forms.EmailField(label='??', max_length=64)
password = forms.CharField(label="??", min_length=6, max_length=16)
captcha = forms.CharField(label="???", max_length=4)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
self.fields[field_name].widget.attrs.update({
"placeholder": field.label,
'class': "input-control"
})
Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check
Languages -> Visual C++ -> Common tools for Visual C++
Windows and web development -> Tools for universal windows apps -> Tools (1.4.1)
and Windows 10 SDK ([version])
Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])
and install. Then right click on solution -> Re-target and it will compile
Just to expand on this error in the context of an interface, if you are type hinting your function parameters like so:
interface A
use Bar;
interface A
{
public function foo(Bar $b);
}
Class B
class B implements A
{
public function foo(Bar $b);
}
If you have forgotten to include the use
statement on your implementing class (Class B), then you will also get this error even though the method parameters are identical.
I am not sure what math can be done on a DATETIME data type, but if you are using PHP, I strongly recommend using the integer-based timestamps. Basically, you can store a 4-byte integer in the database using PHP's time() function. This makes doing math on it much more straightforward.
You could try Directory.Exists(path)
and Directory.GetFiles(path)
- probably less overhead (no objects - just strings etc).
I don't think this can be done using jQuery's animate
function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilize what the browser makes possible. (jQuery experts, correct me if I'm wrong of course.)
I guess you would have to work around this by not using genuine background-image
s, but div
elements containing the image, positioned using position: absolute
(or fixed
) and z-index
for stacking. You would then animate those div
s.
In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:
python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop
python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function(){
//do something depressing
},
success: function(){
//do something cheerful :)
}
});
from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06
Speaking of the counter example - as given above, the counter will be shared between all functions that use the decorator:
def counter(func):
def wrapped(*args, **kws):
print 'Called #%i' % wrapped.count
wrapped.count += 1
return func(*args, **kws)
wrapped.count = 0
return wrapped
That way, your decorator can be reused for different functions (or used to decorate the same function multiple times: func_counter1 = counter(func); func_counter2 = counter(func)
), and the counter variable will remain private to each.
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();
<asp:HiddenField ID="hidden" runat="server" />
protected String LabelProperty
{
get
{
return hidden.Value;
}
set
{
hidden.Value = value;
}
}
<script>
function UpdateControl() {
document.getElementById('<%=hidden.ClientID %>').value = '12';
}
</script>
Now you can access the Property directly across the Postback
. The Label
Control updated value will be Lost across PostBack
in case it is being used directly in code behind .
In the main method using for loops: -the third for loop in my example is the answer to this question. -in my example I made an array of 20 random integers, assigned a variable the smallest number, and stopped the loop when the location of the array reached the smallest value while counting the number of loops.
import java.util.Random;
public class scratch {
public static void main(String[] args){
Random rnd = new Random();
int randomIntegers[] = new int[20];
double smallest = randomIntegers[0];
int location = 0;
for(int i = 0; i < randomIntegers.length; i++){ // fills array with random integers
randomIntegers[i] = rnd.nextInt(99) + 1;
System.out.println(" --" + i + "-- " + randomIntegers[i]);
}
for (int i = 0; i < randomIntegers.length; i++){ // get the location of smallest number in the array
if(randomIntegers[i] < smallest){
smallest = randomIntegers[i];
}
}
for (int i = 0; i < randomIntegers.length; i++){
if(randomIntegers[i] == smallest){ //break the loop when array location value == <smallest>
break;
}
location ++;
}
System.out.println("location: " + location + "\nsmallest: " + smallest);
}
}
Code outputs all the numbers and their locations, and the location of the smallest number followed by the smallest number.
I had same problem and finally I understood that my node version is old. For example, you can install the current active LTS node version in Ubuntu by the following steps:
sudo apt-get update
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
sudo apt-get install nodejs -y
Installation instructions for more versions and systems can be found in the following link:
https://github.com/nodesource/distributions/blob/master/README.md
This code appears to do what you are asking for.
for value in range(1,1000):
if value % 3 == 0 or value % 5 == 0:
print(value)
Or something like
for value in range(1,1000):
if value % 3 == 0 or value % 5 == 0:
some_list.append(value)
Or any number of things.
Here's a solution that works for environments that don't have the string library (Linux kernel, embedded systems, etc):
#define FILENAME ({ \
const char* filename_start = __FILE__; \
const char* filename = filename_start; \
while(*filename != '\0') \
filename++; \
while((filename != filename_start) && (*(filename - 1) != '/')) \
filename--; \
filename; })
Now just use FILENAME
instead of __FILENAME__
. Yes, it's still a runtime thing but it works.
Here's yet another solution, using the XOM library, that competes with my dom4j answer. (This is part of my quest to find a good dom4j replacement where XOM was suggested as one option.)
First read the XML fragment into a nu.xom.Document
:
String newNode = "<node>value</node>"; // Convert this to XML
Document newNodeDocument = new Builder().build(newNode, "");
Then, get the Document and the Node under which the fragment is added. Again, for testing purposes I'll create the Document from a string:
Document originalDoc = new Builder().build("<root><given></given></root>", "");
Element givenNode = originalDoc.getRootElement().getFirstChildElement("given");
Now, adding the child node is simple, and similar as with dom4j (except that XOM doesn't let you add the original root element which already belongs to newNodeDocument
):
givenNode.appendChild(newNodeDocument.getRootElement().copy());
Outputting the document yields the correct result XML (and is remarkably easy with XOM: just print the string returned by originalDoc.toXML()
):
<?xml version="1.0"?>
<root><given><node>value</node></given></root>
(If you wanted to format the XML nicely (with indentations and linefeeds), use a Serializer
; thanks to Peter Štibraný for pointing this out.)
So, admittedly this isn't very different from the dom4j solution. :) However, XOM may be a little nicer to work with, because the API is better documented, and because of its design philosophy that there's one canonical way for doing each thing.
Appendix: Again, here's how to convert between org.w3c.dom.Document
and nu.xom.Document
. Use the helper methods in XOM's DOMConverter
class:
// w3c -> xom
Document xomDoc = DOMConverter.convert(w3cDoc);
// xom -> w3c
org.w3c.dom.Document w3cDoc = DOMConverter.convert(xomDoc, domImplementation);
// You can get a DOMImplementation instance e.g. from DOMImplementationRegistry
git config --list
to check current username & email in your local repo.git config [--global] user.name "Full Name"
git config [--global] user.email "[email protected]"
.git/config
manually instead.When performing step 2 if you see credential.helper=manager
you need to open the credential manager of your computer (Win or Mac) and update the credentials there
Here is how it look on windows
Troubleshooting? Learn more
I created my project folder 'phpproj' in
...\xampp\htdocs
ex:...\xampp\htdocs\phpproj
and it worked for me. I am using Win 7 & and using xampp-win32-1.8.1
I added a php file with the following code
<?php
// Show all information, defaults to INFO_ALL
phpinfo();
?>
was able to access the file using the following URL
http://localhost/phpproj/copy.php
Make sure you restart your Apache server using the control panel before accessing it using the above URL
The most useful thing you can do here is display/i $pc
, before using stepi
as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi
command.
(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)
for-loop
:enumerate
and a list comprehension are more pythonic, not necessarily faster, however, this answer is aimed at students who may not be allowed to use some of those built-in functions.indices
for i in range(len(x)):
, which essentially iterates through a list of index locations [0, 1, 2, 3, ..., len(x)-1]
i
, where x[i]
is a match to value
, to indices
def get_indices(x: list, value: int) -> list:
indices = list()
for i in range(len(x)):
if x[i] == value:
indices.append(i)
return indices
n = [1, 2, 3, -50, -60, 0, 6, 9, -60, -60]
print(get_indices(n, -60))
>>> [4, 8, 9]
get_indices
, are implemented with type hints. In this case, the list, n
, is a bunch of int
s, therefore we search for value
, also defined as an int
.while-loop
and .index
:.index
, use try-except
for error handling, because a ValueError
will occur if value
is not in the list
.def get_indices(x: list, value: int) -> list:
indices = list()
i = 0
while True:
try:
# find an occurrence of value and update i to that index
i = x.index(value, i)
# add i to the list
indices.append(i)
# advance i by 1
i += 1
except ValueError as e:
break
return indices
print(get_indices(n, -60))
>>> [4, 8, 9]
I'm not sure these are the best options but they'll definitely get the job done:
declare @durations table
(
Duration int
)
Insert into @durations(Duration)
values(60),(80),(90),(150),(180),(1000)
--Option 1 - Manually concatenate the values together
select right('0' + convert(varchar,Duration / 60),2) + ':' + right('0' + convert(varchar,Duration % 60),2)
from @Durations
--Option 2 - Make use of the time variable available since SQL Server 2008
select left(convert(time,DATEADD(minute,Duration,0)),5)
from @durations
GO
You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:
The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:
"[\\[\\]?*+|{}\\\\()@.\n\r]"
Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.
Even though it's inside of an if
block, the compiler doesn't know that T
is string
.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime
to string
)
You need to cast to object
, (which any T
can cast to), and from there to string
(since object
can be cast to string
).
For example:
T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;
Another solution would be,you can get the object itself as value if you are not mentioning it's id as value: Note: [value] and [ngValue] both works here.
<select (change)="your_method(values[$event.target.selectedIndex])">
<option *ngFor="let v of values" [value]="v" >
{{v.name}}
</option>
</select>
In ts:
your_method(v:any){
//access values here as needed.
// v.id or v.name
}
Note: If you are using reactive form and you want to catch selected value on form Submit, you should use [ngValue] directive instead of [value] in above scanerio
Example:
<select (change)="your_method(values[$event.target.selectedIndex])" formControlName="form_control_name">
<option *ngFor="let v of values" [ngValue]="v" >
{{v.name}}
</option>
</select>
In ts:
form_submit_method(){
let v : any = this.form_group_name.value.form_control_name;
}
If I understand the question correctly, you want to detect when the h_no
doesn't increase and then increment the class
. (I'm going to walk through how I solved this problem, there is a self-contained function at the end.)
We only care about the h_no
column for the moment, so we can extract that from the data frame:
> h_no <- data$h_no
We want to detect when h_no
doesn't go up, which we can do by working out when the difference between successive elements is either negative or zero. R provides the diff
function which gives us the vector of differences:
> d.h_no <- diff(h_no)
> d.h_no
[1] 1 1 1 -3 1 1 1 1 1 1 -6 1 1 1
Once we have that, it is a simple matter to find the ones that are non-positive:
> nonpos <- d.h_no <= 0
> nonpos
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
[13] FALSE FALSE
In R, TRUE
and FALSE
are basically the same as 1
and 0
, so if we get the cumulative sum of nonpos
, it will increase by 1 in (almost) the appropriate spots. The cumsum
function (which is basically the opposite of diff
) can do this.
> cumsum(nonpos)
[1] 0 0 0 1 1 1 1 1 1 1 2 2 2 2
But, there are two problems: the numbers are one too small; and, we are missing the first element (there should be four in the first class).
The first problem is simply solved: 1+cumsum(nonpos)
. And the second just requires adding a 1
to the front of the vector, since the first element is always in class 1
:
> classes <- c(1, 1 + cumsum(nonpos))
> classes
[1] 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3
Now, we can attach it back onto our data frame with cbind
(by using the class=
syntax, we can give the column the class
heading):
> data_w_classes <- cbind(data, class=classes)
And data_w_classes
now contains the result.
We can compress the lines together and wrap it all up into a function to make it easier to use:
classify <- function(data) {
cbind(data, class=c(1, 1 + cumsum(diff(data$h_no) <= 0)))
}
Or, since it makes sense for the class
to be a factor:
classify <- function(data) {
cbind(data, class=factor(c(1, 1 + cumsum(diff(data$h_no) <= 0))))
}
You use either function like:
> classified <- classify(data) # doesn't overwrite data
> data <- classify(data) # data now has the "class" column
(This method of solving this problem is good because it avoids explicit iteration, which is generally recommend for R, and avoids generating lots of intermediate vectors and list etc. And also it's kinda neat how it can be written on one line :) )
I think this is just what you'er looking for:
ls | xargs -I {} mv {} Unix_{}
Yes, it is simple yet elegant and powerful, and also one-liner. You can get more detailed intro from me on the page:Rename Files and Directories (Add Prefix)
Time flies, the way I do without enabling less secured app
is making a password for specific app
Step one: enable 2FA
Step two: create an app-specific password
After this, put the sixteen digits password to the settings and reload the app, enjoy!
config.action_mailer.smtp_settings = {
...
password: 'HERE', # <---
authentication: 'plain',
enable_starttls_auto: true
}
In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner
. Here is a simple example that reads lines from a file:
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("/path/to/file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
This is the cleanest way to read from a Reader
line by line.
There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of Reader.Read()
.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
Yes. There is a method on UIButton -setTitle:forState:
use that.
Early versions of unix measured system time in 1/60 s intervals. This meant that a 32-bit unsigned integer could only represent a span of time less than 829 days. For this reason, the time represented by the number 0
(called the epoch) had to be set in the very recent past. As this was in the early 1970s, the epoch was set to 1971-1-1.
Later, the system time was changed to increment every second, which increased the span of time that could be represented by a 32-bit unsigned integer to around 136 years. As it was no longer so important to squeeze every second out of the counter, the epoch was rounded down to the nearest decade, thus becoming 1970-1-1. One must assume that this was considered a bit neater than 1971-1-1.
Note that a 32-bit signed integer using 1970-1-1 as its epoch can represent dates up to 2038-1-19, on which date it will wrap around to 1901-12-13.
You should not call .get() directly. Optional<>, that Stream::max
returns, was designed to benefit from .orElse... inline handling.
If you are sure your arguments have their size of 2+:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElseThrow(() -> new IllegalArgumentException("Expected 'list' to be of size: >= 2. Was: 0"));
If you support empty lists, then return some default value, for example:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElse(new Date(Long.MIN_VALUE));
CREDITS to: @JimmyGeers, @assylias from the accepted answer.
To remove the margins on all rows:
.row {
margin: 0px !important;
}
gitx http://gitx.frim.nl/
Some bugs when working with large commit sets but great for browsing through changes and picking different changes to stage and then commit.
This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config
file and having something like this
Host git_host
HostName git.host.de
User root
Port 4019
then you can have
url = git_host:/var/cache/git/project.git
and you can also ssh git_host
and scp git_host ...
and everything will work out.
Use dates.tolist()
to convert to native datetime objects, then simply access year
. Example:
>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]
This is basically the same idea exposed in https://stackoverflow.com/a/35281829/2192272, but using simpler syntax.
Tested with python 3.6 / numpy 1.18.
I have found an FTP server and its working. I was successfully able to upload a file to this FTP server and then see file created by hitting same url. Visit here and read properly before use. Good luck...!
Edit: link is now dead, but the FTP server is still up! Connect with the username "anonymous" and an email address as a password: ftp://ftp.swfwmd.state.fl.us
BUT FIRST read this before using it
You can also set these values programatically in the class library, this will avoid unnecessary movement of the config files across the library. The example code for simple BasciHttpBinding is -
BasicHttpBinding basicHttpbinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
basicHttpbinding.Name = "BasicHttpBinding_YourName";
basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
basicHttpbinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress endpointAddress = new EndpointAddress("http://<Your machine>/Service1/Service1.svc");
Service1Client proxyClient = new Service1Client(basicHttpbinding,endpointAddress);
I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
There is no such thing as a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.
Umm. Just change the string passed to the prompt()
function.
While searching, I found that there we CANNOT change the content of popup Prompt Box
You can't change the title. You can change the content, it is the first argument passed to the prompt()
function.
Command-Option-Shift-K to clean out the build folder. Even better, quit Xcode and clean out ~/Library/Developer/Xcode/DerivedData manually. Remove all its contents because there's a bug where Xcode will run an old version of your project that's in there somewhere. (Xcode 4.2 will show you the Derived Data folder: choose Window > Organizer and switch to the Projects tab. Click the right-arrow to the right of the Derived Data folder name.)
In the simulator, choose iOS Simulator > Reset Content and Settings.
Finally, for completeness, you can delete the contents of /var/folders; some caching happens there too.
WARNING: Deleting /var/folders can cause issues, and you may need to repair or reinstall your operating system after doing so.
EDIT: I have just learned that if you are afraid to grapple with /var/folders/ you can use the following command in the Terminal to delete in a more targeted way:
rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"
EDIT: For certain Swift-related problems I have found it useful to delete ~/Library/Caches/com.apple.dt.Xcode. You lose a lot when you do this, like your spare copies of the downloaded documentation doc sets, but it can be worth it.
The current root password must be empty. Then under "new root password" enter your password and confirm.
If you are running this code on a local server (i.e your computer for development purposes) it won't send the email to the recipient. It will create a .txt
file in a folder named mailoutput
.
In the case if you are using a free hosing service, like 000webhost
or hostinger
, those service providers disable the mail()
function to prevent unintended uses of email spoofing, spamming, etc. I prefer you to contact them to see whether they support this feature.
If you are sure that the service provider supports the mail() function, you can check this PHP manual for further reference,
To check weather your hosting service support the mail() function, try running this code (remember to change the recipient email address):
<?php
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
hr {
border-top:1px dotted #000;
/*Rest of stuff here*/
}
A solution with ggplot2
:
qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)
A similar case solved:
In our case, we wanted to set up linked servers using cnames and with the logins current security context.
All in order we checked that the service account running SQL Server had its' proper spns set and that the AD-object was trusted for delegation. But, while we were able to connect to the cname directly, we still had issues calling a linked server on its' cname: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
It took us far too long to realize that the cnames we used was for A-record, [A], that was set on a higher dns level, and not in its' own domain AD-level. Originally, we had the cname directing to [A].example.com and not (where it should) to: [A].domain.ad.example.com
Ofcourse we had these errors about anonymous logon.
First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.
I don't have enough rep to put this under comments to the existing answers:
unescape
is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent
converts a js string to escaped UTF-8 and decodeURIComponent
only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error
because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // ©
So you need to know your data when using decodeURIComponent.
decodeURIComponent won't work on "%C2"
or any lone byte over 0x7f
because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you ©
Unescape wouldn't work properly on that // ©
AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.
The loop in your code is only an over-simplified example, right?
It would be better to create the PreparedStatement
only once, and re-use it over and over again in the loop.
In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement
, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.
To address the situation that you want to re-use the Java-side PreparedStatement
, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement
for the same SQL on the same connection, it will give you the same (cached) instance.
About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.
You have to use execute immediate (dynamic sql).
DECLARE
v_owner varchar2(40);
v_table_name varchar2(40);
cursor get_tables is
select distinct table_name,user
from user_tables
where lower(user) = 'schema_name';
begin
open get_tables;
loop
fetch get_tables into v_table_name,v_owner;
EXIT WHEN get_tables%NOTFOUND;
execute immediate 'INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
SELECT ''' || v_table_name || ''' , ''' || v_owner ||''',COUNT(*),TO_DATE(SYSDATE,''DD-MON-YY'') FROM ' || v_table_name;
end loop;
CLOSE get_tables;
END;
Get days between Current date to destination Date
SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;
output
335
When you create local variables inside a function that are created on the stack, they most likely get overwritten in memory when exiting the function.
So code like this in most C++ implementations will not work:
char[] populateChar()
{
char* ch = "wonet return me";
return ch;
}
A fix is to create the variable that want to be populated outside the function or where you want to use it, and then pass it as a parameter and manipulate the function, example:
void populateChar(char* ch){
strcpy(ch, "fill me, Will. This will stay", size); // This will work as long as it won't overflow it.
}
int main(){
char ch[100]; // Reserve memory on the stack outside the function
populateChar(ch); // Populate the array
}
A C++11 solution using std::move(ch) to cast lvalues to rvalues:
void populateChar(char* && fillme){
fillme = new char[20];
strcpy(fillme, "this worked for me");
}
int main(){
char* ch;
populateChar(std::move(ch));
return 0;
}
Or this option in C++11:
char* populateChar(){
char* ch = "test char";
// Will change from lvalue to r value
return std::move(ch);
}
int main(){
char* ch = populateChar();
return 0;
}
Objective C:
[[NSString alloc] initWithData:nsdata encoding:NSASCIIStringEncoding];
Swift:
let str = String(data: data, encoding: .ascii)
Just an update of Christopher answer.
Since the version 2.6.0
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.0</version>
</dependency>
Use the JavaTimeModule instead of JSR310Module (deprecated).
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper MAPPER;
public ObjectMapperContextResolver() {
MAPPER = new ObjectMapper();
MAPPER.registerModule(new JavaTimeModule());
MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return MAPPER;
}
}
According to the documentation, the new JavaTimeModule uses same standard settings to default to serialization that does NOT use Timezone Ids, and instead only uses ISO-8601 compliant Timezone offsets.
Behavior may be changed using SerializationFeature.WRITE_DATES_WITH_ZONE_ID
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
A different english definition of Synchronize is Here
Coordinate; combine.
I think that is a better definition than of "Happening at the same time". That one is also a definition, but I don't think it is the one that fits the way it is used in Computer Science.
So an asynchronous task is not co-coordinated with other tasks, whereas a synchronous task IS co-coordinated with other tasks, so one finishes before another starts.
How that is achieved is a different question.
all your code is okay only the things left is just go to the link https://myaccount.google.com/security
and keep scroll down and you will found Allow less secure apps: ON and keep ON, you will find no error.
HEAD
is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.
master
is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).
origin
is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.
This error can occur if you are installing a package with a different bitness than your Python version. To see whether your Python installation is 32- or 64-bit, see here.
Some superpacks (e.g. for Scipy) available on SourceForge or python.org are for 32-bit systems and some are for 64-bit systems. See this answer. In Windows, uninstalling the 32-bit and installing the 64-bit version (or vice versa if your installation is 32-bit) can solve the problem.
Rather than mess with the encode and decode methods I find it easier to specify the encoding when opening the file. The io
module (added in Python 2.6) provides an io.open
function, which has an encoding parameter.
Use the open method from the io
module.
>>>import io
>>>f = io.open("test", mode="r", encoding="utf-8")
Then after calling f's read() function, an encoded Unicode object is returned.
>>>f.read()
u'Capit\xe1l\n\n'
Note that in Python 3, the io.open
function is an alias for the built-in open
function. The built-in open function only supports the encoding argument in Python 3, not Python 2.
Edit: Previously this answer recommended the codecs module. The codecs module can cause problems when mixing read()
and readline()
, so this answer now recommends the io module instead.
Use the open method from the codecs module.
>>>import codecs
>>>f = codecs.open("test", "r", "utf-8")
Then after calling f's read() function, an encoded Unicode object is returned.
>>>f.read()
u'Capit\xe1l\n\n'
If you know the encoding of a file, using the codecs package is going to be much less confusing.
You can embed websites into another website using the <embed>
tag, like so:
<embed src="http://www.example.com" style="width:500px; height: 300px;">
You can change the height, width, and URL to suit your needs.
The <embed>
tag is the most up-to-date way to embed websites, as it was introduced with HTML5.
REST is just a software architecture style for exposing resources.
A typical REST call to return information about customer 34456 could look like:
http://example.com/customer/34456
Have a look at the IBM tutorial for REST web services
Usage:
String remoteCommandOutput = exec("ssh://user:pass@host/work/dir/path", "ls -t | head -n1");
String remoteShellOutput = shell("ssh://user:pass@host/work/dir/path", "ls");
shell("ssh://user:pass@host/work/dir/path", "ls", System.out);
shell("ssh://user:pass@host", System.in, System.out);
sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
Implementation:
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Thread.sleep;
import static org.apache.commons.io.FilenameUtils.getFullPath;
import static org.apache.commons.io.FilenameUtils.getName;
import static org.apache.commons.lang3.StringUtils.trim;
import com.google.common.collect.ImmutableMap;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Map;
import java.util.Properties;
public final class SshUtils {
private static final Logger LOG = LoggerFactory.getLogger(SshUtils.class);
private static final String SSH = "ssh";
private static final String FILE = "file";
private SshUtils() {
}
/**
* <pre>
* <code>
* sftp("file:/C:/home/file.txt", "ssh://user:pass@host/home");
* sftp("ssh://user:pass@host/home/file.txt", "file:/C:/home");
* </code>
*
* <pre>
*
* @param fromUri
* file
* @param toUri
* directory
*/
public static void sftp(String fromUri, String toUri) {
URI from = URI.create(fromUri);
URI to = URI.create(toUri);
if (SSH.equals(to.getScheme()) && FILE.equals(from.getScheme()))
upload(from, to);
else if (SSH.equals(from.getScheme()) && FILE.equals(to.getScheme()))
download(from, to);
else
throw new IllegalArgumentException();
}
private static void upload(URI from, URI to) {
try (SessionHolder<ChannelSftp> session = new SessionHolder<>("sftp", to);
FileInputStream fis = new FileInputStream(new File(from))) {
LOG.info("Uploading {} --> {}", from, session.getMaskedUri());
ChannelSftp channel = session.getChannel();
channel.connect();
channel.cd(to.getPath());
channel.put(fis, getName(from.getPath()));
} catch (Exception e) {
throw new RuntimeException("Cannot upload file", e);
}
}
private static void download(URI from, URI to) {
File out = new File(new File(to), getName(from.getPath()));
try (SessionHolder<ChannelSftp> session = new SessionHolder<>("sftp", from);
OutputStream os = new FileOutputStream(out);
BufferedOutputStream bos = new BufferedOutputStream(os)) {
LOG.info("Downloading {} --> {}", session.getMaskedUri(), to);
ChannelSftp channel = session.getChannel();
channel.connect();
channel.cd(getFullPath(from.getPath()));
channel.get(getName(from.getPath()), bos);
} catch (Exception e) {
throw new RuntimeException("Cannot download file", e);
}
}
/**
* <pre>
* <code>
* shell("ssh://user:pass@host", System.in, System.out);
* </code>
* </pre>
*/
public static void shell(String connectUri, InputStream is, OutputStream os) {
try (SessionHolder<ChannelShell> session = new SessionHolder<>("shell", URI.create(connectUri))) {
shell(session, is, os);
}
}
/**
* <pre>
* <code>
* String remoteOutput = shell("ssh://user:pass@host/work/dir/path", "ls")
* </code>
* </pre>
*/
public static String shell(String connectUri, String command) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
shell(connectUri, command, baos);
return baos.toString();
} catch (RuntimeException e) {
LOG.warn(baos.toString());
throw e;
}
}
/**
* <pre>
* <code>
* shell("ssh://user:pass@host/work/dir/path", "ls", System.out)
* </code>
* </pre>
*/
public static void shell(String connectUri, String script, OutputStream out) {
try (SessionHolder<ChannelShell> session = new SessionHolder<>("shell", URI.create(connectUri));
PipedOutputStream pipe = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(pipe);
PrintWriter pw = new PrintWriter(pipe)) {
if (session.getWorkDir() != null)
pw.println("cd " + session.getWorkDir());
pw.println(script);
pw.println("exit");
pw.flush();
shell(session, in, out);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void shell(SessionHolder<ChannelShell> session, InputStream is, OutputStream os) {
try {
ChannelShell channel = session.getChannel();
channel.setInputStream(is, true);
channel.setOutputStream(os, true);
LOG.info("Starting shell for " + session.getMaskedUri());
session.execute();
session.assertExitStatus("Check shell output for error details.");
} catch (InterruptedException | JSchException e) {
throw new RuntimeException("Cannot execute script", e);
}
}
/**
* <pre>
* <code>
* System.out.println(exec("ssh://user:pass@host/work/dir/path", "ls -t | head -n1"));
* </code>
*
* <pre>
*
* @param connectUri
* @param command
* @return
*/
public static String exec(String connectUri, String command) {
try (SessionHolder<ChannelExec> session = new SessionHolder<>("exec", URI.create(connectUri))) {
String scriptToExecute = session.getWorkDir() == null
? command
: "cd " + session.getWorkDir() + "\n" + command;
return exec(session, scriptToExecute);
}
}
private static String exec(SessionHolder<ChannelExec> session, String command) {
try (PipedOutputStream errPipe = new PipedOutputStream();
PipedInputStream errIs = new PipedInputStream(errPipe);
InputStream is = session.getChannel().getInputStream()) {
ChannelExec channel = session.getChannel();
channel.setInputStream(null);
channel.setErrStream(errPipe);
channel.setCommand(command);
LOG.info("Starting exec for " + session.getMaskedUri());
session.execute();
String output = IOUtils.toString(is);
session.assertExitStatus(IOUtils.toString(errIs));
return trim(output);
} catch (InterruptedException | JSchException | IOException e) {
throw new RuntimeException("Cannot execute command", e);
}
}
public static class SessionHolder<C extends Channel> implements Closeable {
private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
private static final int DEFAULT_PORT = 22;
private static final int TERMINAL_HEIGHT = 1000;
private static final int TERMINAL_WIDTH = 1000;
private static final int TERMINAL_WIDTH_IN_PIXELS = 1000;
private static final int TERMINAL_HEIGHT_IN_PIXELS = 1000;
private static final int DEFAULT_WAIT_TIMEOUT = 100;
private String channelType;
private URI uri;
private Session session;
private C channel;
public SessionHolder(String channelType, URI uri) {
this(channelType, uri, ImmutableMap.of("StrictHostKeyChecking", "no"));
}
public SessionHolder(String channelType, URI uri, Map<String, String> props) {
this.channelType = channelType;
this.uri = uri;
this.session = newSession(props);
this.channel = newChannel(session);
}
private Session newSession(Map<String, String> props) {
try {
Properties config = new Properties();
config.putAll(props);
JSch jsch = new JSch();
Session newSession = jsch.getSession(getUser(), uri.getHost(), getPort());
newSession.setPassword(getPass());
newSession.setUserInfo(new User(getUser(), getPass()));
newSession.setDaemonThread(true);
newSession.setConfig(config);
newSession.connect(DEFAULT_CONNECT_TIMEOUT);
return newSession;
} catch (JSchException e) {
throw new RuntimeException("Cannot create session for " + getMaskedUri(), e);
}
}
@SuppressWarnings("unchecked")
private C newChannel(Session session) {
try {
Channel newChannel = session.openChannel(channelType);
if (newChannel instanceof ChannelShell) {
ChannelShell channelShell = (ChannelShell) newChannel;
channelShell.setPtyType("ANSI", TERMINAL_WIDTH, TERMINAL_HEIGHT, TERMINAL_WIDTH_IN_PIXELS, TERMINAL_HEIGHT_IN_PIXELS);
}
return (C) newChannel;
} catch (JSchException e) {
throw new RuntimeException("Cannot create " + channelType + " channel for " + getMaskedUri(), e);
}
}
public void assertExitStatus(String failMessage) {
checkState(channel.getExitStatus() == 0, "Exit status %s for %s\n%s", channel.getExitStatus(), getMaskedUri(), failMessage);
}
public void execute() throws JSchException, InterruptedException {
channel.connect();
channel.start();
while (!channel.isEOF())
sleep(DEFAULT_WAIT_TIMEOUT);
}
public Session getSession() {
return session;
}
public C getChannel() {
return channel;
}
@Override
public void close() {
if (channel != null)
channel.disconnect();
if (session != null)
session.disconnect();
}
public String getMaskedUri() {
return uri.toString().replaceFirst(":[^:]*?@", "@");
}
public int getPort() {
return uri.getPort() < 0 ? DEFAULT_PORT : uri.getPort();
}
public String getUser() {
return uri.getUserInfo().split(":")[0];
}
public String getPass() {
return uri.getUserInfo().split(":")[1];
}
public String getWorkDir() {
return uri.getPath();
}
}
private static class User implements UserInfo, UIKeyboardInteractive {
private String user;
private String pass;
public User(String user, String pass) {
this.user = user;
this.pass = pass;
}
@Override
public String getPassword() {
return pass;
}
@Override
public boolean promptYesNo(String str) {
return false;
}
@Override
public String getPassphrase() {
return user;
}
@Override
public boolean promptPassphrase(String message) {
return true;
}
@Override
public boolean promptPassword(String message) {
return true;
}
@Override
public void showMessage(String message) {
// do nothing
}
@Override
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
return null;
}
}
}
Make sure the scp command is available on both sides - both on the client and on the server.
BOTH Server and Client, otherwise you will encounter this kind of (weird)error message on your client: scp: command not found
or something similar even though though you have it all configured locally.
In addition to what the others have said, see my answer to a related question which shows that catching and rethrowing is not a no-op (it's in VB, but some of the code could be C# invoked from VB).
Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.
See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html
printf
printf("control string ", argument );
fprintf
fprintf (filename, "control string ", argument );
In Bash you can also explicitly specify your redirects to different files:
cmd >log.out 2>log_error.out
Appending would be:
cmd >>log.out 2>>log_error.out
Assuming you already have a JFrame to call this from:
JOptionPane.showMessageDialog(frame, "thank you for using java");
Note for the answer-seekers (who I also was) - if using arc is not obligatory, a far simpler solution to draw a part-circle is to use stroke-dasharray
of SVG <circle>
.
Divide dash array into two elements, and scale their range to the desired angle. Starting angle can be adjusted using stroke-dashoffset
.
Not a single cosine in sight.
Full example with explanations: https://codepen.io/mjurczyk/pen/wvBKOvP
In python, Suppose you have loaded up the data in some variable train:
train = pandas.read_csv('file_name')
>>> train
train([[ 1., 2., 3.],
[ 5., 1., 2.]],)
I want to check what are the dimensions of the 'file_name'. I have stored the file in train
>>>train.shape
(2,3)
>>>train.shape[0] # will display number of rows
2
>>>train.shape[1] # will display number of columns
3
Problem: Wamp Won't Turn Green & VCRUNTIME140.dll error
Solved:)
You need C++ Redistributable for Visual Studio 2015 RC. Try to download the file, vc_redist.x64.exe from here, https://www.microsoft.com/en-us/download/details.aspx?id=48145
if you already installed then uninstalled it first
I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .
You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.
If none of the above option work, use the following :
$(".datepicker").datepicker();
$(".datepicker").datepicker("setDate", new Date());
This worked for me.
Having also not found a good solution, I wrote a small script a long time ago, by downloading data from the unicode specification (v.5.0.0) and generating intervals for each unicode category and subcategory in the BMP (lately replaced by a small Java program that uses its own native Unicode support).
Basically it converts \p{...}
to a range of values, much like the output of the tool mentioned by Tomalak, but the intervals can end up quite large (since it's not dealing with blocks, but with characters scattered through many different places).
For instance, a Regex written like this:
var regex = unicode_hack(/\p{L}(\p{L}|\p{Nd})*/g);
Will be converted to something like this:
/[\u0041-\u005a\u0061-\u007a...]([...]|[\u0030-\u0039\u0660-\u0669...])*/g
Haven't used it a lot in practice, but it seems to work fine from my tests, so I'm posting here in case someone find it useful. Despite the length of the resulting regexes (the example above has 3591 characters when expanded), the performance seems to be acceptable (see the tests at jsFiddle; thanks to @modiX and @Lwangaman for the improvements).
Here's the source (raw, 27.5KB; minified, 24.9KB, not much better...). It might be made smaller by unescaping the unicode characters, but OTOH will run the risk of encoding issues, so I'm leaving as it is. Hopefully with ES6 this kind of thing won't be necessary anymore.
Update: this looks like the same strategy adopted in the XRegExp Unicode plug-in mentioned by Tim Down, except that in this case regular JavaScript regexes are being used.
Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword.
Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name.
As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final').
Similar question is private final static attribute vs private final attribute
Hope it helps
When creating the TABLE under B2BOWNER
, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert
.
I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.
Remember - if you set the buttons to vbOkOnly
- it will always return 1.
So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk
option.
See wtk's answer.
A more straightforward way to do this would be to use resolve.root.
http://webpack.github.io/docs/configuration.html#resolve-root
resolve.root
The directory (absolute path) that contains your modules. May also be an array of directories. This setting should be used to add individual directories to the search path.
In your case:
var path = require('path');
// ...
resolve: {
root: path.resolve('./mydir'),
extensions: ['', '.js']
}
require('myfile')
or
require('myfile.js')
see also: http://webpack.github.io/docs/configuration.html#resolve-modulesdirectories
AGE
is defined as "42"
so the line:
str += "Do you feel " + AGE + " years old?";
is converted to:
str += "Do you feel " + "42" + " years old?";
Which isn't valid since "Do you feel "
and "42"
are both const char[]
. To solve this, you can make one a std::string
, or just remove the +
:
// 1.
str += std::string("Do you feel ") + AGE + " years old?";
// 2.
str += "Do you feel " AGE " years old?";
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
If you are using Spring, the answer provided by Michail Nikolaev is the simplest and cleanest one, and IMO should be upvoted. Just for convenience purposes, I'll add an inline example using the Springframwework SocketUtils.findAvailableTcpPort() method:
int randomAvailablePort = SocketUtils.findAvailableTcpPort();
It's as easy as that, just one line :). Of course, the Utils class offer many other interesting methods, I suggest having a look at the docs.
Just to extend the accepted answer:
From version 2.7
and 3.1
python has got set
literal {}
in form of usage {1,2,3}
, but {}
itself still used for empty dict.
Python 2.7 (first line is invalid in Python <2.7)
>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>
Python 3.x
>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>
More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes
if you are using bigint in your database table, you can use Long in C#
Its too late but following worked for me well
declare @vCurrentDate date=getutcdate()
select @vCurrentDate
When data type is date, hours would be truncated
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
I was getting this error because my cpp files was not added in the CMakeLists.txt file
You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:
vi test_script.sh
Add the following to your file:
#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>
cd <base directory for your put file>
lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT
And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq
.Then make your script executable chmod +x test_script.sh
and execute it ./test_script.sh
.
Any of LinearLayout.LayoutParams
and TableLayout.LayoutParams
worked for me, for buttons the right one is TableRow.LayoutParams
. That is:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
About using MATCH_PARENT
or WRAP_CONTENT
be the same.
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML
I believe. I use the jQuery html
function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>?
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
Refer to the Flask API document for flask.url_for()
Other sample snippets of usage for linking js or css to your template are below.
<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
Best is this!
function msToTime(duration) {
var milliseconds = parseInt((duration%1000))
, seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
It will return 00:04:21.223 You can format this string then as you wish.
This did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
Of course you can call split
, but it will return strings, not integers. Do
>>> x, y = "42 0".split()
>>> [int(x), int(y)]
[42, 0]
or
[int(x) for x in "42 0".split()]
Something like:
find /path/ -type f -exec stat \{} --printf="%y\n" \; |
sort -n -r |
head -n 1
Explanation:
#!/bin/sh
# http://www.tldp.org/LDP/abs/html/io-redirection.html
echo "Hello World"
exec > script.log 2>&1
echo "Start logging out from here to a file"
bad command
echo "End logging out from here to a file"
exec > /dev/tty 2>&1 #redirects out to controlling terminal
echo "Logged in the terminal"
Output:
> ./above_script.sh
Hello World
Not logged in the file
> cat script.log
Start logging out from here to a file
./logging_sample.sh: line 6: bad: command not found
End logging out from here to a file
Read more here: http://www.tldp.org/LDP/abs/html/io-redirection.html
Try This:
BEGIN
declare @Date1 datetime
declare @Date2 datetime
declare @chkYear int
declare @chkMonth int
declare @chkDay int
declare @chkHour int
declare @chkMinute int
declare @chkSecond int
declare @chkMiliSecond int
set @Date1='2010-12-31 15:13:48.593'
set @Date2='2010-12-31 00:00:00.000'
set @chkYear=datediff(yyyy,@Date1,@Date2)
set @chkMonth=datediff(mm,@Date1,@Date2)
set @chkDay=datediff(dd,@Date1,@Date2)
set @chkHour=datediff(hh,@Date1,@Date2)
set @chkMinute=datediff(mi,@Date1,@Date2)
set @chkSecond=datediff(ss,@Date1,@Date2)
set @chkMiliSecond=datediff(ms,@Date1,@Date2)
if @chkYear=0 AND @chkMonth=0 AND @chkDay=0 AND @chkHour=0 AND @chkMinute=0 AND @chkSecond=0 AND @chkMiliSecond=0
Begin
Print 'Both Date is Same'
end
else
Begin
Print 'Both Date is not Same'
end
End
After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.
The one I've just found and I could absolutely recommend is The Uniform Server
It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.
They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!
Versions in Uniform Server as of today:
Versions in XAMPP as of today:
A simple java implementation, refer to c++ std::next_permutation
:
public static void main(String[] args){
int[] list = {1,2,3,4,5};
List<List<Integer>> output = new Main().permute(list);
for(List result: output){
System.out.println(result);
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
int size = factorial(nums.length);
// add the original one to the list
List<Integer> seq = new ArrayList<Integer>();
for(int a:nums){
seq.add(a);
}
list.add(seq);
// generate the next and next permutation and add them to list
for(int i = 0;i < size - 1;i++){
seq = new ArrayList<Integer>();
nextPermutation(nums);
for(int a:nums){
seq.add(a);
}
list.add(seq);
}
return list;
}
int factorial(int n){
return (n==1)?1:n*factorial(n-1);
}
void nextPermutation(int[] nums){
int i = nums.length -1; // start from the end
while(i > 0 && nums[i-1] >= nums[i]){
i--;
}
if(i==0){
reverse(nums,0,nums.length -1 );
}else{
// found the first one not in order
int j = i;
// found just bigger one
while(j < nums.length && nums[j] > nums[i-1]){
j++;
}
//swap(nums[i-1],nums[j-1]);
int tmp = nums[i-1];
nums[i-1] = nums[j-1];
nums[j-1] = tmp;
reverse(nums,i,nums.length-1);
}
}
// reverse the sequence
void reverse(int[] arr,int start, int end){
int tmp;
for(int i = 0; i <= (end - start)/2; i++ ){
tmp = arr[start + i];
arr[start + i] = arr[end - i];
arr[end - i ] = tmp;
}
}
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
This gives you 3 separate instances of []
, which is what you want
[[]]*n
is similar to
l = []
x = []
for i in range(n):
x.append(l)
While [[] for i in range(3)]
is similar to:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.
The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).
The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
var original_image = 'url(http://stackoverflow.com/Content/img/wmd/link.png)';
var second_image = 'url(http://stackoverflow.com/Content/img/wmd/code.png)';
$('.mydiv').click(function() {
if ($(this).css('background-image').replace(/"/g, '') == original_image) {
$(this).css('background-image', second_image);
} else {
$(this).css('background-image', original_image);
}
return false;
});
});
</script>
<style>
.mydiv {
background-image: url('http://stackoverflow.com/Content/img/wmd/link.png');
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="mydiv"> </div>
</body>
</html>
for(i=0;i<=5;i++)_x000D_
{_x000D_
for(j=0;j<=i;j++)_x000D_
{_x000D_
document.write('*');_x000D_
}_x000D_
document.write('<br>')_x000D_
}
_x000D_
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
Instead of using this
as the accepted answer suggests, use $parent
instead. So in your partial1.html
you'll have:
<form ng-submit="$parent.addLine()">
<input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>
If you want to learn more about the scope in ng-include
or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include
How about :
SQL> select * from all_users;
it will return list of all users/schemas, their ID's and date created in DB :
USERNAME USER_ID CREATED
------------------------------ ---------- ---------
SCHEMA1 120 09-SEP-15
SCHEMA2 119 09-SEP-15
SCHEMA3 118 09-SEP-15
Until PHP 5.3, const
could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum.
define
can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.
An example of good const
usage is to get rid of magic numbers. Take a look at PDO's constants. When you need to specify a fetch type, you would type PDO::FETCH_ASSOC
, for example. If consts were not used, you'd end up typing something like 35
(or whatever FETCH_ASSOC
is defined as). This makes no sense to the reader.
An example of good define
usage is maybe specifying your application's root path or a library's version number.
To run the spring-boot application, need to follow some step.
Maven setup (ignore if already setup):
a. Install maven from https://maven.apache.org/download.cgi
b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).
c. Set MAVEN_HOME in system variable.
d. Set path for maven
Add Maven Plugin to POM.XML
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Build Spring Boot Project with Maven
maven package
or
mvn install / mvn clean install
Run Spring Boot app using Maven:
mvn spring-boot:run
[optional] Run Spring Boot app with java -jar command
java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
I use RC2CryptoServiceProvider.
public static string EncryptText(string openText)
{
RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
ICryptoTransform encryptor = rc2CSP.CreateEncryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
byte[] toEncrypt = Encoding.Unicode.GetBytes(openText);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
byte[] encrypted = msEncrypt.ToArray();
return Convert.ToBase64String(encrypted);
}
}
}
public static string DecryptText(string encryptedText)
{
RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();
ICryptoTransform decryptor = rc2CSP.CreateDecryptor(Convert.FromBase64String(c_key), Convert.FromBase64String(c_iv));
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
List<Byte> bytes = new List<byte>();
int b;
do
{
b = csDecrypt.ReadByte();
if (b != -1)
{
bytes.Add(Convert.ToByte(b));
}
}
while (b != -1);
return Encoding.Unicode.GetString(bytes.ToArray());
}
}
}
Parsing pingtest.txt for each HOST name and result with batch is difficult because the name and result are on different lines.
It is much easier to test the result (the returned error code) of each PING command directly instead of redirecting to a file. It is also more efficient to enclose the entire construct in parens and redirect the final output just once.
>result.txt (
for /f %%i in (testservers.txt) do ping -n 1 %%i >nul && echo %%i UP||echo %%i DOWN
)
It's all about the key bindings which one can simply achieve from .vimrc configurations.
As far as clipboard is concerned you can use :set clipboard unnamed
and the yank from vim will go to system clipboard.
Anyways, whichever one you end up using I suggest using this vimrc config
, it contains a whole lot of plugins and bindings which will make your experience smooth.
This is what worked for me when I had this error:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
</dict>
You need to use the target
selector.
Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/
1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.
$hdfs dfs -get /output-fileFolderName-In-hdfs
On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java. As for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...
ActionLink will never fire post. It always trigger GET request.
you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.
I am creating Dialog in onCreate
and using it with show
and hide
. For me the root cause was not dismissing onBackPressed
, which was finishing the Home
activity.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Home.this.finish();
return;
}
}).create().show();
I was finishing the Home Activity onBackPressed
without closing / dismissing my dialogs.
When I dismissed my dialogs the crash disappeared.
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
networkErrorDialog.dismiss() ;
homeLocationErrorDialog.dismiss() ;
currentLocationErrorDialog.dismiss() ;
Home.this.finish();
return;
}
}).create().show();
#!/bin/bash
goclean() {
local pkg=$1; shift || return 1
local ost
local cnt
local scr
# Clean removes object files from package source directories (ignore error)
go clean -i $pkg &>/dev/null
# Set local variables
[[ "$(uname -m)" == "x86_64" ]] \
&& ost="$(uname)";ost="${ost,,}_amd64" \
&& cnt="${pkg//[^\/]}"
# Delete the source directory and compiled package directory(ies)
if (("${#cnt}" == "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
elif (("${#cnt}" > "2")); then
rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
fi
# Reload the current shell
source ~/.bashrc
}
Usage:
# Either launch a new terminal and copy `goclean` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
goclean github.com/your-username/your-repository
Give this a try.
The code
new DatePickerDialog(MainActivity.this, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
The Style In your styles.xml file
EDIT - Changed theme to Theme.AppCompat.Light.Dialog as suggested
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/blue_500</item>
</style>
Simply invoke orderBy()
as many times as you need it. For instance:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
Produces the following query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
Use the password input type.
<input type="password" name="password" />
Here is a simple demo http://jsfiddle.net/cPaEN/
You could try this
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)
-or-
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row " & MATCH(<single column I value>,<entire column E range>,0))
you could replace <single column I value>
and <entire column E range>
with named ranged. That'd probably be the easiest.
Just drag that formula all the way down the length of your I column in whatever column you want.
I encountered the same problem and solved it by
git checkout -f branch
Well, be careful with the -f
switch. You will lose any uncommitted changes if you use the -f
switch. While there may be some use cases where it is helpful to use -f
, in most cases, you may want to stash
your changes and then switch
branches. The stashing
procedure is explained above.
If you need to create a user_id
then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:
rails generate migration AddUserRefToProducts user:references
This command will generate the following migration:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :user, :product, index: true
end
end
After running rake db:migrate
both a user_id
column and an index will be added to the products
table.
In case you just need to add an index to an existing column, e.g. name
of a user
table, the following technique may be helpful:
rails generate migration AddIndexToUsers name:string:index
will generate the following migration:
class AddIndexToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
add_index :users, :name
end
end
Delete add_column
line and run the migration.
In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index
command and then delete add_column
line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:
rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references
I use a variation of what jpartogi mentioned above, that I find a little shorter:
import platform
from django.core.management import execute_manager
computername = platform.node()
try:
settings = __import__(computername + '_settings')
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file '%r_settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file local_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % (computername, __file__))
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
Basically on each computer (development or production) I have the appropriate hostname_settings.py file that gets dynamically loaded.
public class MainActivity extends AppCompatActivity {
public void clickMe (View view) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
mp.start();
}
create a button with a method could be called when the button pressed (onCreate),
then create a variable for (MediaPlayer) class with the path of your file
MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
finally run start method in that class
mp.start();
the file will run when the button pressed, hope this was helpful!
An improvement to the most useful answer here:
1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network
There is no need to restart the MySQL server.
use FLUSH PRIVILEGES;
after the update mysql.user statement for password change.
The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
The --skip-grant-options
enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to
use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.
from: reference: resetting-permissions-generic
Inside the function parameter list, char arr[]
is absolutely equivalent to char *arr
, so the pair of definitions and the pair of declarations are equivalent.
void function(char arr[]) { ... }
void function(char *arr) { ... }
void function(char arr[]);
void function(char *arr);
The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.
Treat string literals as if they were static const char literal[] = "string literal";
and do not attempt to modify them.
Similar to getting the length of a dataframe, len(df)
, the following worked for pandas and blaze:
Total = sum(df['MyColumn'])
or alternatively
Total = sum(df.MyColumn)
print Total
An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.
It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.
Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.
Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.
I've added the <%%
literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <%
part of the tag which is necessary for js apps like displaying chart.js tooltips etc.
Update (Fixed broken link)
Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags
All you need is to create two layouts:
an empty layout
main layout
Then write the code below in _viewStart file:
@{
if (Request.IsAjaxRequest())
{
Layout = "~/Areas/Dashboard/Views/Shared/_emptyLayout.cshtml";
}
else
{
Layout = "~/Areas/Dashboard/Views/Shared/_Layout.cshtml";
}
}
of course, maybe it is not the best solution
When you push a new branch the first time use: >git push -u origin
After that, you can just type a shorter command: >git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
data = """a,b,c
d,e,f
g,h,i
j,k,l"""
print(data.split()) # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
str.split
, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use
print(data.split("\n")) # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
Or as @Ashwini Chaudhary suggested in the comments, you can use
print(data.splitlines())
I'm using jquery datepicker to select date. My directive read date and convert it to json date format (in milliseconds) store in ng-model
data while display formatted date.and reverse if ng-model have json date (in millisecond) my formatter display in my format as jquery datepicker.
Html Code:
<input type="text" jqdatepicker ng-model="course.launchDate" required readonly />
Angular Directive:
myModule.directive('jqdatepicker', function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
var ar=date.split("/");
date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]);
ngModelCtrl.$setViewValue(date.getTime());
scope.$apply();
}
});
ngModelCtrl.$formatters.unshift(function(v) {
return $filter('date')(v,'dd/MM/yyyy');
});
}
};
});
You can use unicode for this in CSS. If you are using font awesome 5, this is the syntax;
.login::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f007";
}
You can see their documentation here.
I suggest to use sticky js it's have best option ever i have seen. nothing to do just ad this js on you
https://raw.githubusercontent.com/garand/sticky/master/jquery.sticky.js
and use below code :
<script>
$(document).ready(function(){
$("#sticker").sticky({topSpacing:0});
});
</script>
Its git repo: https://github.com/garand/sticky
You should remove navbar-fixed-top
class otherwise navbar stays fixed on top of page where you want logo.
If you want to place logo inside navbar:
Navbar height (set in @navbarHeight
LESS variable) is 40px
by default. Your logo has to fit inside or you have to make navbar higher first.
Then use brand
class:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
</div>
</div>
</div>
If your logo is higher than 20px
, you have to fix stylesheets as well.
If you do that in LESS:
.navbar .brand {
@elementHeight: 32px;
padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}
@elementHeight
should be set to your image height.
Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52
Alternatively you can calculate padding values yourself and use pure CSS.
This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
Just echo
the first list of your source file into your target file.
echo $(head -n 1 source.txt) > target.txt
The Kotlin Way
fun showPopupMenu(view: View) {
PopupMenu(view.context, view).apply {
menuInflater.inflate(R.menu.popup_men, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
true
}
}.show()
}
UPDATE: In the above code, the apply function returns this
which is not required, so we can use run
which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.
Even Simpler:
fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
menuInflater.inflate(R.menu.popup_men, menu)
setOnMenuItemClickListener { item ->
Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
true
}
show()
}
You can revert individual commits with:
git revert <commit_hash>
This will create a new commit which reverts the changes of the commit you specified. Note that it only reverts that specific commit and not commits after that. If you want to revert a range of commits, you can do it like this:
git revert <oldest_commit_hash>..<latest_commit_hash>
It reverts the commits between and including the specified commits.
To know the hash of the commit(s) you can use git log
Look at the git-revert man page for more information about the git revert
command. Also, look at this answer for more information about reverting commits.
You can do this with wget usually. wget --content-disposition
"url" additionally if you add -O /dev/null
you will not be actually saving the file.
wget -O /dev/null --content-disposition example.com
There are already some very great answers but I'm posting a new one to emphasize my observation on case III below about what happens when you have an explicit return statement in a function which you are new
ing up. Have a look at below cases:
Case I:
var Foo = function(){
this.A = 1;
this.B = 2;
};
console.log(Foo()); //prints undefined
console.log(window.A); //prints 1
Above is a plain case of calling the anonymous function pointed by Foo
. When you call this function it returns undefined
. Since there is no explicit return statement so JavaScript interpreter forcefully inserts a return undefined;
statement in the end of the function. Here window is the invocation object (contextual this
) which gets new A
and B
properties.
Case II:
var Foo = function(){
this.A = 1;
this.B = 2;
};
var bar = new Foo();
console.log(bar()); //illegal isn't pointing to a function but an object
console.log(bar.A); //prints 1
Here JavaScript interpreter seeing the new
keyword creates a new object which acts as the invocation object (contextual this
) of anonymous function pointed by Foo
. In this case A
and B
become properties on the newly created object (in place of window object). Since you don't have any explicit return statement so JavaScript interpreter forcefully inserts a return statement to return the new object created due to usage of new
keyword.
Case III:
var Foo = function(){
this.A = 1;
this.B = 2;
return {C:20,D:30};
};
var bar = new Foo();
console.log(bar.C);//prints 20
console.log(bar.A); //prints undefined. bar is not pointing to the object which got created due to new keyword.
Here again JavaScript interpreter seeing the new
keyword creates a new object which acts as the invocation object (contextual this
) of anonymous function pointed by Foo
. Again, A
and B
become properties on the newly created object. But this time you have an explicit return statement so JavaScript interpreter will not do anything of its own.
The thing to note in case III is that the object being created due to new
keyword got lost from your radar. bar
is actually pointing to a completely different object which is not the one which JavaScript interpreter created due to new
keyword.
Quoting David Flanagan from JavaScripit: The Definitive Guide (6th Edition),Ch. 4, Page # 62:
When an object creation expression is evaluated, JavaScript first creates a new empty object, just like the one created by the object initializer {}. Next, it invokes the specified function with the specified arguments, passing the new object as the value of the this keyword. The function can then use this to initialize the properties of the newly created object. Functions written for use as constructors do not return a value, and the value of the object creation expression is the newly created and initialized object. If a constructor does return an object value, that value becomes the value of the object creation expression and the newly created object is discarded.
---Additional Info---
The functions used in code snippet of above cases have special names in JS world as below:
Case I and II - Constructor function
Case III - Factory function. Factory functions shouldn't be used with new
keyword which I've done to explain the concept in current thread.
You can read about difference between them in this thread.
I find it easier using this formula
=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")
Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.
Hope it helps
One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"
edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.
Set the property of your DataGridView:
Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill
[Joke mode on]
You can fix this by adding this:
https://github.com/donavon/undefined-is-a-function
import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.
[joke mode off]
The question has been answered fully, I don't want to go into details. I want to share the usage when writing numerical computation in rust.
There is an example of a lambda(anonymous function)
let f = |x: f32| -> f32 { x * x - 2.0 };
let df = |x: f32| -> f32 { 2.0 * x };
When I was writing a module of Newton–Raphson method, it was used as first and second order derivative. (If you want to know what is Newton–Raphson method, please visit "https://en.wikipedia.org/wiki/Newton%27s_method".
The output as the following
println!("f={:.6} df={:.6}", f(10.0), df(10.0))
f=98.000000 df=20.000000
As @MeBigFatGuy says, except you can make your static {...}
block use a loop over the values()
collection:
static {
for (PcapLinkType type : PcapLinkType.values()) {
intToTypeMap.put(type.getValue(), type);
}
}
I think you can use a sprintf :
int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);
This will remove any number of blank lines
CTRL + H to replace
Select Extended search mode
replace all \r\n
with (space)
then switch to regular expression and replace all \s+
with \n
Here's a function that will do the trick:
def myformat(x):
return ('%.2f' % x).rstrip('0').rstrip('.')
And here are your examples:
>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'
Edit:
From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,
'%.3g' % x
works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.
Using the system
scope. ${basedir}
is the directory of your pom.
<dependency>
<artifactId>..</artifactId>
<groupId>..</groupId>
<scope>system</scope>
<systemPath>${basedir}/lib/dependency.jar</systemPath>
</dependency>
However it is advisable that you install your jar in the repository, and not commit it to the SCM - after all that's what maven tries to eliminate.
Did you try export
directive of Make itself (assuming that you use GNU Make)?
export PATH := bin:$(PATH)
test all:
x
Also, there is a bug in you example:
test all:
PATH=bin:${PATH}
@echo $(PATH)
x
First, the value being echo
ed is an expansion of PATH
variable performed by Make, not the shell. If it prints the expected value then, I guess, you've set PATH
variable somewhere earlier in your Makefile, or in a shell that invoked Make. To prevent such behavior you should escape dollars:
test all:
PATH=bin:$$PATH
@echo $$PATH
x
Second, in any case this won't work because Make executes each line of the recipe in a separate shell. This can be changed by writing the recipe in a single line:
test all:
export PATH=bin:$$PATH; echo $$PATH; x
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
double d = 1.234;
int i = Convert.ToInt32(d);
Handles rounding like so:
rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
In Bourne shell(sh), use the . command to source a file
. filename
Insert array data into mysql php
I Have array data.. I want post that data in database
1: this is my array data:
stdClass Object
(
[questions] => Array
(
[0] => stdClass Object
(
[question_id] => 54
[question] => Which%20of%20the%20following%20is%20a%20rational%20number%20(s)%3F%3Cbr%20%2F%3E%0D%0A%3Cbr%20%2F%3E
[option_1] => %3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F010779c34ce28fee25778247e127b82d.png%22%20alt%3D%22%22%20%2F%3E%3Cspan%20class%3D%22Apple-tab-span%22%20style%3D%22white-space%3A%20pre%3B%20%22%3E%09%3C%2Fspan%3E
[option_2] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F3af35a16c371ffaaf9ea6891fb732478.png%22%20alt%3D%22%22%20%2F%3E
[option_3] => %26nbsp%3B%3Cimg%20align%3D%22middle%22%20%20%20src%3D%22formula%2F54%2F4a57d5766a79f0ddf659d63c7443982b.png%22%20alt%3D%22%22%20%2F%3E
[option_4] => %26nbsp%3BAll%20the%20above%26nbsp%3B
[iscorrect] => yes
[answerGiven] => D
[marksobtain] => 2
[timetaken] => 3
[difficulty_levelval] => 2
)
[1] => stdClass Object
(
[question_id] => 58
[question] => %3Cdiv%3EIf%20A%20%26nbsp%3B%3A%20Every%20whole%20number%20is%20a%20natural%20number%20and%3C%2Fdiv%3E%0D%0A%3Cdiv%3E%26nbsp%3B%20%26nbsp%3BR%20%3A%200%20is%20not%20a%20natural%20number%2C%3C%2Fdiv%3E%0D%0A%3Cdiv%3EThen%20which%20of%20the%20following%20statement%20is%20true%3F%3C%2Fdiv%3E
[option_1] => %26nbsp%3BA%20is%20False%20and%20R%20is%20true.
[option_2] => A%20is%20True%20and%20R%20is%20the%20correct%20explanation%20of%20A
[option_3] => %26nbsp%3BA%20is%20True%20and%20R%20is%20false
[option_4] => %26nbsp%3BBoth%20A%20and%20R%20are%20True
[iscorrect] => no
[answerGiven] => D
[marksobtain] => 0
[timetaken] => 2
[difficulty_levelval] => 2
)
)
)
code used i used to insert that data:
Code ::
<?php
//require_once("config_new2012.php");
require("codelibrary/fb/facebook.php");
include("codelibrary/inc/variables.php");
include_once(INC."functions.php");
include_once(CLASSES."frontuser_class.php");
include_once(CLASSES."testdetails_class.php");
$data = file_get_contents('php://input');
$arr_data = explode("=",$data);
$final_data = urldecode($arr_data[1]);
$final_data2 = json_decode($final_data);
//print_r ($final_data2);
if(is_array($final_data2)){
echo 'i am in array ';
$sql = "INSERT INTO p_user_test_details(question_id, question, option_1, option_2, option_3, option_4,iscorrect,answerGiven,marksobtain,timetaken,difficulty_levelval) values ";
$valuesArr = array();
foreach($final_data2 as $row){
$question_id = (int) $row['question_id'];
$question = mysql_real_escape_string( $row['question'] );
$option_1 = mysql_real_escape_string( $row['option_1'] );
$option_2 = mysql_real_escape_string( $row['option_2'] );
$option_3 = mysql_real_escape_string( $row['option_3'] );
$option_4 = mysql_real_escape_string( $row['option_4'] );
$iscorrect = mysql_real_escape_string( $row['iscorrect'] );
$answerGiven = mysql_real_escape_string( $row['answerGiven'] );
$marksobtain = mysql_real_escape_string( $row['marksobtain'] );
$timetaken = mysql_real_escape_string( $row['timetaken'] );
$difficulty_levelval = mysql_real_escape_string( $row['difficulty_levelval'] );
$valuesArr[] = "('$question_id', '$question', '$option_1','$option_2','$option_3','$option_4','$iscorrect','$answerGiven','$marksobtain','$timetaken','$difficulty_levelval')";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql) or exit(mysql_error());
}
else{
echo 'no one is there ';
}
I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.
Using ${env.foo}
or ${env.FOO}
didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:
Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh
to call it from the parent script.
In shared-pom, create a command-line param that grabs the environment variable:
<plugin> ... <executions> <executions> ... <execution> ... <configuration> <param>${foo}</param> <!-- Note this is *not* ${env.foo} --> </configuration>
In com.google.code.maven-replacer-plugin, make the replacement value ${foo}
.
In my shell script that calls maven, add this to the command: -Dfoo=$foo
Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):
There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.
Note that Apache recommends using apachectl -k
as the command, and for systemd, the command is replaced by httpd -k
apachectl -k graceful
or httpd -k graceful
Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.
apachectl -k restart
or httpd -k restart
This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.
File->Settings->Appearance
There's a dropdown box with various themes.
Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.
Add this class: d-flex align-items-center
to the element
If you had this:
<div class="col-3">
change it to this:
<div class="col-3 d-flex align-items-center>
Try this function...
function calculate_age(birth_month,birth_day,birth_year)
{
today_date = new Date();
today_year = today_date.getFullYear();
today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - birth_year;
if ( today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
return age;
}
OR
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
Actually, none of the given answers are fully cover the request.
As the OP didn't provided a specific use case or types of numbers, I will try to cover all possible cases and permutations.
This number is usually called unsigned integer, but you can also call it a positive non-fractional number, include zero. This includes numbers like 0
, 1
and 99999
.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)$/
This number is usually called signed integer, but you can also call it a non-fractional number. This includes numbers like 0
, 1
, 99999
, -99999
, -1
and -0
.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)$/
As you probably noticed, I have also included -0
as a valid number. But, some may argue with this usage, and tell that this is not a real number (you can read more about Signed Zero here). So, if you want to exclude this number from this regex, here's what you should use instead:
/^-?(0|[1-9]\d*)(?<!-0)$/
All I have added is (?<!-0)
, which means not to include -0
before this assertion. This (?<!...)
assertion called negative lookbehind, which means that any phrase replaces the ...
should not appear before this assertion. Lookbehind has limitations, like the phrase cannot include quantifiers. That's why for some cases I'll be using Lookahead instead, which is the same, but in the opposite way.
Many regex flavors, including those used by Perl and Python, only allow fixed-length strings. You can use literal text, character escapes, Unicode escapes other than
\X
, and character classes. You cannot use quantifiers or backreferences. You can use alternation, but only if all alternatives have the same length. These flavors evaluate lookbehind by first stepping back through the subject string for as many characters as the lookbehind needs, and then attempting the regex inside the lookbehind from left to right.
You can read more bout Lookaround assertions here.
This number is usually called unsigned float or unsigned double, but you can also call it a positive fractional number, include zero. This includes numbers like 0
, 1
, 0.0
, 0.1
, 1.0
, 99999.000001
, 5.10
.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)(\.\d+)?$/
Some may say, that numbers like .1
, .0
and .00651
(same as 0.1
, 0.0
and 0.00651
respectively) are also valid fractional numbers, and I cannot disagree with them. So here is a regex that is additionally supports this format:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
This number is usually called signed float or signed double, but you can also call it a fractional number. This includes numbers like 0
, 1
, 0.0
, 0.1
, 1.0
, 99999.000001
, 5.10
, -0
, -1
, -0.0
, -0.1
, -99999.000001
, 5.10
.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)(\.\d+)?$/
For non -0
believers:
/^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/
For those who want to support also the invisible zero representations, like .1
, -.1
, use the following regex:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
The combination of non -0
believers and invisible zero believers, use this regex:
/^(?!-0?(\.0+)?$)-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
Some may want to support in their validations, numbers with a scientific character e
, which is by the way, an absolutely valid number, it is created for shortly represent a very long numbers. You can read more about Scientific Notation here. These numbers are usually looks like 1e3
(which is 1000
), 1e-3
(which is 0.001) and are fully supported by many major programming languages (e.g. JavaScript). You can test it by checking if the expression '1e3'==1000
returns true
.
I will divide the support for all the above sections, including numbers with scientific notation.
Whole positive number regex validation, supports numbers like 6e4
, 16e-10
, 0e0
but also regular numbers like 0
, 11
:
/^(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Whole positive and negative number regex validation, supports numbers like -6e4
, -16e-10
, -0e0
but also regular numbers like -0
, -11
and all the whole positive numbers above:
/^-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Whole positive and negative number regex validation for non -0
believers, same as the above, except now it forbids numbers like -0
, -0e0
, -0e5
and -0e-6
:
/^(?!-0)-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Positive number regex validation, supports also the whole numbers above, plus numbers like 0.1e3
, 56.0e-3
, 0.0e10
and 1.010e0
:
/^(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Positive number with invisible zero support regex validation, supports also the above positive numbers, in addition numbers like .1e3
, .0e0
, .0e-5
and .1e-7
:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Negative and positive number regex validation, supports the positive numbers above, but also numbers like -0e3
, -0.1e0
, -56.0e-3
and -0.0e10
:
/^-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Negative and positive number regex validation fro non -0
believers, same as the above, except now it forbids numbers like -0
, -0.00000
, -0.0e0
, -0.00000e5
and -0e-6
:
/^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Negative and positive number with invisible zero support regex validation, supports also the above positive and negative numbers, in addition numbers like -.1e3
, -.0e0
, -.0e-5
and -.1e-7
:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Negative and positive number with the combination of non -0
believers and invisible zero believers, same as the above, but forbids numbers like -.0e0
, -.0000e15
and -.0e-19
:
/^(?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
In many programming languages, string representation of hexadecimal number like 0x4F7A
may be easily cast to decimal number 20346
.
Thus, one may want to support it in his validation script.
The following Regular Expression supports only hexadecimal numbers representations:
/^0x[0-9a-f]+$/i
These final Regular Expressions, support the invisible zero numbers.
/^(-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
/^((?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
Hope I covered all number permutations that are supported in many programming languages.
Good luck!
Oh, forgot to mention, that those who want to validate a number includes a thousand separator, you should clean all the commas (,
) first, as there may be any type of separator out there, you can't actually cover them all.
But you can remove them first, before the number validation:
//JavaScript
function clearSeparators(number)
{
return number.replace(/,/g,'');
}
Yes, via the text-overflow
property in CSS 3. Caveat: it is not universally supported yet in browsers.
Prior to PHP 5.2.0 and above you should use filter_input()
which is especially created for that to get a specific external user inputs such as get, post or cookie variables by name and optionally filters it to avoid any XSS/Injection attacks on your site. For example:
$user = filter_input(INPUT_POST, 'username');
You may use one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
By using optional 3rd argument, you can extend it by variety of filters (for validating, sanitizing, filtering or other), e.g. FILTER_SANITIZE_SPECIAL_CHARS
, FILTER_SANITIZE_ENCODED
, etc.
For example:
<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>
The syntax is:
mixed
filter_input
( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )(PHP 5 >= 5.2.0, PHP 7)
See also: Why is better to use filter_input()?
net stop <your service> && net start <your service>
No net restart
, unfortunately.
You can also use this notation in your own custom classes to make it do whatever you want
class C(object):
def __getitem__(self, k):
return k
# Single argument is passed directly.
assert C()[0] == 0
# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)
# Slice notation generates a slice object.
assert C()[1:2:3] == slice(1, 2, 3)
# If you omit any part of the slice notation, it becomes None.
assert C()[:] == slice(None, None, None)
assert C()[::] == slice(None, None, None)
assert C()[1::] == slice(1, None, None)
assert C()[:2:] == slice(None, 2, None)
assert C()[::3] == slice(None, None, 3)
# Tuple with a slice object:
assert C()[:, 1] == (slice(None, None, None), 1)
# Ellipsis class object.
assert C()[...] == Ellipsis
We can then open up slice objects as:
s = slice(1, 2, 3)
assert s.start == 1
assert s.stop == 2
assert s.step == 3
This is notably used in Numpy to slice multi-dimensional arrays in any direction.
Of course, any sane API should use ::3
with the usual "every 3" semantic.
The related Ellipsis
is covered further at: What does the Ellipsis object do?
helloworld.png: file not recognized: File format not recognized
Obviously, you should format your hard drive.
Really, these errors aren't that hard to read.
On Mac after installing Android Studio IDE android-studio-ide-173.4907809-mac.dmg
and using studio SDK Manager to install SDK Tools
Add to your PATH using ~/.profile
or ~/.bash_profile
and make sure you have $ANDROID_HOME/emulator
in your $PATH
before $ANDROID_HOME/tools
like so:
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
alias androidemulator='emulator -avd Nexus_5X_API_28_x86'
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
Simple solution
source='category.name'
where category
is foreign key and .name
it's attribute.
from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item
class ItemSerializer(ModelSerializer):
category_name = ReadOnlyField(source='category.name')
class Meta:
model = Item
fields = "__all__"
Ctrl+A, Ctrl+K to wipe the current line in the terminal. You can then recall it with Ctrl+Y if you need.
From commons-lang3
org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)
I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:
UPDATE FUNCTIONS A
INNER JOIN (
SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
FROM TAX BB, FUNCTIONS AA
WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
GROUP BY AA.Func_ID
) B
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code
Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:
UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code
However, this still doesn't work.
I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:
UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
"MinOfTax_Code",
"FUNCTIONS_TAX",
"Func_ID = '" & Func_ID & "'"
)
Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).
Good luck!
It can be as simple as that:
const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);
Quoting MDN:
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
The
reduce()
method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
from Array.prototype.reduce()
on MDN
You can use this function like that:
sumValues({a: 4, b: 6, c: -5, d: 0}); // gives 5
Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.
Besides CMAKE_GENERATOR_PLATFORM
variable, there is also the -A
switch
cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64
https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection
-A <platform-name> = Specify platform name if supported by
generator.
The GMaps Utility Library has a plugin called MapIconMaker that makes it easy to generate different marker styles on the fly. It uses Google Charts to draw the markers.
There's a good demo here that shows what kind of markers you can make with it.
first of all, we have to make sure that you have downloaded and installed the JDK. In order to download it click on the following link
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
(Do not forget to check "Accept License Agreement", before you choose the version you want to download)
For Windows OS 32-Bit (x86) choose "jdk-8u77-windows-i586.exe"
For Windows OS 64-Bit (x64) choose "jdk-8u77-windows-x64.exe"
Install the file that is going to be downloaded. During the installation, pay attention, because you have to keep the installation path.
When you have done so, the last thing to do, is to define two "Environment Variables".
The first "Environmental Variable" name should be:
JAVA_HOME
and its value should be the installation path
(for example: C:\Program Files\Java\jdk1.8.0_77
)
The second "Environmental Variable" name should be:
JRE_HOME
and its value should be the installation path
(for example C:\Program Files\Java\jre8
)
As soon as you have defined the Environment Variables, you can go to command prompt (cdm) and run from every path your preferred "java.exe" commands. Your command line can now recognize your "java.exe" commands.
:)
P.S.: In order to define "Environment Variable", make a right click on "This PC" and select "properties" from the menu. Then the "System" window will appear and you have to click on "Advanced system settings". As a consequence "System properties" window shows. Select the "Advanced" tab and click on "Environment Variables" button. You can now define the aforementioned variables and you're done
Instead of getting image row by row, you can put it directly to an array. For CV_8U type image, you can use byte array, for other types check here.
Mat img; // Should be CV_8U for using byte[]
int size = (int)img.total() * img.channels();
byte[] data = new byte[size];
img.get(0, 0, data); // Gets all pixels
Something like this worked for me. I am guessing this should work for you.
Run webpack-dev using this
webpack-dev-server --host 0.0.0.0 --port 80
And set this in webpack.config.js
entry: [
'webpack-dev-server/client?http://0.0.0.0:80',
config.paths.demo
]
Note If you are using hot loading, you will have to do this.
Run webpack-dev using this
webpack-dev-server --host 0.0.0.0 --port 80
And set this in webpack.config.js
entry: [
'webpack-dev-server/client?http://0.0.0.0:80',
'webpack/hot/only-dev-server',
config.paths.demo
],
....
plugins:[new webpack.HotModuleReplacementPlugin()]
This might work for you...
<script type="text/javascript">
function image(img) {
var src = img.src;
window.open(src);
}
</script>
<img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" onclick="image(this)">
https://github.com/loic-sharma/profiler this is good example for alternative to laravel3 debug bar.
Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:
render = () => null
This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render
function and this is the most concise form satisfying this requirement that I can think of.
I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router
documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.
You can also do linking almost normally:
<a href="#" onclick="window.location='URL_TO_GO';">TEXT OF THE LINK</a>
And you can remove the hash tag and href, everything it does it affects appearance..
For those still experimenting, npm install react-html-parser
When I installed it it had 123628 weekly downloads.
import ReactHtmlParser from 'react-html-parser'
<div>{ReactHtmlParser(htmlString)}</div>