Those are users. Check your /etc/passwd
.
cd ~username
takes you to that user's home directory.
If the label
immediately follows a specified input
element:
input#example + label { ... }
input:checked + label { ... }
You could use os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')
or as I did it,
os.system('cp '+ rawfile + ' rawdata.dat')
where rawfile
is the name that I had generated inside the program.
This is a Linux only solution
just to improve answer given above: if you are getting NullPointerEx:
you can also use getApplicationContext() without context
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
Just add this section to Web.config, and all requests to the route/{*pathInfo} will be handled by the specified handler, even when there are dots in pathInfo. (taken from ServiceStack MVC Host Web.config example and this answer https://stackoverflow.com/a/12151501/801189)
This should work for both IIS 6 & 7. You could assign specific handlers to different paths after the 'route' by modifying path="*" in 'add' elements
<location path="route">
<system.web>
<httpHandlers>
<add path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" />
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ApiURIs-ISAPI-Integrated-4.0" path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</location>
This is from the Docker documentation itself, might be of help, simple and plain:
"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".
Solved
Model
public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}
Controller
public class BookController : Controller
{
[HttpPost]
public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
{
throw new NotImplementedException();
}
}
And View
@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.EditorFor(m => m)
<input type="file" name="fileUpload[0]" /><br />
<input type="file" name="fileUpload[1]" /><br />
<input type="file" name="fileUpload[2]" /><br />
<input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}
Note title of parameter from controller action must match with name of input elements
IEnumerable<HttpPostedFileBase> fileUpload
-> name="fileUpload[0]"
fileUpload
must match
Set the application pool to 2.0, I did it and worked.
My opinion is C# and ASP.NET would be the best of the three for development that is web biased.
I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.
I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.
The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).
Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.
So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.
Another option is YADDRESS.
There is a better way to write polar(), here it is:
def polar(x,y):
`returns r, theta(degrees)`
return math.hypot(x,y),math.degrees(math.atan2(y,x))
Download codeblocks-13.12mingw-setup.exe instead of codeblocks-13.12setup.exe from the official site. Here 13.12 is the latest version so far.
Nowadays, code to do this should look something like:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.keyCode == 8) {
console.log('BACKSPACE was pressed');
// Call event.preventDefault() to stop the character before the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
if (event.keyCode == 46) {
console.log('DELETE was pressed');
// Call event.preventDefault() to stop the character after the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
});
although in the future, once they are broadly supported in browsers, you may want to use the .key
or .code
attributes of the KeyboardEvent
instead of the deprecated .keyCode
.
Details worth knowing:
Calling event.preventDefault()
in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document
instead of a text field).
Documentation on how the value of the keyCode
attribute is determined can be found in section B.2.1 How to determine keyCode
for keydown
and keyup
events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.
There is an effort underway to deprecate the .keyCode
attribute in favour of .key
and .code
. The W3 describe the .keyCode
property as "legacy", and MDN as "deprecated".
One benefit of the change to .key
and .code
is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace"
and "Delete"
and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.
On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.
The .key
attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete"
. The .code
attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace"
.
Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode
attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.code == 'Delete') {
console.log('The physical key pressed was the DELETE key');
}
if (event.code == 'Backspace') {
console.log('The physical key pressed was the BACKSPACE key');
}
if (event.key == 'Delete') {
console.log('The keypress meant the same as pressing DELETE');
// This can happen for one of two reasons:
// 1. The user pressed the DELETE key
// 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
// FN+BACKSPACE deletes the character in front of the text cursor,
// instead of the one behind it.
}
if (event.key == 'Backspace') {
console.log('The keypress meant the same as pressing BACKSPACE');
}
});
Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.
On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:
=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))
Hit OK then close the "Name Manager" window.
Now, in cell A1 enter the following:
=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))
This will return FQS for red and SM for yellow. For any other color the cell will remain blank.
***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).
Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html
Cheers.
::Edit::
The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).
Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:
=GET.CELL(63,Sheet1!B2)
Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.
Also remember that in general an id is more specific than a class is more specific than an element.
Hope that helps.
-Rick
Assignment expressions from PEP 572 (new in Python 3.8) offer yet another way to solve this:
time_interval = [4, 6, 12]
total_time = 0
cum_time = [total_time := total_time + t for t in time_interval]
Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.
First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService
, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean>
-definition for the UserService-implementation.
If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package=
-value).
Assuming you only have the list of items and a list of true/required indices, this should be the fastest:
property_asel = [ property_a[index] for index in good_indices ]
This means the property selection will only do as many rounds as there are true/required indices. If you have a lot of property lists that follow the rules of a single tags (true/false) list you can create an indices list using the same list comprehension principles:
good_indices = [ index for index, item in enumerate(good_objects) if item ]
This iterates through each item in good_objects (while remembering its index with enumerate) and returns only the indices where the item is true.
For anyone not getting the list comprehension, here is an English prose version with the code highlighted in bold:
list the index for every group of index, item that exists in an enumeration of good objects, if (where) the item is True
I am a little late to party but you may want to consider using GetAwaiter.GetResult() to run your async code in sync context but as paralled as below;
Parallel.ForEach(ids, i =>
{
ICustomerRepo repo = new CustomerRepo();
// Run this in thread which Parallel library occupied.
var cust = repo.GetCustomer(i).GetAwaiter().GetResult();
customers.Add(cust);
});
Here is the details from laravel.com
http://laravel.com/docs/eloquent#soft-deleting
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete
property on the model:
class User extends Eloquent {
protected $softDelete = true;
}
To add a deleted_at column to your table, you may use the softDeletes
method from a migration:
$table->softDeletes();
Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.
Had this and my .gitignore was inside my project folder, but the main git folders were at the solution level. Moving .gitignore out to the solution/git level folders worked. Still not sure how it got there but...
Create a function and pass out put parameter as of generic type.
public static T some_function<T>(T out_put_object /*declare as Output object*/)
{
return out_put_object;
}
You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.
Here is small piece of code:
NSArray* tempVCA = [self.navigationController viewControllers];
for(UIViewController *tempVC in tempVCA)
{
if([tempVC isKindOfClass:[urViewControllerClass class]])
{
[tempVC removeFromParentViewController];
}
}
I think this will make your work easier.
What a bout StatePattern. Does that fit your needs?
I think its context related, but its worth a shot for sure.
http://en.wikipedia.org/wiki/State_pattern
This let your states decide where to go and not the "object" class.
Bruno
To anyone else who ended up here while searching for info on how to decode a string encoded with Base64.encodeBytes()
, here was my solution:
// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());
// decode
String ps2 = "dGVjaFBhC3M=";
byte[] tmp2 = Base64.decode(ps2);
String val2 = new String(tmp2, "UTF-8");
Also, I'm supporting older versions of Android so I'm using Robert Harder's Base64 library from http://iharder.net/base64
To undo git checkout
do git checkout -
, similarly to cd
and cd -
in shell.
To quote a quote:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
.data()
- jQuery Documentiation
Note that this (Frankly odd) limitation is only withheld to the use of .data()
.
The solution? Use .attr
instead.
Of course, several of you may feel uncomfortable with not using it's dedicated method. Consider the following scenario:
Common sense - Why would they change an already established attribute like that? Just imagine class
begin renamed to group and id
to identifier. The Internet would break.
And even then, Javascript itself has the ability to fix this - And of course, despite it's infamous incompatibility with HTML, REGEX (And a variety of similar methods) could rapidly rename your attributes to this new-mythical 'standard'.
TL;DR
alert($(targetField).attr("data-helptext"));
DELETE t.* FROM test t WHERE t.name = 'foo' LIMIT 1
@Andre If I understood what you are asking, I think the only thing missing is the t.* before FROM
.
SWIFT 3.01
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "Conversation_VC") as! Conversation_VC
self.navigationController?.pushViewController(secondViewController, animated: true)
For the sake of snippet of what the guys have explained above:
import socket
from contextlib import closing
def find_free_port():
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
javac only compiles the code. You need to use java command to run the code. The error is because your classpath doesn't contain the class Subclass iwhen you tried to compile it. you need to add them with the -cp variable in javac command
java -cp classpath-entries mainjava arg1 arg2
should run your code with 2 arguments
For ASP.NET try this:
<script type="text/javascript">
Sys.Application.add_load(function() { ... });
</script>
This appears to work on page load and on update panel load
Please find the full discussion here.
The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.
Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.
You can import one of them using import. For all other similar class , you need to specify Fully qualified class names. Otherwise you will get compilation error.
Eg:
import java.util.Date;
class Test{
public static void main(String [] args){
// your own date
my.own.Date myOwndate ;
// util.Date
Date utilDate;
}
}
I think your best bet would be to use a combination of absolute and relative positioning.
Here's a fiddle: http://jsfiddle.net/PKVza/2/
given your html:
<div class="row">
<div class="col-sm-6">
<img src="~/Images/MyLogo.png" alt="Logo" />
</div>
<div class="bottom-align-text col-sm-6">
<h3>Some Text</h3>
</div>
</div>
use the following CSS:
@media (min-width: 768px ) {
.row {
position: relative;
}
.bottom-align-text {
position: absolute;
bottom: 0;
right: 0;
}
}
EDIT - Fixed CSS and JSFiddle for mobile responsiveness and changed the ID to a class.
After lots of tests, following code works for me in Typescreipt
export function ReplaceNewline(input: string) {
var newline = String.fromCharCode(13, 10);
return ReplaceAll(input, "<br>", newline.toString());
}
export function ReplaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
var test = parseInt($("#testid").val());
All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to use the Camera 2 API:
This class was deprecated in API level 21. We recommend using the new android.hardware.camera2 API for new applications.
In the newer API you have almost complete power over the Android device camera and documentation explicitly advice to
String[] getCameraIdList()
and then use obtained CameraId to open the camera:
void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)
99% of the frontal cameras have id = "1", and the back camera id = "0" according to this:
Non-removable cameras use integers starting at 0 for their identifiers, while removable cameras have a unique identifier for each individual device, even if they are the same model.
However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embedded cameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more important than frontal.
I don't know about a uniform method to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".
Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html
Explicit Examples: https://github.com/googlesamples/android-Camera2Basic
For the older API (it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same Integer CameraID (1) to open frontal camera like in this answer:
cam = Camera.open(1);
If you trust OpenCV to do the camera part:
Inside
<org.opencv.android.JavaCameraView
../>
use the following for the frontal camera:
opencv:camera_id="1"
For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.
Next, check that your current module is the correct renamed module and not the old one.
origin/xxx
branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).
What you need to do to update the remote is to force push your local changes to master:
git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master
What's wrong with using Git For Windows? From the repo view, there's an icon of the branch you're in (at the top), and if you click on manage you can drag&drop in a very visual and convenient way.
While the accepted answer will work most of the times, I have encountered (still do not know why) some cases that is does not. A slight modification of the query by using the WITH OVERRIDE
in RECONFIGURE
gives the solution
Use Master
GO
EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO
The expected output is
Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
For .NET 2.0:
list.Find(delegate(Item i) { return i.Property == someValue; });
Here i get the answer for that question . After searching for too long finally i get to crack the key and password for this . I forget my key and alias also the jks file but fortunately i know the bunch of password what i had put in it . but finding correct combinations for that was toughest task for me .
Solution - Download this - Keytool IUI version 2.4.1 plugin
the window will pop up now it show the alias name ..if you jks file is correct .. right click on alias and hit "view certificates chain ".. it will show the SHA1 Key .. match this key with tha key you get while you was uploading the apk in google app store ...
if it match then you are with the right jks file and alias ..
now lucky i have bunch of password to match ..
now go to this scrren put the same jks path .. and password(among the password you have ) put any path in "Certificate file"
if the screen shows any error then password is not matching .. if it doesn't show any error then it means you are with correct jks file . correct alias and password() now with that you can upload your apk in play store :)
def jsonFile = new File('File Path');
JsonSlurper jsonSlurper = new JsonSlurper();
def parseJson = jsonSlurper.parse(jsonFile)
String json = JsonOutput.toJson(parseJson)
def prettyJson = JsonOutput.prettyPrint(json)
println(prettyJson)
The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).
To initialize an list with 60 zeros you do:
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));
If you want to create a list with 60 different objects, you could use the Stream API with a Supplier
as follows:
List<Person> persons = Stream.generate(Person::new)
.limit(60)
.collect(Collectors.toList());
You could use the arrays CopyTo()
method.
Or with LINQ you can use Skip()
and Take()
...
byte[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
var subset = arr.Skip(2).Take(2);
Since a for
loop is a statement (as is print
, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write
method on sys.stdout
along with the join
method.
x = lambda x: sys.stdout.write("\n".join(x) + "\n")
Swift 4.0
self.messageLabel = UILabel(frame: CGRect(x: 70, y: 60, width:UIScreen.main.bounds.width - 80, height: 30)
messageLabel.text = message
messageLabel.lineBreakMode = .byWordWrapping //in versions below swift 3 (messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping)
messageLabel.numberOfLines = 0 //To write any number of lines within a label scope
messageLabel.textAlignment = .center
messageLabel.textColor = UIColor.white
messageLabel.font = messageLabel.font.withSize(12)
messageLabel.sizeToFit()
Blockquote NSParagraphStyle.LineBreakMode, apply to entire paragraphs, not words within paragraphs.This property is in effect both during normal drawing and in cases where the font size must be reduced to fit the label’s text in its bounding box. This property is set to byTruncatingTail by default.
If you do the call several times you can use the new method handles introduced in Java 7. Here we go for your method returning a String:
Object obj = new Point( 100, 200 );
String methodName = "toString";
Class<String> resultType = String.class;
MethodType mt = MethodType.methodType( resultType );
MethodHandle methodHandle = MethodHandles.lookup().findVirtual( obj.getClass(), methodName, mt );
String result = resultType.cast( methodHandle.invoke( obj ) );
System.out.println( result ); // java.awt.Point[x=100,y=200]
Do configure --help
and see what other options are available.
It is very common to provide different options to override different locations. By standard, --prefix
overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.
The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:
./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc
I believe that should do it.
In C, a "stream" is an abstraction; from the program's perspective it is simply a producer (input stream) or consumer (output stream) of bytes. It can correspond to a file on disk, to a pipe, to your terminal, or to some other device such as a printer or tty. The FILE
type contains information about the stream. Normally, you don't mess with a FILE
object's contents directly, you just pass a pointer to it to the various I/O routines.
There are three standard streams: stdin
is a pointer to the standard input stream, stdout
is a pointer to the standard output stream, and stderr
is a pointer to the standard error output stream. In an interactive session, the three usually refer to your console, although you can redirect them to point to other files or devices:
$ myprog < inputfile.dat > output.txt 2> errors.txt
In this example, stdin
now points to inputfile.dat
, stdout
points to output.txt
, and stderr
points to errors.txt
.
fprintf
writes formatted text to the output stream you specify.
printf
is equivalent to writing fprintf(stdout, ...)
and writes formatted text to wherever the standard output stream is currently pointing.
sprintf
writes formatted text to an array of char
, as opposed to a stream.
The best bet with these types of questions is to see exactly what python does. The dis
module is incredibly informative:
>>> import dis
>>> dis.dis("val != None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 3 (!=)
6 RETURN_VALUE
>>> dis.dis("not (val is None)")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("val is not None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None)
and uses the is not
operator. The first uses the !=
operator when comparing with None
.
As pointed out by other answers, using !=
when comparing with None
is a bad idea.
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
One way, making the preprocessor do the work. It also ensures your enums and strings are in sync.
#define FOREACH_FRUIT(FRUIT) \
FRUIT(apple) \
FRUIT(orange) \
FRUIT(grape) \
FRUIT(banana) \
#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,
enum FRUIT_ENUM {
FOREACH_FRUIT(GENERATE_ENUM)
};
static const char *FRUIT_STRING[] = {
FOREACH_FRUIT(GENERATE_STRING)
};
After the preprocessor gets done, you'll have:
enum FRUIT_ENUM {
apple, orange, grape, banana,
};
static const char *FRUIT_STRING[] = {
"apple", "orange", "grape", "banana",
};
Then you could do something like:
printf("enum apple as a string: %s\n",FRUIT_STRING[apple]);
If the use case is literally just printing the enum name, add the following macros:
#define str(x) #x
#define xstr(x) str(x)
Then do:
printf("enum apple as a string: %s\n", xstr(apple));
In this case, it may seem like the two-level macro is superfluous, however, due to how stringification works in C, it is necessary in some cases. For example, let's say we want to use a #define with an enum:
#define foo apple
int main() {
printf("%s\n", str(foo));
printf("%s\n", xstr(foo));
}
The output would be:
foo
apple
This is because str will stringify the input foo rather than expand it to be apple. By using xstr the macro expansion is done first, then that result is stringified.
See Stringification for more information.
You can use in this manner also
var rowId =$("#list").jqGrid('getGridParam','selrow');
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId']; // perticuler Column name of jqgrid that you want to access
This has really puzzled me for a while but this is what I found in the end.
When you call, sc.close()
in first method, it not only closes your scanner but closes your System.in
input stream as well. You can verify it by printing its status at very top of the second method as :
System.out.println(System.in.available());
So, now when you re-instantiate, Scanner
in second method, it doesn't find any open System.in
stream and hence the exception.
I doubt if there is any way out to reopen System.in
because:
public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**
The only good solution for your problem is to initiate the Scanner
in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:
main
method related code block:
Scanner scanner = new Scanner(System.in);
// Ask users for quantities
PromptCustomerQty(customer, ProductList, scanner );
// Ask user for payment method
PromptCustomerPayment(customer, scanner );
//close the scanner
scanner.close();
Your Methods:
public static void PromptCustomerQty(Customer customer,
ArrayList<Product> ProductList, Scanner scanner) {
// no more scanner instantiation
...
// no more scanner close
}
public static void PromptCustomerPayment (Customer customer, Scanner sc) {
// no more scanner instantiation
...
// no more scanner close
}
Hope this gives you some insight about the failure and possible resolution.
To get all the records where record created date is today's date Use the code after WHERE clause
WHERE CAST(Submission_date AS DATE) = CAST( curdate() AS DATE)
What you are doing will not work for root user. Maybe you are running your services as root and hence you don't get to see the change.
To increase the ulimit for root user you should replace the *
by root. *
does not apply for root user. Rest is the same as you did. I will re-quote it here.
Add the following lines to the file: /etc/security/limits.conf
root soft nofile 40000
root hard nofile 40000
And then add following line in the file: /etc/pam.d/common-session
session required pam_limits.so
This will update the ulimit for root user. As mentioned in comments, you may don't even have to reboot to see the change.
Just if someone is having this issue and hadn't done list[index, sub-index]
, you could be having the problem because you're missing a comma between two arrays in an array of arrays (It happened to me).
for loop will be iterate through index..
consider you have a list,
[5, 7, 13, 29, 65, 91]
you have using list variable called lis
. and you using same to remove..
your variable
lis = [5, 7, 13, 29, 35, 65, 91]
0 1 2 3 4 5 6
during 5th iteration,
your number 35 was not a prime so you removed it from a list.
lis.remove(y)
and then next value (65) move on to previous index.
lis = [5, 7, 13, 29, 65, 91]
0 1 2 3 4 5
so 4th iteration done pointer moved onto 5th..
thats why your loop doesnt cover 65 since its moved into previous index.
so you shouldn't reference list into another variable which still reference original instead of copy.
ite = lis #dont do it will reference instead copy
so do copy of list using list[::]
now you it will give,
[5, 7, 13, 29]
Problem is you removed a value from a list during iteration then your list index will collapse.
so you can try comprehension instead.
which supports all the iterable like, list, tuple, dict, string etc
Check out FPDF (with FPDI):
http://www.setasign.de/products/pdf-php-solutions/fpdi/
These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.
Another possible library is TCPDF: https://tcpdf.org/
Update to add a more modern library: PDF Parser
Just click on the "Build" node in the Build Output
From some reason the "Compilation failed" node just started being automatically selected and for that the description window is very unhelpful.
**
**
You can do it for macOS, too. Ok, not through code, but with some simple steps:
Actually it is a general thing not specific to electron. You can change the icon of many macOS apps like this.
A simple way is.....
#include <stdio.h>
#include <stdlib.h>
#define SHELLSCRIPT "\
#/bin/bash \n\
echo \"hello\" \n\
echo \"how are you\" \n\
echo \"today\" \n\
"
/*Also you can write using char array without using MACRO*/
/*You can do split it with many strings finally concatenate
and send to the system(concatenated_string); */
int main()
{
puts("Will execute sh with the following script :");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT); //it will run the script inside the c code.
return 0;
}
Say thanks to
Yoda @http://www.unix.com/programming/216190-putting-bash-script-c-program.html
http://developer.android.com/reference/android/location/Location.html
Look into distanceTo or distanceBetween. You can create a Location object from a latitude and longitude:
Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lon);
I would tentatively recommend using PDO for your SQL access.
Then it is only a case of changing the driver and ensuring the SQL works on the new backend. In theory. Data migration is a different issue.
Abstract database access is great.
Try data.table's :=
operator :
DT = as.data.table(df)
DT[b==0, est := (a-5)/2.533]
It's fast and short. See these linked questions for more information on :=
:
When should I use the :=
operator in data.table
"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)
So, if you want to evaluate dot literaly, I think you should put it in square brackets:
>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah [email protected] blah blah")
>>> resp.group()
'test.this'
For anyone that might be having this issue. I was building a custom MVC in PHP when I encountered this issue.
I was able to resolve this by setting my assets (css/js/images) files to an absolute path. Instead of using url like href="css/style.css" which use this entire current url to load it. As an example, if you are in http://example.com/user/5, it will try to load at http://example.com/user/5/css/style.css.
To fix it, you can add a / at the start of your asset's url (i.e. href="/css/style.css"). This will tell the browser to load it from the root of your url. In this example, it will try to load http://example.com/css/style.css.
Hope this comment will help you.
Take me to [pookie](#pookie)
should be the correct markdown syntax to jump to the anchor point named pookie.
To insert an anchor point of that name use HTML:
<a name="pookie"></a>
Markdown doesn't seem to mind where you put the anchor point. A useful place to put it is in a header. For example:
### <a name="tith"></a>This is the Heading
works very well. (I'd demonstrate here but SO's renderer strips out the anchor.)
id=
versus name=
An earlier version of this post suggested using <a id='tith' />
, using the self-closing syntax for XHTML, and using the id
attribute instead of name
.
XHTML allows for any tag to be 'empty' and 'self-closed'. That is, <tag />
is short-hand for <tag></tag>
, a matched pair of tags with an empty body. Most browsers will accept XHTML, but some do not. To avoid cross-browser problems, close the tag explicitly using <tag></tag>
, as recommended above.
Finally, the attribute name=
was deprecated in XHTML, so I originally used id=
, which everyone recognises. However, HTML5 now creates a global variable in JavaScript when using id=
, and this may not necessarily be what you want. So, using name=
is now likely to be more friendly.
(Thanks to Slipp Douglas for explaining XHTML to me, and nailer for pointing out the HTML5 side-effect — see the comments and nailer's answer for more detail. name=
appears to work everywhere, though it is deprecated in XHTML.)
If you want a quick demo and more details about how you move elements, try this link:
http://html-tuts.com/move-div-in-another-div-with-jquery
Here is a short example:
To move ABOVE an element:
$('.whatToMove').insertBefore('.whereToMove');
To move AFTER an element:
$('.whatToMove').insertAfter('.whereToMove');
To move inside an element, ABOVE ALL elements inside that container:
$('.whatToMove').prependTo('.whereToMove');
To move inside an element, AFTER ALL elements inside that container:
$('.whatToMove').appendTo('.whereToMove');
if you don't want to create an explicitly a js file but still want to test your javascript code, you can use snippets to run your JS code.
Follow the steps here:
I'm not sure what types of files you are trying to write the properties for but taglib-sharp is an excellent open source tagging library that wraps up all this functionality nicely. It has a lot of built in support for most of the popular media file types but also allows you to do more advanced tagging with pretty much any file.
EDIT: I've updated the link to taglib sharp. The old link no longer worked.
EDIT: Updated the link once again per kzu's comment.
Try to do...
DELIMITER $$
CREATE TRIGGER aumentarsalario
BEFORE INSERT
ON empregados
FOR EACH ROW
BEGIN
if (NEW.SALARIO < 900) THEN
set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
END IF;
END $$
DELIMITER ;
For a non-specific package and a more general solution you can check out pip-review, a tool that checks what packages could/should be updated.
$ pip-review --interactive
requests==0.14.0 is available (you have 0.13.2)
Upgrade now? [Y]es, [N]o, [A]ll, [Q]uit y
For those who have problem with wrong requestCode in onActivityResult
If you are calling startActivityForResult()
from your Fragment
, the requestCode is changed by the Activity that owns the Fragment.
If you want to get the correct resultCode in your activity try this:
Change:
startActivityForResult(intent, 1);
To:
getActivity().startActivityForResult(intent, 1);
ServicePointManager.ServerCertificateValidationCallback +=
(mender, certificate, chain, sslPolicyErrors) => true;
will bypass invaild ssl . Write it to your web service constructor.
I saw similar issues (particularly with depth) on some legacy projects when we were cloning that used to live on TFS. Enabling long paths resolved our issue and may be something else worth trying.
git config --system core.longpaths true
Example to get last article or any other element:
document.querySelector("article:last-child")
Assuming that you are using UTF-8 encoding:
string convert = "This is the string to be converted";
// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);
// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
ul {_x000D_
list-style-type: none;_x000D_
padding-left: 0px;_x000D_
}_x000D_
_x000D_
ul li span {_x000D_
float: left;_x000D_
width: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li><span></span> The lazy dog.</li>_x000D_
<li><span>AND</span> The lazy cat.</li>_x000D_
<li><span>OR</span> The active goldfish.</li>_x000D_
</ul>
_x000D_
Like Eoin said, you need to put a non-breaking space into your "empty" spans, but you can't assign a width to an inline element, only padding/margin so you'll need to make it float so that you can give it a width.
For a jsfiddle example, see http://jsfiddle.net/laurensrietveld/JZ2Lg/
In urls.py
you can override the 3 most important variables:
from django.contrib import admin
admin.site.site_header = 'My project' # default: "Django Administration"
admin.site.index_title = 'Features area' # default: "Site administration"
admin.site.site_title = 'HTML title from adminsitration' # default: "Django site admin"
Reference: Django documentation on these attributes.
Update a row or column of a table
$update = "UPDATE daily_patients SET queue_status = 'pending' WHERE doctor_id = $room_no and serial_number= $serial_num";
if ($con->query($update) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
You can do:
def mul_table(n,i=1):
print(n*i)
if i !=10:
mul_table(n,i+1)
mul_table(7)
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems
in the NotifyCollectionChangedEventArgs
object.
this is the perfect ObservableCollection
.
public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
#region Constructors
public ObservableCollectionEX() : base()
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(IEnumerable<T> c) : base(c)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
public ObservableCollectionEX(List<T> l) : base(l)
{
CollectionChanged += ObservableCollection_CollectionChanged;
}
#endregion
public new void Clear()
{
foreach (var item in this)
if (item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
base.Clear();
}
private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (var item in e.OldItems)
if (item != null && item is INotifyPropertyChanged i)
i.PropertyChanged -= Element_PropertyChanged;
if (e.NewItems != null)
foreach (var item in e.NewItems)
if (item != null && item is INotifyPropertyChanged i)
{
i.PropertyChanged -= Element_PropertyChanged;
i.PropertyChanged += Element_PropertyChanged;
}
}
}
private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);
public ListedItemPropertyChangedEventHandler ItemPropertyChanged;
}
first add in parent view flex:1, justifyContent: 'center', alignItems: 'center'
then in text add textAlign:'center'
This is happening because of the spaces in the current working directory that came from $(pwd)
for map volumes. So, I used docker-compose
instead.
The docker-compose.yml
file.
version: '3'
services:
react-app:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "3000:3000"
volumes:
- /app/node_modules
- .:/app
This was a long time ago, so not sure if this is still needed, but you could use @@ROWCOUNT variable to see how many rows were affected with the previous sql statement.
This is helpful when for example you construct a dynamic Update statement and run it with exec. @@ROWCOUNT would show how many rows were updated.
Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties
to set a default date format to all of your classes spring.jackson.date-format
.
For your date format example, you would add this line to your properties file:
spring.jackson.date-format=yyyy-MM-dd
On Ubuntu with OpenJDK, it installed in /usr/lib/jvm/default-java/jre/lib/ext/jfxrt.jar
(technically its a symlink to /usr/share/java/openjfx/jre/lib/ext/jfxrt.jar
, but it is probably better to use the default-java
link)
Struggled with the same problem for a couple hours this morning. Building my project from command line seems to have done the trick for me.
Exact steps -
To check if it worked, look in your projects exploded-bundles folder, inspect a library and find the classes.jar. If it is expandable, then everything is going to be ok.
edit - I found after doing a clean within Android studio, it broke again. So if you have to clean, you will need to do this process again.
Does this work for you:
You find this dialog on the Home
ribbon, under the Styles
group, the Conditional Formatting
menu, New rule...
.
add line in .zshrc
# vi .zshrc
alias ngrok="/usr/local/lib/node_modules/node/lib/node_modules/node/lib/node_modules/ngrok/bin/ngrok"
Below code will only allow numbers "0123456789”, even if you accidentally type other than "0123456789”, edit text will not accept.
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_CLASS_PHONE);
number1.setKeyListener(DigitsKeyListener.getInstance("0123456789”));
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
It's also possible to select attributes regardless of their content, in modern browsers
with:
[data-my-attribute] {
/* Styles */
}
[anything] {
/* Styles */
}
For example: http://codepen.io/jasonm23/pen/fADnu
Works on a very significant percentage of browsers.
Note this can also be used in a JQuery selector, or using document.querySelector
It's your gun, your bullet and your foot...
It's bad because you are asking for trouble. It won't be you or any of the other posters on this page who have examples of short/simple while loops.
The trouble will start at some very random time in the future. It might be caused by another programmer. It might be the person installing the software. It might be the end user.
Why? I had to find out why a 700K LOC app would gradually start burning 100% of the CPU time until every CPU was saturated. It was an amazing while (true) loop. It was big and nasty but it boiled down to:
x = read_value_from_database()
while (true)
if (x == 1)
...
break;
else if (x ==2)
...
break;
and lots more else if conditions
}
There was no final else branch. If the value did not match an if condition the loop kept running until the end of time.
Of course, the programmer blamed the end users for not picking a value the programmer expected. (I then eliminated all instances of while(true) in the code.)
IMHO it is not good defensive programming to use constructs like while(true). It will come back to haunt you.
(But I do recall professors grading down if we did not comment every line, even for i++;)
A session cookie is just a normal cookie without an expiration date. Those are handled by the browser to be valid until the window is closed or program is quit.
But if the cookie is a httpOnly
cookie (a cookie with the httpOnly
parameter set), you cannot read, change or delete it from outside of HTTP (meaning it must be changed on the server).
The following works by starting the jar with a batch file, in case the program runs as a stand alone:
public static void startExtJarProgram(){
String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
ProcessBuilder processBuilder = new ProcessBuilder(extJar);
processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External Jar Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
In the batchfile.bat then we can say:
@echo off
start /min C:\path\to\jarprogram.jar
if using logging.config.fileConfig with a configuration file use something like:
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
None of the many answers with Application.CutCopyMode
or .Select
worked for me.
But I did find a solution not posted here, which worked fantastically for me!
From StackExchange SuperUser: Excel VBA “Unselect” wanted
If you are really wanting 'nothing selected`, you can use VBA to protect the sheet at the end of your code execution, which will cause nothing to be selected. You can either add this to a macro or put it into your VBA directly.
Sub NoSelect()
With ActiveSheet
.EnableSelection = xlNoSelection
.Protect
End With
End Sub
As soon as the sheet is unprotected, the cursor will activate a cell.
Hope this helps someone with the same problem!
If you're using Anaconda to manage Python on your system, you can install it with:
$ conda install pyqt=4
Omit the =4
to install the most current version.
Answer from How to install PyQt4 in anaconda?
int power(int x,int y){
int r=1;
do{
r*=r;
if(y%2)
r*=x;
}while(y>>=1);
return r;
};
(iterative)
int power(int x,int y){
return y?(y%2?x:1)*power(x*x,y>>1):1;
};
(if it has to be recursive)
imo, the algorithm should definitely be O(logn)
This post contains a brilliant trick to detect where the cascade problem is:
Try to replace on Cascade at the time with Cascade.None()
until you do not get the error and then you have detected the cascade causing the problem.
Then solve the problem either by changing the original cascade to something else or using Tom Anderson answer.
Reading through the answers, I don't see another option that I like so will offer it as well. I love the parameterization of jobs, but it doesn't always scale well. If you have jobs which are not directly downstream of the first job but farther down the pipeline, you don't really want to parameterize every job in the pipeline so as to be able to pass the parameters all the way through. Or if you have a large number of parameters used by a variety of other jobs (especially those not necessarily tied to one parent or master job), again parameterization doesn't work.
In these cases, I favor outputting the values to a properties file and then injecting that in whatever job I need using the EnvInject plugin. This can be done dynamically, which is another way to solve the issue from another answer above where parameterized jobs were still used. This solution scales very well in many scenarios.
arrList.set(5,newValue);
and if u want to update it then add this line also
youradapater.NotifyDataSetChanged();
I run a very simple bash script which takes all of 10 seconds to do the job and sends me a mail when done.
#!/bin/bash
sudo service nginx stop
sudo rm -rf /var/cache/nginx/*
sudo service nginx start | mail -s "Nginx Purged" [email protected]
exit 0
In cases wherein the width/height of the space is beyond
I usually use:
For horizontal spacer:
<span style="display:inline-block; width: YOURWIDTH;"></span>
For vertical spacer:
<span style="display:block; height: YOURHEIGHT;"></span>
In addition to psparrow's answer if you need to add an index to your temporary table do:
CREATE TEMPORARY TABLE IF NOT EXISTS
temp_table ( INDEX(col_2) )
ENGINE=MyISAM
AS (
SELECT col_1, coll_2, coll_3
FROM mytable
)
It also works with PRIMARY KEY
Another way of simply telling if an element exists is to check the count()
if (myset.count(x)) {
// x is in the set, count is 1
} else {
// count zero, i.e. x not in the set
}
Most of the times, however, I find myself needing access to the element wherever I check for its existence.
So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end
too.
set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
// do something with *it
}
C++ 20
In C++20 set gets a contains
function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245
if (myset.contains(x)) {
// x is in the set
} else {
// no x
}
rpmquery <package Name>
By this command you can check which package is installed.
For Example: rpmquery mysql
It could happen after you update your php version, for instance if you upgrade from php5.6 to php7.1 you need to run these commands:
sudo apt-get install php7.1-mbstring
sudo service apache2 restart
If your destination version is different you need to check if the mbstring package exsit or not, an example for php7.0:
sudo apt-cache search php7.0-mbstring
I found it useful to first check existence of all modules that you working with, then performing an upgrade, in addition to that update phpmyadmin after upgrading your php is a good idea
If you're simply looking for a way to display it, you could use describe():
grp = df.groupby['colName']
grp.describe()
This gives you a neat table.
Try the DATENAME()
function:
select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'
You can .write()
the content into the iframe document. Example:
<iframe id="FileFrame" src="about:blank"></iframe>
<script type="text/javascript">
var doc = document.getElementById('FileFrame').contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
doc.close();
</script>
Max value for array index is Integer.MAX_INT - it's around 2Gb (2^31 / 2 147 483 647). Your input stream can be bigger than 2Gb, so you have to process data in chunks, sorry.
InputStream is;
final byte[] buffer = new byte[512 * 1024 * 1024]; // 512Mb
while(true) {
final int read = is.read(buffer);
if ( read < 0 ) {
break;
}
// do processing
}
If you are able to use other associated technologies such as C#, I suggest using the built in SQL command with Transaction parameter.
var sqlCommand = new SqlCommand(commandText, null, transaction);
I've created a simple Console App that demonstrates this ability which can be found here: https://github.com/hecked12/SQL-Transaction-Using-C-Sharp
In short, C# allows you to overcome this limitation where you can inspect the output of each stored procedure and use that output however you like, for example you can feed it to another stored procedure. If the output is ok, you can commit the transaction, otherwise, you can revert the changes using rollback.
Such difference between the output of du -sh
and df -h
may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted
to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.
Assuming you've used home-brew to install and upgrade Postgres, you can perform the following steps.
Stop current Postgres server:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Initialize a new 10.1 database:
initdb /usr/local/var/postgres10.1 -E utf8
run pg_upgrade
(note: change bin version if you're upgrading from something other than below):
pg_upgrade -v \
-d /usr/local/var/postgres \
-D /usr/local/var/postgres10.1 \
-b /usr/local/Cellar/postgresql/9.6.5/bin/ \
-B /usr/local/Cellar/postgresql/10.1/bin/
-v
to enable verbose internal logging
-d
the old database cluster configuration directory
-D
the new database cluster configuration directory
-b
the old PostgreSQL executable directory
-B
the new PostgreSQL executable directory
Move new data into place:
cd /usr/local/var
mv postgres postgres9.6
mv postgres10.1 postgres
Restart Postgres:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
Check /usr/local/var/postgres/server.log
for details and to make sure the new server started properly.
Finally, re-install the rails pg
gem
gem uninstall pg
gem install pg
I suggest you take some time to read the PostgreSQL documentation to understand exactly what you're doing in the above steps to minimize frustrations.
You're using message.Length
which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:
byte[] messageBytes = uniEncoding.GetBytes(message);
stringAsStream.Write(messageBytes, 0, messageBytes.Length);
You're then reading a single byte and expecting to get a character from it just by casting to char
. UnicodeEncoding
will use two bytes per character.
As Justin says you're also not seeking back to the beginning of the stream.
Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter
to write and then a StreamReader
to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.
there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.
Try git pull --rebase development
In AndroidManifest.xml
, set android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
in application
tag.
Individual activities can override the default by setting their own theme attributes.
1. Ctrl + H
2. Choose File Search for plain text search in workspace/selected projects
For specific expression searches, choose the relevant tab (such as Java Search which allows you to search for specific identifiers)
For whole project search:
3. Scope (in the form section) > Enclosing project (Radio button selection).
Try this instead:
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumall = str(sumall) # add this line
sumln = (int(sumall[0])+int(sumall[1]))
print "Your lucky number is", sumln
sumall
is a number, and you can't access its digits using the subscript notation (sumall[0]
, sumall[1]
). For that to work, you'll need to transform it back to a string.
From the docs:
urllib.quote(string[, safe])
Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'
That means passing '' for safe will solve your first issue:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'
About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller
By the way have a look at urlencode
The same, except replace urllib.quote
with urllib.parse.quote
.
Why don't you simply hide, append, then show, like this:
<div id="parent1" style=" width: 300px; height: 300px; background-color: yellow;">
<div id="child" style=" width: 100px; height: 100px; background-color: red;"></div>
</div>
<div id="parent2" style=" width: 300px; height: 300px; background-color: green;">
</div>
<input id="mybutton" type="button" value="move">
<script>
$("#mybutton").click(function(){
$('#child').hide(1000, function(){
$('#parent2').append($('#child'));
$('#child').show(1000);
});
});
</script>
#!/bin/bash
set -e
# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx
repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git
echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir
echo "CD"
cd ./$dir
echo "Remove GIT"
rm -rf .git
echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url
echo "Push..."
git push -u origin master
Unfortunately, no. This feature is not available for facebook albums.
As you can see I only have java 1.7 installed (on a Ubuntu 14.04 machine).
update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
To install Java 8, I did,
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk
Afterwards, now I have java 7 and 8,
update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64
BONUS ADDED (how to switch between different versions)
sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 auto mode 1 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 manual mode * 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1069 manual mode Press enter to keep the current choice[*], or type selection number:
As you can see I'm running open jdk 8. To switch to to jdk 7, press 1
and hit the Enter key. Do the same for javac
as well with, sudo update-alternatives --config javac
.
Check versions to confirm the change: java -version
and javac -version
.
Kind of, use the XmlAttribute
instead of XmlElement
, but it won't look like what you want. It will look like the following:
<SomeModel SomeStringElementName="testData">
</SomeModel>
The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.
// TODO: make the class generic so that an int or string can be used.
[Serializable]
public class SerializationClass
{
public SerializationClass(string value)
{
this.Value = value;
}
[XmlAttribute("value")]
public string Value { get; }
}
[Serializable]
public class SomeModel
{
[XmlIgnore]
public string SomeString { get; set; }
[XmlIgnore]
public int SomeInfo { get; set; }
[XmlElement]
public SerializationClass SomeStringElementName
{
get { return new SerializationClass(this.SomeString); }
}
}
I believe this is controlled by the css color
property applied to the element.
They are not identical. Memcache is older but it has some limitations. I was using just fine in my application until I realized you can't store literal FALSE
in cache. Value FALSE
returned from the cache is the same as FALSE returned when a value is not found in the cache. There is no way to check which is which. Memcached has additional method (among others) Memcached::getResultCode
that will tell you whether key was found.
Because of this limitation I switched to storing empty arrays instead of FALSE
in cache. I am still using Memcache, but I just wanted to put this info out there for people who are deciding.
If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
with open("./404.csv", "a") as f:
f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
That should be:
java -Dtest="true" -jar myApplication.jar
Then the following will return the value:
System.getProperty("test");
The value could be null
, though, so guard against an exception using a Boolean
:
boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );
Note that the getBoolean
method delegates the system property value, simplifying the code to:
if( Boolean.getBoolean( "test" ) ) {
// ...
}
Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);
Here is my full implementation of modal bootstrap angular2 component:
I assume that in your main index.html file (with <html>
and <body>
tags) at the bottom of <body>
tag you have:
<script src="assets/js/jquery-2.1.1.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
modal.component.ts:
import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';
declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
@Component({
selector: 'modal',
templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {
@Input() title:string;
@Input() showClose:boolean = true;
@Output() onClose: EventEmitter<any> = new EventEmitter();
modalEl = null;
id: string = uniqueId('modal_');
constructor(private _rootNode: ElementRef) {}
open() {
this.modalEl.modal('show');
}
close() {
this.modalEl.modal('hide');
}
closeInternal() { // close modal when click on times button in up-right corner
this.onClose.next(null); // emit event
this.close();
}
ngAfterViewInit() {
this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
}
has(selector) {
return $(this._rootNode.nativeElement).find(selector).length;
}
}
let modal_id: number = 0;
export function uniqueId(prefix: string): string {
return prefix + ++modal_id;
}
modal.html:
<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog" aria-hidden="true" #thisModal>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
<button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<ng-content select="mhead"></ng-content>
<h4 *ngIf='title' class="modal-title">{{ title }}</h4>
</div>
<div class="modal-body">
<ng-content></ng-content>
</div>
<div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
<ng-content select="mfoot"></ng-content>
</div>
</div>
</div>
</div>
And example of usage in client Editor component: client-edit-component.ts:
import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';
@Component({
selector: 'client-edit',
directives: [ Modal ],
templateUrl: './client-edit.html',
providers: [ ClientService ]
})
export class ClientEdit {
_modal = null;
constructor(private _ClientService: ClientService) {}
bindModal(modal) {this._modal=modal;}
open(client) {
this._modal.open();
console.log({client});
}
close() {
this._modal.close();
}
}
client-edit.html:
<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
<mhead>Som non-standart title</mhead>
Some contents
<mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>
Ofcourse title
, showClose
, <mhead>
and <mfoot>
ar optional parameters/tags.
Copy & Paste.
To Add a folder, all the sub-directories, and files we can also Copy and Paste. For example we can:
Right click in Windows explorer on the folder, and Copy on the folder with many files and folders.
Then in Visual Studio Solution explorer, right click on the destination folder and click paste.
Optional add to TFS; Then in the top folder right click and check in to TFS to check in all sub-folders and files.
A, = np.array(M.T)
depends what you mean by elegance i suppose but thats what i would do
In case of NULL
columns it is better to use IF
clause like this which combine the two functions of : CONCAT
and COALESCE
and uses special chars between the columns in result like space or '_'
SELECT FirstName , LastName ,
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,'')))
AS Contact_Phone FROM TABLE1
<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>
To set up an external DB and still use your local DB, you need to edit the config.inc.php file:
On Ubuntu: sudo gedit /etc/phpmyadmin/config.inc.php
The file is roughly set up like this:
if (!empty($dbname)) {
//Your local db setup
$i++;
}
What you need to do is duplicate the "your local db setup" by copying and pasting it outside of the IF
statement I've shown in the code below, and change the host to you external IP. Mine for example is:
$cfg['Servers'][$i]['host'] = '10.10.1.90:23306';
You can leave the defaults (unless you know you need to change them)
Save and refresh your PHPMYADMIN login page and a new dropdown should appear. You should be good to go.
EDIT: if you want to give the server a name to select at login page, rather than having just the IP address to select, add this to the server setup:
$cfg['Servers'][$i]['verbose'] = 'Name to show when selecting your server';
It's good if you have multiple server configs.
If your images are plots you created mith matplotlib, you can use matplotlib.backends.backend_pdf.PdfPages
(See documentation).
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# generate a list with dummy plots
figs = []
for i in [-1, 1]:
fig = plt.figure()
plt.plot([1, 2, 3], [i*1, i*2, i*3])
figs.append(fig)
# gerate a multipage pdf:
with PdfPages('multipage_pdf.pdf') as pdf:
for fig in figs:
pdf.savefig(fig)
plt.close()
Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.
import Image
def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
fg_img_trans = Image.new("RGBA",fg_img.size)
fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
bg_img.paste(fg_img_trans,box,fg_img_trans)
return bg_img
bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
If the formula already exists in a cell you can fill it down as follows:
On Mac, use CMD instead of CTRL.
An alternative if the formula is in the first cell of a column:
Getting a stack trace from a running Python application
There are several tricks here. These include
I think you're looking for the ndenumerate.
>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
... print x,y
...
0 0
0 1
1 0
1 1
2 0
2 1
Regarding the performance. It is a bit slower than a list comprehension.
X = np.zeros((100, 100, 100))
%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop
%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop
If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate
, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords
attribute of the flat iterator.
a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop
Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded @ e.g. 1 and to have increment of 1 - save and you're done.
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
Try:
$ rm YOUR_PROJECT_DIR/.metadata/.plugins/org.eclipse.core.resources/.snap
Original source: Job found still running after platform shutdown eclipse
One of the mistakes is setting components
as array instead of object!
This is wrong:
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: [
ChildComponent
],
props: {
...
}
};
</script>
This is correct:
<script>
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
props: {
...
}
};
</script>
Note: for components that use other ("child") components, you must also specify a components
field!
Code > Preferences > Keyboard Shortcuts
emmet wrap
Because none of the above answers did the trick for me, here is my solution:
I combined the POSITION_NONE
with loading on setUserVisibleHint(boolean isVisibleToUser)
instead of onStart()
As seen here: https://stackoverflow.com/a/25676323/497366
In the Fragment
:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}
and in the FragmentStatePagerAdapter
as seen in the top answer here from Simon Dorociak https://stackoverflow.com/a/18088509/497366:
@Override
public int getItemPosition(@NonNull Object object) {
return POSITION_NONE;
}
Now the fragments reload the data into their views everytime they are shown to the user.
PowerShell One-Liners (string to hash)
MD5
([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")
SHA1
([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")
SHA256
([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")
SHA384
([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")
SHA512
([System.BitConverter]::ToString((New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider).ComputeHash((New-Object -TypeName System.Text.UTF8Encoding).GetBytes("Hello, World!")))).Replace("-","")
This should be cross platform. At least for Linux and Mac OS X.
python -c 'import multiprocessing as mp; print(mp.cpu_count())'
A little bit slow but works.
Correct final syntax for [Mr. C]s answer.
With the release of VS2017RC and its C#7 support it works this way:
switch(message)
{
case string a when a.Contains("test2"): return "no";
case string b when b.Contains("test"): return "yes";
}
You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.
See the docs:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates toTRUE
, andexpr3
otherwise.
class, interface, or enum expected
The above error is even possible when import statement is miss spelled. A proper statement is "import com.company.HelloWorld;"
If by mistake while code writing/editing it is miss written like "t com.company.HelloWorld;"
compiler will show "class, interface, or enum expected"
Convert both dates to timestamps then do
pseudocode:
if date_from_user > start_date && date_from_user < end_date
return true
I think maybe you are implementing the OnClickListener in the wrong place - usually you should definitely implement an OnItemClickListener in your Activity and set it on the ListView instead, or you will get problems with your events...
Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.
The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.
This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
Hope this helps.
The HTML Tidy library is able to fix some malformed XML files. Running your feeds through that before passing them on to the parser may help.
One option that might work is using WindowsIdentity.Impersonate
(and change the thread principal) to become the desired user, like so. Back to p/invoke, though, I'm afraid...
Another cheeky (and equally far from ideal) option might be to spawn a process to do the work... ProcessStartInfo
accepts a .UserName
, .Password
and .Domain
.
Finally - perhaps run the service in a dedicated account that has access? (removed as you have clarified that this isn't an option).
I am still a beginner at git, and it was just a stupid mistake I made, long story in one sentence. I was not in a subfolder as @gaoagong reported, but the other way round, in a parent folder. Strange enough, I did not get the idea from that answer, instead, the idea came up when I tested git add --all
, see the long story below.
Example in details. Actual repo:
The Parent folder that I had opened mistakenly on parent level (vscode_git in my case):
I had cloned a repo, but I had a parent folder above this repo which I had opened instead, and then I tried adding a file of the subfolder's repo with git add 'd:\Stack Overflow\vscode_git\vscode-java\.github\ISSUE_TEMPLATE.md'
, which simply did nothing, no warning message, and the git status
afterwards said:
nothing added to commit but untracked files present (use "git add" to track)
Running git add --all
gave me the yellow notes:
warning: adding embedded git repository: vscode-java the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use: git submodule add vscode-java
hint: If you added this path by mistake, you can remove it from the index with git rm --cached vscode-java
See "git help submodule" for more information.git
To fix this, I reverted the git add --all
with git rm --cached -r -f -- "d:\Stack Overflow\vscode_git\vscode-java" rm 'vscode-java'
:
Then, by simply opening the actual repo folder instead,
the git worked as expected again. Of course the ".git" folder of the parent folder could be deleted then:
Git 1.8.2 added the possibility to track branches.
# add submodule to track branch_name branch
git submodule add -b branch_name URL_to_Git_repo optional_directory_rename
# update your submodule
git submodule update --remote
See also Git submodules
I just had this issue and realized that there were empty columns being treated as columns with values, I saw this by opening my CSV in my text editor. To fix this, I opened my spreadsheet and deleted the columns after my last column, they looked completely empty but they were not. After I did this, the import worked perfectly.
Either raise the new exception with your error message using
raise Exception('your error message')
or
raise ValueError('your error message')
within the place where you want to raise it OR attach (replace) error message into current exception using 'from' (Python 3.x supported only):
except ValueError as e:
raise ValueError('your message') from e
The Bash builtin getopts function can be used to parse long options by putting a dash character followed by a colon into the optspec:
#!/usr/bin/env bash
optspec=":hv-:"
while getopts "$optspec" optchar; do
case "${optchar}" in
-)
case "${OPTARG}" in
loglevel)
val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
;;
loglevel=*)
val=${OPTARG#*=}
opt=${OPTARG%=$val}
echo "Parsing option: '--${opt}', value: '${val}'" >&2
;;
*)
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
echo "Unknown option --${OPTARG}" >&2
fi
;;
esac;;
h)
echo "usage: $0 [-v] [--loglevel[=]<value>]" >&2
exit 2
;;
v)
echo "Parsing option: '-${optchar}'" >&2
;;
*)
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
echo "Non-option argument: '-${OPTARG}'" >&2
fi
;;
esac
done
After copying to executable file name=getopts_test.sh
in the current working directory, one can produce output like
$ ./getopts_test.sh
$ ./getopts_test.sh -f
Non-option argument: '-f'
$ ./getopts_test.sh -h
usage: code/getopts_test.sh [-v] [--loglevel[=]<value>]
$ ./getopts_test.sh --help
$ ./getopts_test.sh -v
Parsing option: '-v'
$ ./getopts_test.sh --very-bad
$ ./getopts_test.sh --loglevel
Parsing option: '--loglevel', value: ''
$ ./getopts_test.sh --loglevel 11
Parsing option: '--loglevel', value: '11'
$ ./getopts_test.sh --loglevel=11
Parsing option: '--loglevel', value: '11'
Obviously getopts neither performs OPTERR
checking nor option-argument parsing for the long options. The script fragment above shows how this may be done manually. The basic principle also works in the Debian Almquist shell ("dash"). Note the special case:
getopts -- "-:" ## without the option terminator "-- " bash complains about "-:"
getopts "-:" ## this works in the Debian Almquist shell ("dash")
Note that, as GreyCat from over at http://mywiki.wooledge.org/BashFAQ points out, this trick exploits a non-standard behaviour of the shell which permits the option-argument (i.e. the filename in "-f filename") to be concatenated to the option (as in "-ffilename"). The POSIX standard says there must be a space between them, which in the case of "-- longoption" would terminate the option-parsing and turn all longoptions into non-option arguments.
You are probably manually calling setVisible(true)
on the menu. That can cause some nasty buggy behavior in the menu.
The show(Component, int x, int x)
method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true)
just shows the menu without adding any additional behavior.
To make a right click popup menu simply create a JPopupMenu
.
class PopUpDemo extends JPopupMenu {
JMenuItem anItem;
public PopUpDemo() {
anItem = new JMenuItem("Click Me!");
add(anItem);
}
}
Then, all you need to do is add a custom MouseListener
to the components you would like the menu to popup for.
class PopClickListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
private void doPop(MouseEvent e) {
PopUpDemo menu = new PopUpDemo();
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
// Then on your component(s)
component.addMouseListener(new PopClickListener());
Of course, the tutorials have a slightly more in-depth explanation.
Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen()
and e.getYOnScreen()
methods for the x and y coordinates.
When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.
What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true
and -o yaml
options:
kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -
The command above will not raise an error if the resource already exists (and will update the resource if needed).
This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).
First lets take a look at how can we define a variable in mysql
To define a varible in mysql it should start with '@' like @{variable_name} and this '{variable_name}', we can replace it with our variable name.
Now, how to assign a value in a variable in mysql. For this we have many ways to do that
Example :-
mysql > SET @a = 1;
Example:-
mysql > @a:=1;
Example:-
mysql > select 1 into @a;
Here @a is user defined variable and 1 is going to be assigned in @a.
Now how to get or select the value of @{variable_name}.
we can use select statement like
Example :-
mysql > select @a;
it will show the output and show the value of @a.
Now how to assign a value from a table in a variable.
For this we can use two statement like :-
1.
@a := (select emp_name from employee where emp_id = 1);
select emp_name into @a from employee where emp_id = 1;
Always be careful emp_name must return single value otherwise it will throw you a error in this type statements.
refer this:- http://www.easysolutionweb.com/sql-pl-sql/how-to-assign-a-value-in-a-variable-in-mysql
var normalText = "Hi am normal"
var boldText = "And I am BOLD!"
var attributedString = NSMutableAttributedString(string:normalText)
var attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15)]
var boldString = NSMutableAttributedString(string: boldText, attributes:attrs)
attributedString.append(boldString)
When you want to assign it to a label:
yourLabel.attributedText = attributedString
Put parentheses around the "OR"s:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
Or even better, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
For Java, consider using Apache Commons FileUtils:
/**
* Convert a file to base64 string representation
*/
public String fileToBase64(File file) throws IOException {
final byte[] bytes = FileUtils.readFileToByteArray(file);
return Base64.getEncoder().encodeToString(bytes);
}
/**
* Convert base64 string representation to a file
*/
public void base64ToFile(String base64String, String filePath) throws IOException {
byte[] bytes = Base64.getDecoder().decode(base64String);
FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}
Use below one,
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
I've used ZetaHtmlTidy in the past to load random websites and then hit against various parts of the content with xpath (eg /html/body//p[@class='textblock']). It worked well but there were some exceptional sites that it had problems with, so I don't know if it's the absolute best solution.
No! The same execution plan, look at these two tables:
CREATE TABLE table1 (
id INT,
name VARCHAR(20)
);
CREATE TABLE table2 (
id INT,
name VARCHAR(20)
);
The execution plan for the query using the inner join:
-- with inner join
EXPLAIN PLAN FOR
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t1.id = t2.id;
SELECT *
FROM TABLE (DBMS_XPLAN.DISPLAY);
-- 0 select statement
-- 1 hash join (access("T1"."ID"="T2"."ID"))
-- 2 table access full table1
-- 3 table access full table2
And the execution plan for the query using a WHERE clause.
-- with where clause
EXPLAIN PLAN FOR
SELECT * FROM table1 t1, table2 t2
WHERE t1.id = t2.id;
SELECT *
FROM TABLE (DBMS_XPLAN.DISPLAY);
-- 0 select statement
-- 1 hash join (access("T1"."ID"="T2"."ID"))
-- 2 table access full table1
-- 3 table access full table2
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
1. for error: unescaped apostrophe in string
what I found is that AAPT2 tool points to wrong row in xml, sometimes. So you should correct whole strings.xml file
In Android Studio, in problem file use :
Edit->find->replace
Then write in first field \' (or \&,>,\<,\")
in second put '(or &,>,<,")
then replace each if needed.(or "reptlace all" in case with ')
Then in first field again put '(or &,>,<,")
and in second write \'
then replace each if needed.(or "replace all" in case with ')
2. for other problematic symbols
I use to comment each next half part +rebuild
until i won't find the wrong sign.
E.g. an escaped word "\update" unexpectedly drops such error :)
I'm running Eclipse Indigo 64 bit on Windows 7 64 bit and I kept getting missing dependency errors associated with Maven and other plugins using the JBoss Tools 3.3.X latest download. Here is the link.
So, I opted to only install Hibernate Tools with nothing else by typing in "hibernate" at the top of the install software dialog in eclipse. Only 4 items showed up, so that is all I installed. It worked fine with no problems. Here is the tutorial that I used to get it installed properly after several failed attempts.
I don't know if part of this was due to having a lot of plugins already installed or if this is the best solution or not, but I thought I'd share it with everyone.
This code will demonstrate how a java int can be split up into its 4 consecutive bytes. We can then inspect each byte using Java methods compared to low level byte / bit interrogation.
This is the expected output when you run the code below:
[Input] Integer value: 8549658
Integer.toBinaryString: 100000100111010100011010
Integer.toHexString: 82751a
Integer.bitCount: 10
Byte 4th Hex Str: 0
Byte 3rd Hex Str: 820000
Byte 2nd Hex Str: 7500
Byte 1st Hex Str: 1a
(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: 82751a
(1st + 2nd + 3rd + 4th (int(s)) == Integer.toHexString): true
Individual bits for each byte in a 4 byte int:
00000000 10000010 01110101 00011010
Here is the code to run:
public class BitsSetCount
{
public static void main(String[] args)
{
int send = 8549658;
System.out.println( "[Input] Integer value: " + send + "\n" );
BitsSetCount.countBits( send );
}
private static void countBits(int i)
{
System.out.println( "Integer.toBinaryString: " + Integer.toBinaryString(i) );
System.out.println( "Integer.toHexString: " + Integer.toHexString(i) );
System.out.println( "Integer.bitCount: "+ Integer.bitCount(i) );
int d = i & 0xff000000;
int c = i & 0xff0000;
int b = i & 0xff00;
int a = i & 0xff;
System.out.println( "\nByte 4th Hex Str: " + Integer.toHexString(d) );
System.out.println( "Byte 3rd Hex Str: " + Integer.toHexString(c) );
System.out.println( "Byte 2nd Hex Str: " + Integer.toHexString(b) );
System.out.println( "Byte 1st Hex Str: " + Integer.toHexString(a) );
int all = a+b+c+d;
System.out.println( "\n(1st + 2nd + 3rd + 4th (int(s)) as Integer.toHexString: " + Integer.toHexString(all) );
System.out.println("(1st + 2nd + 3rd + 4th (int(s)) == Integer.toHexString): " +
Integer.toHexString(all).equals(Integer.toHexString(i) ) );
System.out.println( "\nIndividual bits for each byte in a 4 byte int:");
/*
* Because we are sending the MSF bytes to a method
* which will work on a single byte and print some
* bits we are generalising the MSF bytes
* by making them all the same in terms of their position
* purely for the purpose of printing or analysis
*/
System.out.print(
getBits( (byte) (d >> 24) ) + " " +
getBits( (byte) (c >> 16) ) + " " +
getBits( (byte) (b >> 8) ) + " " +
getBits( (byte) (a >> 0) )
);
}
private static String getBits( byte inByte )
{
// Go through each bit with a mask
StringBuilder builder = new StringBuilder();
for ( int j = 0; j < 8; j++ )
{
// Shift each bit by 1 starting at zero shift
byte tmp = (byte) ( inByte >> j );
// Check byte with mask 00000001 for LSB
int expect1 = tmp & 0x01;
builder.append(expect1);
}
return ( builder.reverse().toString() );
}
}
This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):
$('#domTarget').html('<img src="" />');
var url = '/some/image/path.png';
$('#domTarget img').load(function(){}).attr('src', url).error(function() {
if ( isIE ) {
var thisImg = this;
setTimeout(function() {
if ( ! thisImg.complete ) {
$(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
}
},250);
} else {
$(this).attr('src', '/web/css/img/picture-broken-url.png');
}
});
Note: You will need to supply a valid boolean state for the isIE variable.
If you are running a really old version of nltk, then there is indeed no download module available (reference)
Try this:
import nltk
print(nltk.__version__)
As per the reference, anything after 0.9.5 should be fine
I've set up a JSFiddle to test several different solutions to this problem. Based on the [vague] criteria of
1) Maximum flexibility
2) No weird behavior
The accepted answer here of
img { display: block; }
which is recommended by a lot of people (such as in this excellent article), actually ranks fourth.
1st, 2nd, and 3rd place are all a toss-up between these three solutions:
1) The solution given by @Dave Kok and @Hasan Gursoy:
img { vertical-align: top; } /* or bottom */
pros:
cons:
2) Setting font-size: 0;
on the parent element:
.parent {
font-size: 0;
vertical-align: top;
}
.parent > * {
font-size: 16px;
vertical-align: top;
}
Since this one [kind of] requires vertical-align: top
on the img
, this is basically an extension of the 1st solution.
pros:
cons:
3) Setting line-height: 0
on the parent element:
.parent {
line-height: 0;
vertical-align: top;
}
.parent > * {
line-height: 1.15;
vertical-align: top;
}
Similar to the 2nd solution in that, to make it fully flexible, it basically becomes an extension of the 1st.
pros:
cons:
So there you have it. I hope this helps some poor soul.
127.0.0.1,6283
Add a comma between the ip and port
For every client you need to start separate thread. Example:
public class ThreadedEchoServer {
static final int PORT = 1978;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new EchoThread(socket).start();
}
}
}
and
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try {
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
return;
}
String line;
while (true) {
try {
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
socket.close();
return;
} else {
out.writeBytes(line + "\n\r");
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
You can also go with more advanced solution, that uses NIO selectors, so you will not have to create thread for every client, but that's a bit more complicated.
Probably not exactly your issue..
Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments
sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /
The server directive has to be in the http directive. It should not be outside of it.
Incase if you need detailed information, refer this.
Since nobody posted the modern C++ approach yet,
#include <iostream>
#include <random>
int main()
{
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(25, 63); // define the range
for(int n=0; n<40; ++n)
std::cout << distr(gen) << ' '; // generate numbers
}
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.
Private Sub Open_multiple_sub_pages_from_main_page()
Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
Set objCollection = IE.Document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "txtUserName" Then
' Set text for search
objCollection(i).Value = "1234"
End If
If objCollection(i).Name = "txtPwd" Then
' Set text for search
objCollection(i).Value = "password"
End If
If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click ' click button to load page
' Wait while IE re-loading...
While IE.Busy
DoEvents
Wend
' Show IE
IE.Visible = True
Set Doc = IE.Document
Dim links, link
Dim j As Integer 'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n 'loop to go thru all "a" item so it loads next page
links(j).Click
While IE.Busy
DoEvents
Wend
'-------------Do stuff here: copy field value and paste in excel sheet. Will post another question for this------------------------
IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click 'save
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click 'close
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
j = j + 2
Wend
End Sub
Objective C
Post API with parameters and validate with url to navigate if json
response key with status:"success"
NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
NSLog(@"%@",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData: %@", str);
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:nil];
NSDictionary* latestLoans = [json objectForKey:@"status"];
NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
NSString *str3=@"success";
if ([str3 isEqualToString:str2 ])
{
[self performSegueWithIdentifier:@"move" sender:nil];
NSLog(@"successfully.");
}
else
{
UIAlertController *alert= [UIAlertController
alertControllerWithTitle:@"Try Again"
message:@"Username or Password is Incorrect."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[self.view endEditing:YES];
}
];
[alert addAction:ok];
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
[self presentViewController:alert animated:YES completion:nil];
[self.view endEditing:YES];
}
JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code
**
In Python there is a method for doing this: driver.refresh()
. It may not be the same in Java.
Alternatively, you could driver.get("http://foo.bar");
, although I think the refresh method should work just fine.
Only working option for me is:
$('body').on('hidden.bs.modal', '#modalBox', function () {
$(this).remove();
});
I use Bootstrap 3 and I have a function called
popup('popup content')
which appends the modal box html.