The objdump
tool can tell you this information. If you invoke objdump
with the -x
option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".
For example running objdump -x /usr/lib/libXpm.so.4
on my system gives the following information in the "Dynamic Section":
Dynamic Section:
NEEDED libX11.so.6
NEEDED libc.so.6
SONAME libXpm.so.4
INIT 0x0000000000002450
FINI 0x000000000000e0e8
GNU_HASH 0x00000000000001f0
STRTAB 0x00000000000011a8
SYMTAB 0x0000000000000470
STRSZ 0x0000000000000813
SYMENT 0x0000000000000018
PLTGOT 0x000000000020ffe8
PLTRELSZ 0x00000000000005e8
PLTREL 0x0000000000000007
JMPREL 0x0000000000001e68
RELA 0x0000000000001b38
RELASZ 0x0000000000000330
RELAENT 0x0000000000000018
VERNEED 0x0000000000001ad8
VERNEEDNUM 0x0000000000000001
VERSYM 0x00000000000019bc
RELACOUNT 0x000000000000001b
The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4
on my system just needs libX11.so.6
and libc.so.6
.
It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump
will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.
some resources:
ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:
arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]
or using fromELF utility(built in most IDEs such as ADS though):
fromelf -bin -o [binary-output-file] [elf-input-file]
In general, when you get an error like this, just do
yum provides ld-linux.so.2
then you'll see something like:
glibc-2.20-5.fc21.i686 : The GNU libc libraries
Repo : fedora
Matched from:
Provides : ld-linux.so.2
and then you just run the following like BRPocock wrote (in case you were wondering what the logic was...):
yum install glibc.i686
As per this response, the complete steps are:
1) Open SDK Manager (In Android Studio, go to Tools > Android > SDK Manager) and Download Intel x86 Emulator Accelerator (HAXM installer) if you haven't.
2) Now go to your SDK directory C:\users\%USERNAME%\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\
and run the file named intelhaxm-android.exe
.
In case you get an error like "Intel virtualization technology (vt,vt-x) is not enabled". Go to your BIOS settings and enable Hardware Virtualization.
3) Restart Android Studio and then try to start the AVD again.
It might take a minute or 2 to show the emulator window.
If the Object
was originally been instantiated as an Integer
, then you can downcast it to an int
using the cast operator (Subtype)
.
Object object = new Integer(10);
int i = (Integer) object;
Note that this only works when you're using at least Java 1.5 with autoboxing feature, otherwise you have to declare i
as Integer
instead and then call intValue()
on it.
But if it initially wasn't created as an Integer
at all, then you can't downcast like that. It would result in a ClassCastException
with the original classname in the message. If the object's toString()
representation as obtained by String#valueOf()
denotes a syntactically valid integer number (e.g. digits only, if necessary with a minus sign in front), then you can use Integer#valueOf()
or new Integer()
for this.
Object object = "10";
int i = Integer.valueOf(String.valueOf(object));
You can use \t
to create a tab in a file.
As of Visual Studio 2012, Microsoft no longer provides the built-in deployment package. If you wish to use this package, you will need to use VS2010.
In 2013 you have several options:
In my projects I create my own installers from scratch, which, since I do not use Windows Installer, have the advantage of being super fast, even on old machines.
A few ideas:
HEAD
command instead of a full GET to see if it needs to download the full file again, and the server uses the timestamp to see.If you want to disable caching on your server, you can do something like:
Header set Expires "Thu, 19 Nov 1981 08:52:00 GM"
Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
Header set Pragma "no-cache"
In .htaccess
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
Try this on Debian/Ubuntu:
sudo apt-get install python-mechanize
if you want read and write on your extra field, you can use a new custom serializer, that extends serializers.Serializer, and use it like this
class ExtraFieldSerializer(serializers.Serializer):
def to_representation(self, instance):
# this would have the same as body as in a SerializerMethodField
return 'my logic here'
def to_internal_value(self, data):
# This must return a dictionary that will be used to
# update the caller's validation data, i.e. if the result
# produced should just be set back into the field that this
# serializer is set to, return the following:
return {
self.field_name: 'Any python object made with data: %s' % data
}
class MyModelSerializer(serializers.ModelSerializer):
my_extra_field = ExtraFieldSerializer(source='*')
class Meta:
model = MyModel
fields = ['id', 'my_extra_field']
i use this in related nested fields with some custom logic
It comes down to what you're using in class.
If the labs and the assignments are in linux, then you probably want a MinGW solution. If they're in windows, get Visual Studio Express.
Take a look at this answer:
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.
Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.
Implementing the necessary interfaces for using an object as a data source can be found here.
Once upon a time (pre C++98); the following would break:
{
for (int i=0; i<.; ++i) {std::string foo;}
for (int i=0; i<.; ++i) {std::string foo;}
}
with the warning that i was already declared (foo was fine as that's scoped within the {}). This is likely the WHY people would first argue it's bad. It stopped being true a long time ago though.
If you STILL have to support such an old compiler (some people are on Borland) then the answer is yes, a case could be made to put the i out the loop, because not doing so makes it makes it "harder" for people to put multiple loops in with the same variable, though honestly the compiler will still fail, which is all you want if there's going to be a problem.
If you no longer have to support such an old compiler, variables should be kept to the smallest scope you can get them so that you not only minimise the memory usage; but also make understanding the project easier. It's a bit like asking why don't you have all your variables global. Same argument applies, but the scopes just change a bit.
To find all configurations, you just write this command:
git config --list
In my local i run this command .
Md Masud@DESKTOP-3HTSDV8 MINGW64 ~
$ git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
[email protected]
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f
This happened to me when I installed Angular 8, there are some incompatibilities I couldn't solve. I had to downgrade because I went down the rabbit hole juggling around with every version until I found one that worked.
First, TypeScript was outdated, the default installation added a reference to TypeScript 3.1.6 and it requires 3.4 or greater.
npm install typescript@">=3.4 <3.5"
Second, using the devkit 0.800.1 or 0.800.1 always ended up in incompatibilities. I tried many combinations but I am not sure it's fully compatible yet, specially because I am using one bootstrap a bit older and I cannot upgrade yet.
Finally I tried to downgrade (go to package.json and find the devDependencies) until one of them worked.
@angular-devkit/build-angular": "0.13.4"
I am sure your problem is dependencies versions but I cannot tell you which one. Give it a try downgrading.
To generate a number between 10 to 20 inclusive, you can use java.util.Random
int myNumber = new Random().nextInt(11) + 10
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
git pull
is really equivalent to running git fetch
and then git merge
. The git fetch
updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master
, github/experiment
, etc. that you see with git branch -r
. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch
(or a successful git push
).
So, suppose you've got a remote called origin
that refers to your GitHub repository, you would do:
git fetch origin
... and then do:
git diff master origin/master
... in order to see the difference between your master
, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master
, assuming master
is your current branch.
Personally, I think that doing git fetch
and git merge
separately is generally a good idea.
When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.
Off hand the code looks right. What if you try using an 'Else' and see what happens?
IF @SchoolCategoryCode = 'Elem'
--- We now have determined we are processing an elementary school...
BEGIN
---- Only do the following if the variable @Term equals a 3 - if it does not, skip just this first part
IF @Term = 3
BEGIN
INSERT INTO @Classes
SELECT
XXXXXX
FROM XXXX blah blah blah
INSERT INTO @Classes
SELECT
XXXXXXXX
FROM XXXXXX (more code)
END <----(Should this be ENDIF?)
ELSE
BEGIN
INSERT INTO @Classes
SELECT
XXXXXXXX
FROM XXXXXX (more code)
END
END
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
Environment.getExternalStorageDirectory()
will NOT return path to micro SD card Storage.
how to get file path from sd card in android
By sd card, I am assuming that, you meant removable micro SD card.
In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type)
in Context
Class that allows apps to store data/files in micro SD cards.
Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.
Environment.getExternalStorageDirectory()
was there from API level 1
getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).
But note that,
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using
getExternalStorageState(File)
.There is no security enforced with these files. For example, any application holding
WRITE_EXTERNAL_STORAGE
can write to these files.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
Try to use protocol relative links.
Your link is http://example.com/script.js, use:
<script src="//example.com/script.js" type="text/javascript"></script>
In this way, you can leave the scheme free (do not indicate the protocol in the links) and trust that the browser uses the protocol of the embedded Web page. If your users visit the HTTP version of your Web page, the script will be loaded over http:// and if your users visit the HTTPS version of your Web site, the script will be loaded over https://.
Seen in: https://developer.mozilla.org/es/docs/Seguridad/MixedContent/arreglar_web_con_contenido_mixto
Simply speaking, closure is a trick about scope, lambda is an anonymous function. We can realize closure with lambda more elegantly and lambda is often used as a parameter passed to a higher function
let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print("Synchronous\(jsonResult)")
} catch {
print(error.localizedDescription)
}
}.resume()
If you have another variable also referring to the same dictionary, there is a big difference:
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
This is because assigning d = {}
creates a new, empty dictionary and assigns it to the d
variable. This leaves d2
pointing at the old dictionary with items still in it. However, d.clear()
clears the same dictionary that d
and d2
both point at.
Taken from the Multimarkdown Users Guide (thanks to @MultiMarkdown on Twitter for pointing it out)
[Some Text][]
will link to a header named “Some Text”
e.g.
### Some Text ###
An optional label of your choosing to help disambiguate cases where multiple headers have the same title:
### Overview [MultiMarkdownOverview] ##
This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.
If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.
In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.
If you have an image inside a UIImageView , e.g. "myImageView", you can do the following:
Convert your image using UIImageJPEGRepresentation() or UIImagePNGRepresentation() like this:
NSData *data = UIImagePNGRepresentation(myImageView.image);
//or
NSData *data = UIImageJPEGRepresentation(myImageView.image, 0.8);
//The float param (0.8 in this example) is the compression quality
//expressed as a value from 0.0 to 1.0, where 1.0 represents
//the least compression (or best quality).
You can also put this code inside a GCD block and execute in another thread, showing an UIActivityIndicatorView during the process ...
//*code to show a loading view here*
dispatch_queue_t myQueue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(myQueue, ^{
NSData *data = UIImagePNGRepresentation(myImageView.image);
//some code....
dispatch_async( dispatch_get_main_queue(), ^{
//*code to hide the loading view here*
});
});
If I understood the question correctly there should be an easier way to accomplish what you need. Call
dgvSomeDataGrid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
That should do the trick. However, there is one pitfall as you cannot simply call this method directly after populating your DataGridView control. Instead you will have to add an EventHandler for the VisibleChanged event and call the method in there.
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 one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.
I can finally copy paste between MacVim on my terminal and the rest of my applications.
I transfered some Java enums to javascript objects.
These objects returned correct arrays for me. if object keys are mixed type (string, int, char), there is a problem.
var Helper = {_x000D_
isEmpty: function (obj) {_x000D_
return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
},_x000D_
_x000D_
isObject: function (obj) {_x000D_
return (typeof obj === 'object');_x000D_
},_x000D_
_x000D_
sortObjectKeys: function (object) {_x000D_
return Object.keys(object)_x000D_
.sort(function (a, b) {_x000D_
c = a - b;_x000D_
return c_x000D_
});_x000D_
},_x000D_
containsItem: function (arr, item) {_x000D_
if (arr && Array.isArray(arr)) {_x000D_
return arr.indexOf(item) > -1;_x000D_
} else {_x000D_
return arr === item;_x000D_
}_x000D_
},_x000D_
_x000D_
pushArray: function (arr1, arr2) {_x000D_
if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
function TypeHelper() {_x000D_
var _types = arguments[0],_x000D_
_defTypeIndex = 0,_x000D_
_currentType,_x000D_
_value;_x000D_
_x000D_
if (arguments.length == 2) {_x000D_
_defTypeIndex = arguments[1];_x000D_
}_x000D_
_x000D_
Object.defineProperties(this, {_x000D_
Key: {_x000D_
get: function () {_x000D_
return _currentType;_x000D_
},_x000D_
set: function (val) {_x000D_
_currentType.setType(val, true);_x000D_
},_x000D_
enumerable: true_x000D_
},_x000D_
Value: {_x000D_
get: function () {_x000D_
return _types[_currentType];_x000D_
},_x000D_
set: function (val) {_x000D_
_value.setType(val, false);_x000D_
},_x000D_
enumerable: true_x000D_
}_x000D_
});_x000D_
_x000D_
this.getAsList = function (keys) {_x000D_
var list = [];_x000D_
Helper.sortObjectKeys(_types).forEach(function (key, idx, array) {_x000D_
if (key && _types[key]) {_x000D_
_x000D_
if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
var json = {};_x000D_
json.Key = key;_x000D_
json.Value = _types[key];_x000D_
Helper.pushArray(list, json);_x000D_
}_x000D_
}_x000D_
});_x000D_
return list;_x000D_
};_x000D_
_x000D_
this.setType = function (value, isKey) {_x000D_
if (!Helper.isEmpty(value)) {_x000D_
Object.keys(_types).forEach(function (key, idx, array) {_x000D_
if (Helper.isObject(value)) {_x000D_
if (value && value.Key == key) {_x000D_
_currentType = key;_x000D_
}_x000D_
} else if (isKey) {_x000D_
if (value && value.toString() == key.toString()) {_x000D_
_currentType = key;_x000D_
}_x000D_
} else if (value && value.toString() == _types[key]) {_x000D_
_currentType = key;_x000D_
}_x000D_
});_x000D_
} else {_x000D_
this.setDefaultType();_x000D_
}_x000D_
return isKey ? _types[_currentType] : _currentType;_x000D_
};_x000D_
_x000D_
this.setTypeByIndex = function (index) {_x000D_
var keys = Helper.sortObjectKeys(_types);_x000D_
for (var i = 0; i < keys.length; i++) {_x000D_
if (index === i) {_x000D_
_currentType = keys[index];_x000D_
break;_x000D_
}_x000D_
}_x000D_
};_x000D_
_x000D_
this.setDefaultType = function () {_x000D_
this.setTypeByIndex(_defTypeIndex);_x000D_
};_x000D_
_x000D_
this.setDefaultType();_x000D_
}_x000D_
_x000D_
_x000D_
var TypeA = {_x000D_
"-1": "Any",_x000D_
"2": "2L",_x000D_
"100": "100L",_x000D_
"200": "200L",_x000D_
"1000": "1000L"_x000D_
};_x000D_
_x000D_
var TypeB = {_x000D_
"U": "Any",_x000D_
"W": "1L",_x000D_
"V": "2L",_x000D_
"A": "100L",_x000D_
"Z": "200L",_x000D_
"K": "1000L"_x000D_
};_x000D_
console.log('keys of TypeA', Helper.sortObjectKeys(TypeA));//keys of TypeA ["-1", "2", "100", "200", "1000"]_x000D_
_x000D_
console.log('keys of TypeB', Helper.sortObjectKeys(TypeB));//keys of TypeB ["U", "W", "V", "A", "Z", "K"]_x000D_
_x000D_
var objectTypeA = new TypeHelper(TypeA),_x000D_
objectTypeB = new TypeHelper(TypeB);_x000D_
_x000D_
console.log('list of objectA = ', objectTypeA.getAsList());_x000D_
console.log('list of objectB = ', objectTypeB.getAsList());
_x000D_
Types:
var TypeA = {
"-1": "Any",
"2": "2L",
"100": "100L",
"200": "200L",
"1000": "1000L"
};
var TypeB = {
"U": "Any",
"W": "1L",
"V": "2L",
"A": "100L",
"Z": "200L",
"K": "1000L"
};
Sorted Keys(output):
Key list of TypeA -> ["-1", "2", "100", "200", "1000"]
Key list of TypeB -> ["U", "W", "V", "A", "Z", "K"]
we can find upper case letter by using regular expression as well
private static void findUppercaseFirstLetterInString(String content) {
Matcher m = Pattern
.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
content);
System.out.println("Given input string : " + content);
while (m.find()) {
if (m.group(1).equals(m.group(1).toUpperCase())) {
System.out.println("First Letter Upper case match found :"
+ m.group());
}
}
}
for detailed example . please visit http://www.onlinecodegeek.com/2015/09/how-to-determines-if-string-starts-with.html
Negative numbers can add some quirks that people need to be aware of.
printf
-style approaches give us correct numbers, but they can result in some odd displays. We have discovered that this method (in my opinion, stupidly) puts in a -
sign whether or not it should or shouldn't. For example, -0.01 rounded to one decimal place returns a -0.0, rather than just 0. If you are going to do the printf
style approach, and you know you want no decimal, use %d
and not %f
(when you need decimals, it's when the display gets wonky).
While it's correct and for math no big deal, for display it just looks weird showing something like "-0.0".
For the int method, negative numbers can change what you want as a result (though there are some arguments that can be made they are correct).
The int + 0.5
causes real issues with -negative numbers, unless you want it to work that way, but I imagine most people don't. -0.9 should probably round to -1, not 0. If you know that you want negative to be a ceiling rather than a floor then you can do it in one-liner, otherwise, you might want to use the int method with a minor modification (this obviously only works to get back whole numbers:
my $var = -9.1;
my $tmpRounded = int( abs($var) + 0.5));
my $finalRounded = $var >= 0 ? 0 + $tmpRounded : 0 - $tmpRounded;
Unless I have misunderstood:
$("e").prepend("<yourelem>Text</yourelem>");
Or
$("<yourelem>Text</yourelem>").prependTo("e");
Although it sounds like from your description that there is some condition attached, so
if (SomeCondition){
$("e").prepend("<yourelem>Text</yourelem>");
}
else{
$("e").append("<yourelem>Text</yourelem>");
}
You can have it this way:
It is important to mind the commas after each struct item or set of items.
earnings := []LineItemsType{
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
}
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5. Happy coding!
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"
This is pattern to enter the date for textbox in HTML5.
The first one[0-9]{1,2} will take only decimal number minimum 1 and maximum 2.
And other similarly.
I have build such kind of application using approximatively the same approach except :
UIImage
but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.Whenever the user start zooming, I acquire the CGPDFPage
and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context
is like :
CGAffineTransform currentCTM = CGContextGetCTM(context);
if (currentCTM.a == 1.0 && baseImage) {
//Calculate ideal scale
CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height;
CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);
CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
@synchronized(issue) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
CGContextConcatCTM(context, pdfToPageTransform);
CGContextDrawPDFPage(context, pdfPage);
}
}
issue is the object containg the CGPDFDocumentRef
. I synchronize the part where I access the pdfDoc
property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef
object do some internal caching that I did not find how to get rid of.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 45.0f;
//set height according to row or section , whatever you want to do!
}
section label text are set.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *sectionHeaderView;
sectionHeaderView = [[UIView alloc] initWithFrame:
CGRectMake(0, 0, tableView.frame.size.width, 120.0)];
sectionHeaderView.backgroundColor = kColor(61, 201, 247);
UILabel *headerLabel = [[UILabel alloc] initWithFrame:
CGRectMake(sectionHeaderView.frame.origin.x,sectionHeaderView.frame.origin.y - 44, sectionHeaderView.frame.size.width, sectionHeaderView.frame.size.height)];
headerLabel.backgroundColor = [UIColor clearColor];
[headerLabel setTextColor:kColor(255, 255, 255)];
headerLabel.textAlignment = NSTextAlignmentCenter;
[headerLabel setFont:kFont(20)];
[sectionHeaderView addSubview:headerLabel];
switch (section) {
case 0:
headerLabel.text = @"Section 1";
return sectionHeaderView;
break;
case 1:
headerLabel.text = @"Section 2";
return sectionHeaderView;
break;
case 2:
headerLabel.text = @"Section 3";
return sectionHeaderView;
break;
default:
break;
}
return sectionHeaderView;
}
Actually you can do it in interface builder.
You should set Title to "Attributed" and then choose center alignment.
To expand on cristobalito's answer:
I assume you're talking about on the command-line - if it's in a script, then a new-line >acts as a command delimiter.
On the command line, use a semi-colon ';'
For example:
Sign a PowerShell script on the command-line. No line breaks.
powershell -Command "&{$cert=Get-ChildItem –Path cert:\CurrentUser\my -codeSigningCert ; Set-AuthenticodeSignature -filepath Z:\test.ps1 -Cert $cert}
You can iterate through each and every node and see if a node exists.
doc.Load(xmlPath);
XmlNodeList node = doc.SelectNodes("//Nodes/Node");
foreach (XmlNode chNode in node)
{
try{
if (chNode["innerNode"]==null)
return true; //node exists
//if ... check for any other nodes you need to
}catch(Exception e){return false; //some node doesn't exists.}
}
You iterate through every Node elements under Nodes (say this is root) and check to see if node named 'innerNode' (add others if you need) exists. try..catch is because I suspect this will throw popular 'object reference not set' error if the node does not exist.
A web api endpoint (controller) is a single resource that accepts get/post/put/delete verbs. It is not a normal MVC controller.
Necessarily, at /api/VTRouting
there can only be one HttpPost method that accepts the parameters you are sending. The function name does not matter, as long as you are decorating with the [http] stuff. I've never tried, though.
Edit: This does not work. In resolving, it seems to go by the number of parameters, not trying to model-bind to the type.
You can overload the functions to accept different parameters. I am pretty sure you would be OK if you declared it the way you do, but used different (incompatible) parameters to the methods. If the params are the same, you are out of luck as model binding won't know which one you meant.
[HttpPost]
public MyResult Route(MyRequestTemplate routingRequestTemplate) {...}
[HttpPost]
public MyResult TSPRoute(MyOtherTemplate routingRequestTemplate) {...}
This part works
The default template they give when you create a new one makes this pretty explicit, and I would say you should stick with this convention:
public class ValuesController : ApiController
{
// GET is overloaded here. one method takes a param, the other not.
// GET api/values
public IEnumerable<string> Get() { .. return new string[] ... }
// GET api/values/5
public string Get(int id) { return "hi there"; }
// POST api/values (OVERLOADED)
public void Post(string value) { ... }
public void Post(string value, string anotherValue) { ... }
// PUT api/values/5
public void Put(int id, string value) {}
// DELETE api/values/5
public void Delete(int id) {}
}
If you want to make one class that does many things, for ajax use, there is no big reason to not use a standard controller/action pattern. The only real difference is your method signatures aren't as pretty, and you have to wrap things in Json( returnValue)
before you return them.
Edit:
Overloading works just fine when using the standard template (edited to include) when using simple types. I've gone and tested the other way too, with 2 custom objects with different signatures. Never could get it to work.
This worked for me in this case, see where it gets you. Exception for testing only.
public class NerdyController : ApiController
{
public void Post(string type, Obj o) {
throw new Exception("Type=" + type + ", o.Name=" + o.Name );
}
}
public class Obj {
public string Name { get; set; }
public string Age { get; set; }
}
And called like this form the console:
$.post("/api/Nerdy?type=white", { 'Name':'Slim', 'Age':'21' } )
I was also wanted to upload stuff to a Server and it was a Spring application i finally discovered that I needed to acctually set an content type for it to interpret it as a file. Just like this:
...
MultipartFormDataContent form = new MultipartFormDataContent();
var fileStream = new FileStream(uniqueTempPathInProject, FileMode.Open);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType=new MediaTypeHeaderValue("application/zip");
form.Add(streamContent, "file",fileName);
...
No you cannot force a file that is already committed in the repo to be removed just because it is added to the .gitignore
You have to git rm --cached
to remove the files that you don't want in the repo. ( --cached since you probably want to keep the local copy but remove from the repo. ) So if you want to remove all the exe's from your repo do
git rm --cached /\*.exe
(Note that the asterisk * is quoted from the shell - this lets git, and not the shell, expand the pathnames of files and subdirectories)
On Windows Server 2012 R2 I had trouble to run from user account
psexec -u administrator -p password \\machinename -h -s -d -accepteula cmd.exe
But it works fine if you run without parameters -h -s
. That's why I use this to solve my trouble:
psexec -accepteula -u administrator -p password \\machinename %PathToLocalUtils%\psexec.exe -h -s -d cmd.exe
you can actually do it with numpy:
import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)
import { CSSProperties } from 'react'_x000D_
import { BLACK, BLUE, GREY_DARK, WHITE } from '../colours'_x000D_
_x000D_
export const COLOR_ACCENT = BLUE_x000D_
export const COLOR_DEFAULT = BLACK_x000D_
export const FAMILY = "'Segoe UI', sans-serif"_x000D_
export const SIZE_LARGE = '26px'_x000D_
export const SIZE_MEDIUM = '20px'_x000D_
export const WEIGHT = 400_x000D_
_x000D_
type Font = {_x000D_
color: string,_x000D_
size: string,_x000D_
accent: Font,_x000D_
default: Font,_x000D_
light: Font,_x000D_
neutral: Font,_x000D_
xsmall: Font,_x000D_
small: Font,_x000D_
medium: Font,_x000D_
large: Font,_x000D_
xlarge: Font,_x000D_
xxlarge: Font_x000D_
} & (() => CSSProperties)_x000D_
_x000D_
function font (this: Font): CSSProperties {_x000D_
const css = {_x000D_
color: this.color,_x000D_
fontFamily: FAMILY,_x000D_
fontSize: this.size,_x000D_
fontWeight: WEIGHT_x000D_
}_x000D_
delete this.color_x000D_
delete this.size_x000D_
return css_x000D_
}_x000D_
_x000D_
const dp = (type: 'color' | 'size', name: string, value: string) => {_x000D_
Object.defineProperty(font, name, { get () {_x000D_
this[type] = value_x000D_
return this_x000D_
}})_x000D_
}_x000D_
_x000D_
dp('color', 'accent', COLOR_ACCENT)_x000D_
dp('color', 'default', COLOR_DEFAULT)_x000D_
dp('color', 'light', COLOR_LIGHT)_x000D_
dp('color', 'neutral', COLOR_NEUTRAL)_x000D_
dp('size', 'xsmall', SIZE_XSMALL)_x000D_
dp('size', 'small', SIZE_SMALL)_x000D_
dp('size', 'medium', SIZE_MEDIUM)_x000D_
_x000D_
export default font as Font
_x000D_
Working Code:
<TextView
android:id="@+id/scroller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:text="Some veryyyyy long text with all the characters that cannot fit in screen, it so sad :( that I will not scroll"
android:textAppearance="?android:attr/textAppearanceLarge" />
Creating own answer, as nobody has considered that the split might not happened (shorter text). In that case we don't want to add '...' as suffix.
Ternary operator will sort that out:
var text = "blahalhahkanhklanlkanhlanlanhak";
var count = 35;
var result = text.slice(0, count) + (text.length > count ? "..." : "");
Can be closed to function:
function fn(text, count){
return text.slice(0, count) + (text.length > count ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10));
And expand to helpers class so You can even choose if You want the dots or not:
function fn(text, count, insertDots){
return text.slice(0, count) + (((text.length > count) && insertDots) ? "..." : "");
}
console.log(fn("aognaglkanglnagln", 10, true));
console.log(fn("aognaglkanglnagln", 10, false));
Use the following JavaScript to get the value after hash (#) from a URL. You don't need to use jQuery for that.
var hash = location.hash.substr(1);
I have got this code and tutorial from here - How to get hash value from URL using JavaScript
If you are looking to reduce the size using coding itself, you can follow this code in php.
<?php
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
$source_img = 'source.jpg';
$destination_img = 'destination .jpg';
$d = compress($source_img, $destination_img, 90);
?>
$d = compress($source_img, $destination_img, 90);
This is just a php function that passes the source image ( i.e., $source_img
), destination image ( $destination_img
) and quality for the image that will take to compress ( i.e., 90 ).
$info = getimagesize($source);
The getimagesize()
function is used to find the size of any given image file and return the dimensions along with the file type.
In order to make more concise you can declare constructor parameters as public
which automatically create properties with same names and these properties are available via this
:
export class Environment {
constructor(public id:number, public name:string) {}
getProperties() {
return `${this.id} : ${this.name}`;
}
}
let serverEnv = new Environment(80, 'port');
console.log(serverEnv);
---result---
// Environment { id: 80, name: 'port' }
Spanish ISO:
Please see this Question
You can only replace a "dynamically added fragment".
So, if you want to add a dynamic fragment, see this example.
It's been nearly five years since this post was first made, and JavaScript has come a long way. In repeating the tests in the original post, I found no consistent difference between the following test methods:
abc === undefined
abc === void 0
typeof abc == 'undefined'
typeof abc === 'undefined'
Even when I modified the tests to prevent Chrome from optimizing them away, the differences were insignificant. As such, I'd now recommend abc === undefined
for clarity.
Relevant content from chrome://version
:
In Google Chrome, the following was ever so slightly faster than a typeof
test:
if (abc === void 0) {
// Undefined
}
The difference was negligible. However, this code is more concise, and clearer at a glance to someone who knows what void 0
means. Note, however, that abc
must still be declared.
Both typeof
and void
were significantly faster than comparing directly against undefined
. I used the following test format in the Chrome developer console:
var abc;
start = +new Date();
for (var i = 0; i < 10000000; i++) {
if (TEST) {
void 1;
}
}
end = +new Date();
end - start;
The results were as follows:
Test: | abc === undefined abc === void 0 typeof abc == 'undefined'
------+---------------------------------------------------------------------
x10M | 13678 ms 9854 ms 9888 ms
x1 | 1367.8 ns 985.4 ns 988.8 ns
Note that the first row is in milliseconds, while the second row is in nanoseconds. A difference of 3.4 nanoseconds is nothing. The times were pretty consistent in subsequent tests.
I'm not sure I understand completely, but you might be looking for the 'formatoptions' configuration setting. Try something like :set formatoptions-=t
. The t
option will insert line breaks to make text wrap at the width set by textwidth
. You can also put this command in your .vimrc
, just remove the colon (:
).
There are a few things to change in your edited version:
You've taken the suggestion of using document.myform['whichThing']
a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].
There's no such thing as an action
attribute for the <input>
tag. Use onclick
instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault()
won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false
in the onclick tag as in number 2 above (or return false from the function as stephen suggested).
Because of #3, get rid of everything not the alert statement in your handler.
The code should now look like:
function handleClick()
{
alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
}
</script>
</head>
<body>
<form name="aye">
<input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>
Which of the following do you like best?
<p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
<p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
<p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>
INSERT INTO Destination SELECT * FROM Source;
See SQL As Understood By SQLite: INSERT for a formal definition.
If you use Dojo Toolkit:
require(["dojo/json"], function(JSON){
JSON.parse('{"hello":"world"}', true);
});
You can try:
var headingDiv = document.getElementById("head");
headingDiv.innerHTML = "<H3>Public Offers</H3>";
Haskell uses init
to refer to all but the last element of a list (the inverse of tail
, basically); would isInInit
work, or is that too opaque?
You could also try out http://code.google.com/p/android-multitouch-controller/
The library is really great, although initially a little hard to grasp.
Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:
conda install pyqt=4
This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example
conda install pyqt=4.11
would install the latest (or last) release of version 4.11.
Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.
package com.example.readfilefromexternalresource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
reader = new BufferedReader(new FileReader(textFile));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
There are many ways of doing it, I'm listing a few here.
Use Container
and give some height:
Column(
children: <Widget>[
Widget1(),
Container(height: 10), // set height
Widget2(),
],
)
Use Spacer
Column(
children: <Widget>[
Widget1(),
Spacer(), // use Spacer
Widget2(),
],
)
Use Expanded
Column(
children: <Widget>[
Widget1(),
Expanded(child: SizedBox()), // use Expanded
Widget2(),
],
)
Use mainAxisAlignment
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround, // mainAxisAlignment
children: <Widget>[
Widget1(),
Widget2(),
],
)
Use Wrap
Wrap(
direction: Axis.vertical, // make sure to set this
spacing: 20, // set your spacing
children: <Widget>[
Widget1(),
Widget2(),
],
)
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
You could use pandas.concat()
or DataFrame.append()
. For details and examples, see Merge, join, and concatenate.
I actually had solved this not long after posting but failed to post my solution. I honestly don't remember it. But, I had to re-visit the task when I was given a new project that faced the same challenge.
I used the ReceivedTime property of Outlook.MailItem to get the time-stamp, I was able to use this as a unique identifier for each file so they do not override one another.
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\PathToDirectory\"
Dim dateFormat As String
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
Next
End Sub
Thanks a ton for the other solutions, many of them go above an beyond :)
JTable.AUTO_RESIZE_LAST_COLUMN
is defined as "During all resize operations, apply adjustments to the last column only" which means you have to set the autoresizemode at the end of your code, otherwise setPreferredWidth() won't affect anything!
So in your case this would be the correct way:
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(400);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
<%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
[<%=System.Environment.MachineName%>]
<%}%>
for FILE in /var/www/html/files/*
do
/usr/bin/dos2unix FILE
done
I was playing around with this and tried all solutions, eventually the solution I went with was a suggestion from Google Chrome's Inspector. If you add this to your CSS it worked for me:
video{
object-fit: inherit;
}
Based on Wikipedia's articles.
A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one.
The idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.
This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.
For example, let's say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations of roads you might take, and will only then tell you which way is the fastest. Of course, you might have to wait for a while until the algorithm finishes, and only then can you start driving. The path you will take will be the fastest one (assuming that nothing changed in the external environment).
On the other hand, a greedy algorithm will start you driving immediately and will pick the road that looks the fastest at every intersection. As you can imagine, this strategy might not lead to the fastest arrival time, since you might take some "easy" streets and then find yourself hopelessly stuck in a traffic jam.
In mathematical optimization, greedy algorithms solve combinatorial problems having the properties of matroids.
Dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure.
C/C++ standard library <stdlib.h>
contains qsort
function.
This is not the best quick sort implementation in the world but it fast enough and VERY EASY to be used... the formal syntax of qsort is:
qsort(<arrayname>,<size>,sizeof(<elementsize>),compare_function);
The only thing that you need to implement is the compare_function, which takes in two arguments of type "const void", which can be cast to appropriate data structure, and then return one of these three values:
1. Comparing a list of integers:
simply cast a and b to integers
if x < y
,x-y
is negative, x == y
, x-y = 0
, x > y
, x-y
is positive
x-y
is a shortcut way to do it :)
reverse *x - *y
to *y - *x
for sorting in decreasing/reverse order
int compare_function(const void *a,const void *b) {
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;
}
2. Comparing a list of strings:
For comparing string, you need strcmp
function inside <string.h>
lib.
strcmp
will by default return -ve,0,ve appropriately... to sort in reverse order, just reverse the sign returned by strcmp
#include <string.h>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));
}
3. Comparing floating point numbers:
int compare_function(const void *a,const void *b) {
double *x = (double *) a;
double *y = (double *) b;
// return *x - *y; // this is WRONG...
if (*x < *y) return -1;
else if (*x > *y) return 1; return 0;
}
4. Comparing records based on a key:
Sometimes you need to sort a more complex stuffs, such as record. Here is the simplest
way to do it using qsort
library.
typedef struct {
int key;
double value;
} the_record;
int compare_function(const void *a,const void *b) {
the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;
}
You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:
$('div#id').click(function (e) {
// Do whatever you want
});
This solution has the distinct advantage of keeping the logic not in your markup.
While everyone will generally agree that Javascript encryption is a bad idea, there are a few small use cases where slowing down the attack is better than nothing. You can start with YUI Compressor (as @Ben Alpert) said, or JSMin, Uglify, or many more.
However, the main case in which I want to really 'hide stuff' is when I'm publishing an email address. Note, there is the problem of Chrome when you click on 'inspect element'. It will show your original code: every time. This is why obfuscation is generally regarded as being a better way to go.
On that note, I take a two pronged attack, purely to slow down spam bots. I Obfuscate/minify the js and then run it again through an encoder (again, this second step is completely pointless in chrome).
While not exactly a pure Javascript encoder, the best html encoder I have found is http://hivelogic.com/enkoder/. It will turn this:
<script type="text/javascript">
//<![CDATA[
<!--
var c=function(e) { var m="mail" + "to:webmaster";var a="somedomain"; e.href = m+"@"+a+".com";
};
//-->
//]]>
</script>
<a href="#" onclick="return c(this);"><img src="images/email.png" /></a>
into this:
<script type="text/javascript">
//<![CDATA[
<!--
var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
"=50){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return o" +
".substr(0,ol);}f(\")87,\\\"meozp?410\\\\=220\\\\s-dvwggd130\\\\#-2o,V_PY420" +
"\\\\I\\\\\\\\_V[\\\\\\\\620\\\\o710\\\\RB\\\\\\\\610\\\\JAB620\\\\720\\\\n\\"+
"\\{530\\\\410\\\\WJJU010\\\\|>snnn|j5J(771\\\\p{}saa-.W)+T:``vk\\\"\\\\`<02" +
"0\\\\!610\\\\'Dr\\\\010\\\\630\\\\400\\\\620\\\\700\\\\\\\\\\\\N730\\\\,530" +
"\\\\2S16EF600\\\\;420\\\\9ZNONO1200\\\\/000\\\\`'7400\\\\%n\\\\!010\\\\hpr\\"+
"\\= -cn720\\\\a(ce230\\\\500\\\\f730\\\\i,`200\\\\630\\\\[YIR720\\\\]720\\\\"+
"r\\\\720\\\\h][P]@JHADY310\\\\t230\\\\G500\\\\VBT230\\\\200\\\\Clxhh{tzra/{" +
"g0M0$./Pgche%Z8i#p`v^600\\\\\\\\\\\\R730\\\\Q620\\\\030\\\\730\\\\100\\\\72" +
"0\\\\530\\\\700\\\\720\\\\M410\\\\N730\\\\r\\\\530\\\\400\\\\4420\\\\8OM771" +
"\\\\`4400\\\\$010\\\\t\\\\120\\\\230\\\\r\\\\610\\\\310\\\\530\\\\e~o120\\\\"+
"RfJjn\\\\020\\\\lZ\\\\\\\\CZEWCV771\\\\v5lnqf2R1ox771\\\\p\\\"\\\\tr\\\\220" +
"\\\\310\\\\420\\\\600\\\\OSG300\\\\700\\\\410\\\\320\\\\410\\\\120\\\\620\\" +
"\\q)5<: 0>+\\\"(f};o nruter};))++y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;" +
"721=%y;++y)87<i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\\\"\\\"=o,i rav{)y,x(f noit" +
"cnuf\")" ;
while(x=eval(x));
//-->
//]]>
</script>
Maybe it's enough to slow down a few spam bots. I haven't had any spam come through using this (!yet).
Remove @ResponseBody annotation from your use parameters in method. Like this;
@Autowired
ProjectService projectService;
@RequestMapping(path = "/add", method = RequestMethod.POST)
public ResponseEntity<Project> createNewProject(Project newProject){
Project project = projectService.save(newProject);
return new ResponseEntity<Project>(project,HttpStatus.CREATED);
}
No, which is why so many other libraries have their own copy :)
Another recommended exersice for understanding lists and indexes:
L = ['a', 'b', 'c']
for index, item in enumerate(L):
print index + '\n' + item
0
a
1
b
2
c
If you want to know a property's underlying type, try this:
propInfo.PropertyType.UnderlyingSystemType.GenericTypeArguments[0]
You need to type it without the word image
.
background: url('/image/btn.png') no-repeat;
Tested both ways and this one works.
Example:
<html>
<head>
<style type="text/css">
.button{
background: url(/image/btn.png) no-repeat;
cursor:pointer;
border: none;
}
</style>
</head>
<body>
<input type="button" name="button" value="Search" onclick="showUser()" class="button"/>
<input type="image" name="button" value="Search" onclick="showUser()" class="button"/>
<input type="submit" name="button" value="Search" onclick="showUser()" class="button"/>
</body>
</html>
First I think you need to fix your lists, as the first node of a <ul>
must be a <li>
(stackoverflow ref). Once that is setup you can do this:
// note this array has outer scope
var phrases = [];
$('.phrase').each(function(){
// this is inner scope, in reference to the .phrase element
var phrase = '';
$(this).find('li').each(function(){
// cache jquery var
var current = $(this);
// check if our current li has children (sub elements)
// if it does, skip it
// ps, you can work with this by seeing if the first child
// is a UL with blank inside and odd your custom BLANK text
if(current.children().size() > 0) {return true;}
// add current text to our current phrase
phrase += current.text();
});
// now that our current phrase is completely build we add it to our outer array
phrases.push(phrase);
});
// note the comma in the alert shows separate phrases
alert(phrases);
Working jsfiddle.
One thing is if you get the .text()
of an upper level li
you will get all sub level text with it.
Keeping an array will allow for many multiple phrases to be extracted.
EDIT:
This should work better with an empty UL
with no LI
:
// outer scope
var phrases = [];
$('.phrase').each(function(){
// inner scope
var phrase = '';
$(this).find('li').each(function(){
// cache jquery object
var current = $(this);
// check for sub levels
if(current.children().size() > 0) {
// check is sublevel is just empty UL
var emptyULtest = current.children().eq(0);
if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
phrase += ' -BLANK- '; //custom blank text
return true;
} else {
// else it is an actual sublevel with li's
return true;
}
}
// if it gets to here it is actual li
phrase += current.text();
});
phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);
If you want to interpret $replace
, you should not use single quotes since they prevent variable substitution.
Try:
echo $LINE | sed -e "s/12345678/${replace}/g"
Transcript:
pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _
Just be careful to ensure that ${replace}
doesn't have any characters of significance to sed
(like /
for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.
In that case, it might be that you program exits before the writing can be finished.
If your program uses an event loop (like with a GUI application, e.g. QMainWindow
) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).
stream << "something" << endl;
stream.flush();
This guarantees that the changes are committed to the file before the program continues from this instruction.
The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.
I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.
I ran some tests (on postgres 9.5) using two tables with ~2M rows each. This query below performed at least 5* better than the other queries proposed:
-- Count
SELECT count(*) FROM (
(SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2;
-- Get full row
SELECT table1.* FROM (
(SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2 JOIN table1 ON t1_not_in_t2.id=table1.id;
There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.
I'll add that if you want to read the dimensions, you can do this:
int[][][] a = new int[4][3][2];
System.out.println(a.length); // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2
You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length
.
The correct syntax is described in the manual. Try this:
INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';
If the id columns is an auto-increment column and you already have some data in both tables then in some cases you may want to omit the id from the column list and generate new ids instead to avoid insert an id that already exists in the original table. If your target table is empty then this won't be an issue.
I had a similar problem and found out that all problem of this nature can be solved as follows:
and this way you'll be able to style your current, previous items(all items overridden with current and next items) and your next items.
example:
/* all items (will be styled as previous) */
li {
color: blue;
}
/* the item i want to distinguish */
li.milk {
color: red;
}
/* next items */
li ~ li {
color: green;
}
<ul>
<li>Tea</li>
<li class="milk">Milk</li>
<li>Juice</li>
<li>others</li>
</ul>
Hope it helps someone.
Of all the approaches, I find using org.apache.commons.collections.CollectionUtils#isEqualCollection
is the best approach. Here are the reasons -
If it's not possible to have apache.commons.collections
as a dependency, I would recommend to implement the algorithm it follows to check equality of the list because of it's efficiency.
In your case, $scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue);
does the trick - it makes both the form and the field dirty, and appends appropriate CSS classes.
Just to be honest, I found this solution in new post in the topic from the link from your question. It worked perfectly for me, so I am putting this here as a standalone answer to make it easier to be found.
EDIT:
Above solution works best for Angular version up to 1.3.3. Starting with 1.3.4 you should use newly exposed API method $setDirty()
from ngModel.NgModelController
.
2 Here a short ES6 variadic version:
function objectsHaveSameKeys(...objects) {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
const union = new Set(allKeys);
return objects.every(object => union.size === Object.keys(object).length);
}
A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):
var x = {};
var y = {};
for (var i = 0; i < 5000000; ++i) {
x[i] = i;
y[i] = i;
}
Results:
objectsHaveSameKeys(x, y) // took 4996 milliseconds
compareKeys(x, y) // took 14880 milliseconds
hasSameProps(x,y) // after 10 minutes I stopped execution
I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.
you can give an <a> tag the visual behavior of a table cell:
HTML:
<table>
<tr>
<a href="...">Cell 1</a>
<td>Cell 2</td>
</tr>
</table>
CSS:
tr > a {
display: table-cell;
}
We use these settings:
etc/my.cnf
innodb_buffer_pool_size = 384M
key_buffer = 256M
query_cache_size = 1M
query_cache_limit = 128M
thread_cache_size = 8
max_connections = 400
innodb_lock_wait_timeout = 100
for a server with the following specifications:
Dell Server
CPU cores: Two
Processor(s): 1x Dual Xeon
Clock Speed: >= 2.33GHz
RAM: 2 GBytes
Disks: 1×250 GB SATA
The stemmer vs lemmatizer debates goes on. It's a matter of preferring precision over efficiency. You should lemmatize to achieve linguistically meaningful units and stem to use minimal computing juice and still index a word and its variations under the same key.
Here's an example with python NLTK:
>>> sent = "cats running ran cactus cactuses cacti community communities"
>>> from nltk.stem import PorterStemmer, WordNetLemmatizer
>>>
>>> port = PorterStemmer()
>>> " ".join([port.stem(i) for i in sent.split()])
'cat run ran cactu cactus cacti commun commun'
>>>
>>> wnl = WordNetLemmatizer()
>>> " ".join([wnl.lemmatize(i) for i in sent.split()])
'cat running ran cactus cactus cactus community community'
Use this function to find all script elements containing some word and refresh them.
function forceReloadJS(srcUrlContains) {_x000D_
$.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {_x000D_
var oldSrc = $(el).attr('src');_x000D_
var t = +new Date();_x000D_
var newSrc = oldSrc + '?' + t;_x000D_
_x000D_
console.log(oldSrc, ' to ', newSrc);_x000D_
_x000D_
$(el).remove();_x000D_
$('<script/>').attr('src', newSrc).appendTo('head');_x000D_
});_x000D_
}_x000D_
_x000D_
forceReloadJS('/libs/');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
_x000D_
To hide the ActionBar add this code into java file.
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
To pad int i
to match the string length of int x
, when both can be negative:
i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')
If your project is Maven-based you can run all test-methods from test-class CustomTest which belongs to module 'my-module' using next command:
mvn clean test -pl :my-module -Dtest=CustomTest
Or run only 1 test-method myMethod from test-class CustomTest using next command:
mvn clean test -pl :my-module -Dtest=CustomTest#myMethod
For this ability you need Maven Surefire Plugin v.2.7.3+ and Junit 4. More details is here: http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html
For jQuery 1.9+ as Dunstkreis mentioned .data('events') was removed. But you can use another hack (it is not recommended to use undocumented possibilities) $._data($(this).get(0), 'events') instead and solution provided by anurag will look like:
$.fn.bindFirst = function(name, fn) {
this.bind(name, fn);
var handlers = $._data($(this).get(0), 'events')[name.split('.')[0]];
var handler = handlers.pop();
handlers.splice(0, 0, handler);
};
EOF is -1 because that's how it's defined. The name is provided by the standard library headers that you #include
. They make it equal to -1 because it has to be something that can't be mistaken for an actual byte read by getchar()
. getchar()
reports the values of actual bytes using positive number (0 up to 255 inclusive), so -1 works fine for this.
The !=
operator means "not equal". 0 stands for false, and anything else stands for true. So what happens is, we call the getchar()
function, and compare the result to -1 (EOF). If the result was not equal to EOF, then the result is true, because things that are not equal are not equal. If the result was equal to EOF, then the result is false, because things that are equal are not (not equal).
The call to getchar()
returns EOF when you reach the "end of file". As far as C is concerned, the 'standard input' (the data you are giving to your program by typing in the command window) is just like a file. Of course, you can always type more, so you need an explicit way to say "I'm done". On Windows systems, this is control-Z. On Unix systems, this is control-D.
The example in the book is not "wrong". It depends on what you actually want to do. Reading until EOF means that you read everything, until the user says "I'm done", and then you can't read any more. Reading until '\n' means that you read a line of input. Reading until '\0' is a bad idea if you expect the user to type the input, because it is either hard or impossible to produce this byte with a keyboard at the command prompt :)
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
Big difference, TABLOCK
will try to grab "shared" locks, and TABLOCKX
exclusive locks.
If you are in a transaction and you grab an exclusive lock on a table, EG:
SELECT 1 FROM TABLE WITH (TABLOCKX)
No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.
TABLOCK
only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED
(default). If your isolation level is higher, for example: SERIALIZABLE
, shared locks are held until the end of a transaction.
Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK
). However, if transaction A
holds a shared lock on a table, transaction B
will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.
Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).
In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.
In general you would not use TABLOCK
or TABLOCKX
unless you absolutely needed it for some edge case.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId
.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
I had the same issue in a Windows Service. All keys where in the right place in the registry. The build of the service was done for x86 and I still got the exception. I found out about CorFlags.exe
Run this on your service.exe
without flags to verify if you run under 32 bit. If not run it with the flag /32BIT+ /Force
(Force only for signed assemblies)
If you have UAC turned you can get the following error: corflags : error CF001 : Could not open file for writing
Give the user full control on the assemblies.
The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).
I suggest:
if (cursor.getCount() > 0) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
<do stuff>
}
}
You can use \n for new line
alert("Welcome\nto Jumanji");
alert("Welcome\nto Jumanji");
_x000D_
Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).
Setting overflow: hidden
on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.
I wonder why people are not highlighting the MOST compelling reason in favor of EFS. EFS can be mounted on more than one EC2 instance at the same time, enabling access to files on EFS at the same time.
(Edit 2020 May, EBS supports mounting to multiple EC2 at same time now as well, see: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html)
use this simple cod:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* Modal Content (image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* Caption of Modal Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* Add Animation */
.modal-content, #caption {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
@-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
@keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
.modal-content {
width: 100%;
}
}
</style>
</head>
<body>
<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>
<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("modal")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
</body>
</html>
this code open and close your photo.
To take the definitions the other mentioned earlier a bit further, how about this perspective...
LDAP is Lightweight Directory Access Protocol. DAP, is an X.500 notion, and in X.500 is VERY heavy weight! (It sort of requires a full 7 layer ISO network stack, which basically only IBM's SNA protocol ever realistically implemented).
There are many other approaches to DAP. Novell has one called NDAP (NCP Novell Core Protocols are the transport, and NDAP is how it reads the directory).
LDAP is just a very lightweight DAP, as the name suggests.
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
Here is some example code to help you get started:
package com.acme;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileArrayProvider {
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
And an example unit test:
package com.acme;
import java.io.IOException;
import org.junit.Test;
public class FileArrayProviderTest {
@Test
public void testFileArrayProvider() throws IOException {
FileArrayProvider fap = new FileArrayProvider();
String[] lines = fap
.readLines("src/main/java/com/acme/FileArrayProvider.java");
for (String line : lines) {
System.out.println(line);
}
}
}
Hope this helps.
As per ECMAScript 6 specification, you can use findIndex
.
const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');
magenicIndex
will hold either 0
(which is the index in the array) or -1
if it wasn't found.
rgl
is great, but takes a bit of experimentation to get the axes right.
If you have a lot of points, why not take a random sample from them, and then plot the resulting surface. You can add several surfaces all based on samples from the same data to see if the process of sampling is horribly affecting your data.
So, here is a pretty horrible function but it does what I think you want it to do (but without the sampling). Given a matrix (x, y, z) where z is the heights it will plot both the points and also a surface. Limitations are that there can only be one z for each (x,y) pair. So planes which loop back over themselves will cause problems.
The plot_points = T
will plot the individual points from which the surface is made - this is useful to check that the surface and the points actually meet up. The plot_contour = T
will plot a 2d contour plot below the 3d visualization. Set colour to rainbow
to give pretty colours, anything else will set it to grey, but then you can alter the function to give a custom palette. This does the trick for me anyway, but I'm sure that it can be tidied up and optimized. The verbose = T
prints out a lot of output which I use to debug the function as and when it breaks.
plot_rgl_model_a <- function(fdata, plot_contour = T, plot_points = T,
verbose = F, colour = "rainbow", smoother = F){
## takes a model in long form, in the format
## 1st column x
## 2nd is y,
## 3rd is z (height)
## and draws an rgl model
## includes a contour plot below and plots the points in blue
## if these are set to TRUE
# note that x has to be ascending, followed by y
if (verbose) print(head(fdata))
fdata <- fdata[order(fdata[, 1], fdata[, 2]), ]
if (verbose) print(head(fdata))
##
require(reshape2)
require(rgl)
orig_names <- colnames(fdata)
colnames(fdata) <- c("x", "y", "z")
fdata <- as.data.frame(fdata)
## work out the min and max of x,y,z
xlimits <- c(min(fdata$x, na.rm = T), max(fdata$x, na.rm = T))
ylimits <- c(min(fdata$y, na.rm = T), max(fdata$y, na.rm = T))
zlimits <- c(min(fdata$z, na.rm = T), max(fdata$z, na.rm = T))
l <- list (x = xlimits, y = ylimits, z = zlimits)
xyz <- do.call(expand.grid, l)
if (verbose) print(xyz)
x_boundaries <- xyz$x
if (verbose) print(class(xyz$x))
y_boundaries <- xyz$y
if (verbose) print(class(xyz$y))
z_boundaries <- xyz$z
if (verbose) print(class(xyz$z))
if (verbose) print(paste(x_boundaries, y_boundaries, z_boundaries, sep = ";"))
# now turn fdata into a wide format for use with the rgl.surface
fdata[, 2] <- as.character(fdata[, 2])
fdata[, 3] <- as.character(fdata[, 3])
#if (verbose) print(class(fdata[, 2]))
wide_form <- dcast(fdata, y ~ x, value_var = "z")
if (verbose) print(head(wide_form))
wide_form_values <- as.matrix(wide_form[, 2:ncol(wide_form)])
if (verbose) print(wide_form_values)
x_values <- as.numeric(colnames(wide_form[2:ncol(wide_form)]))
y_values <- as.numeric(wide_form[, 1])
if (verbose) print(x_values)
if (verbose) print(y_values)
wide_form_values <- wide_form_values[order(y_values), order(x_values)]
wide_form_values <- as.numeric(wide_form_values)
x_values <- x_values[order(x_values)]
y_values <- y_values[order(y_values)]
if (verbose) print(x_values)
if (verbose) print(y_values)
if (verbose) print(dim(wide_form_values))
if (verbose) print(length(x_values))
if (verbose) print(length(y_values))
zlim <- range(wide_form_values)
if (verbose) print(zlim)
zlen <- zlim[2] - zlim[1] + 1
if (verbose) print(zlen)
if (colour == "rainbow"){
colourut <- rainbow(zlen, alpha = 0)
if (verbose) print(colourut)
col <- colourut[ wide_form_values - zlim[1] + 1]
# if (verbose) print(col)
} else {
col <- "grey"
if (verbose) print(table(col2))
}
open3d()
plot3d(x_boundaries, y_boundaries, z_boundaries,
box = T, col = "black", xlab = orig_names[1],
ylab = orig_names[2], zlab = orig_names[3])
rgl.surface(z = x_values, ## these are all different because
x = y_values, ## of the confusing way that
y = wide_form_values, ## rgl.surface works! - y is the height!
coords = c(2,3,1),
color = col,
alpha = 1.0,
lit = F,
smooth = smoother)
if (plot_points){
# plot points in red just to be on the safe side!
points3d(fdata, col = "blue")
}
if (plot_contour){
# plot the plane underneath
flat_matrix <- wide_form_values
if (verbose) print(flat_matrix)
y_intercept <- (zlim[2] - zlim[1]) * (-2/3) # put the flat matrix 1/2 the distance below the lower height
flat_matrix[which(flat_matrix != y_intercept)] <- y_intercept
if (verbose) print(flat_matrix)
rgl.surface(z = x_values, ## these are all different because
x = y_values, ## of the confusing way that
y = flat_matrix, ## rgl.surface works! - y is the height!
coords = c(2,3,1),
color = col,
alpha = 1.0,
smooth = smoother)
}
}
The add_rgl_model
does the same job without the options, but overlays a surface onto the existing 3dplot.
add_rgl_model <- function(fdata){
## takes a model in long form, in the format
## 1st column x
## 2nd is y,
## 3rd is z (height)
## and draws an rgl model
##
# note that x has to be ascending, followed by y
print(head(fdata))
fdata <- fdata[order(fdata[, 1], fdata[, 2]), ]
print(head(fdata))
##
require(reshape2)
require(rgl)
orig_names <- colnames(fdata)
#print(head(fdata))
colnames(fdata) <- c("x", "y", "z")
fdata <- as.data.frame(fdata)
## work out the min and max of x,y,z
xlimits <- c(min(fdata$x, na.rm = T), max(fdata$x, na.rm = T))
ylimits <- c(min(fdata$y, na.rm = T), max(fdata$y, na.rm = T))
zlimits <- c(min(fdata$z, na.rm = T), max(fdata$z, na.rm = T))
l <- list (x = xlimits, y = ylimits, z = zlimits)
xyz <- do.call(expand.grid, l)
#print(xyz)
x_boundaries <- xyz$x
#print(class(xyz$x))
y_boundaries <- xyz$y
#print(class(xyz$y))
z_boundaries <- xyz$z
#print(class(xyz$z))
# now turn fdata into a wide format for use with the rgl.surface
fdata[, 2] <- as.character(fdata[, 2])
fdata[, 3] <- as.character(fdata[, 3])
#print(class(fdata[, 2]))
wide_form <- dcast(fdata, y ~ x, value_var = "z")
print(head(wide_form))
wide_form_values <- as.matrix(wide_form[, 2:ncol(wide_form)])
x_values <- as.numeric(colnames(wide_form[2:ncol(wide_form)]))
y_values <- as.numeric(wide_form[, 1])
print(x_values)
print(y_values)
wide_form_values <- wide_form_values[order(y_values), order(x_values)]
x_values <- x_values[order(x_values)]
y_values <- y_values[order(y_values)]
print(x_values)
print(y_values)
print(dim(wide_form_values))
print(length(x_values))
print(length(y_values))
rgl.surface(z = x_values, ## these are all different because
x = y_values, ## of the confusing way that
y = wide_form_values, ## rgl.surface works!
coords = c(2,3,1),
alpha = .8)
# plot points in red just to be on the safe side!
points3d(fdata, col = "red")
}
So my approach would be to, try to do it with all your data (I easily plot surfaces generated from ~15k points). If that doesn't work, take several smaller samples and plot them all at once using these functions.
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
As of version 3.0.0, you can get the current route by calling:
this.context.router.location.pathname
Sample code is below:
var NavLink = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
render() {
return (
<Link {...this.props}></Link>
);
}
});
The value is correctly selected, but you didn't see it because the plugin hide the real select and show a button with an unordered list, so, if you want that the user see the selected value on the select you can do something like this:
//Get the text using the value of select
var text = $("select[name=selValue] option[value='1']").text();
//We need to show the text inside the span that the plugin show
$('.bootstrap-select .filter-option').text(text);
//Check the selected attribute for the real select
$('select[name=selValue]').val(1);
Like @blushrt points out, a better solution is:
$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh')
To select multiple values, pass the values as an array.
To add to Jason's answer:
You can speed the process up (which might be helpful for very large exponents) using the binary expansion of the exponent. First calculate 5, 5^2, 5^4, 5^8 mod 221 - you do this by repeated squaring:
5^1 = 5(mod 221)
5^2 = 5^2 (mod 221) = 25(mod 221)
5^4 = (5^2)^2 = 25^2(mod 221) = 625 (mod 221) = 183(mod221)
5^8 = (5^4)^2 = 183^2(mod 221) = 33489 (mod 221) = 118(mod 221)
5^16 = (5^8)^2 = 118^2(mod 221) = 13924 (mod 221) = 1(mod 221)
5^32 = (5^16)^2 = 1^2(mod 221) = 1(mod 221)
Now we can write
55 = 1 + 2 + 4 + 16 + 32
so 5^55 = 5^1 * 5^2 * 5^4 * 5^16 * 5^32
= 5 * 25 * 625 * 1 * 1 (mod 221)
= 125 * 625 (mod 221)
= 125 * 183 (mod 183) - because 625 = 183 (mod 221)
= 22875 ( mod 221)
= 112 (mod 221)
You can see how for very large exponents this will be much faster (I believe it's log as opposed to linear in b, but not certain.)
You can use this with HTTPClient API.
public RestTemplate getRestTemplateBypassingHostNameVerifcation() {
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
My installer copied a log.txt file which had been generated on an XP computer. I was looking at that log file thinking it was generated on Vista. Once I fixed my log4net configuration to be "Vista Compatible". Environment.GetFolderPath was returning the expected results. Therefore, I'm closing this post.
The following SpecialFolder path reference might be useful:
Output On Windows Server 2003:
SpecialFolder.ApplicationData: C:\Documents and Settings\blake\Application Data SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Documents and Settings\blake\Desktop SpecialFolder.LocalApplicationData: C:\Documents and Settings\blake\Local Settings\Application Data SpecialFolder.MyDocuments: C:\Documents and Settings\blake\My Documents SpecialFolder.System: C:\WINDOWS\system32`
Output on Vista:
SpecialFolder.ApplicationData: C:\Users\blake\AppData\Roaming SpecialFolder.CommonApplicationData: C:\ProgramData SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Users\blake\Desktop SpecialFolder.LocalApplicationData: C:\Users\blake\AppData\Local SpecialFolder.MyDocuments: C:\Users\blake\Documents SpecialFolder.System: C:\Windows\system32
Dot operator can't be overloaded, arrow operator can be overloaded. Arrow operator is generally meant to be applied to pointers (or objects that behave like pointers, like smart pointers). Dot operator can't be applied to pointers.
EDIT
When applied to pointer arrow operator is equivalent to applying dot operator to pointee e.g. ptr->field
is equivalent to (*ptr).field
.
Simplest of all solutions:
filtered_df = df[df['var2'].isnull()]
This filters and gives you rows which has only NaN
values in 'var2'
column.
had similar problem, issue was different versions of included library. to find out what causes problem run build command with stacktrace
./gradlew build --stacktrace
Read up the concept of a name space. When you assign a variable in a function, you only assign it in the namespace of this function. But clearly you want to use it between all functions.
def defineAList():
#list = ['1','2','3'] this creates a new list, named list in the current namespace.
#same name, different list!
list.extend['1', '2', '3', '4'] #this uses a method of the existing list, which is in an outer namespace
print "For checking purposes: in defineAList, list is",list
return list
Alternatively, you can pass it around:
def main():
new_list = defineAList()
useTheList(new_list)
For drawable resource
you can use standard android images :
http://androiddrawables.com/Menu.html
For example :
android:background="@android:drawable/ic_menu_close_clear_cancel"
Forget about the react first:
This is not related to react and let us understand the basic concepts of Java Script. For Example you have written following function in java script (name is A).
function a() {
};
Q.1) How to call the function that we have defined?
Ans: a();
Q.2) How to pass reference of function so that we can call it latter?
Ans: let fun = a;
Now coming to your question, you have used paranthesis with function name, mean that function will be called when following statement will be render.
<td><span onClick={this.toggle()}>Details</span></td>
_x000D_
Then How to correct it?
Simple!! Just remove parenthesis. By this way you have given the reference of that function to onClick event. It will call back your function only when your component is clicked.
<td><span onClick={this.toggle}>Details</span></td>
_x000D_
One suggestion releated to react:
Avoid using inline function as suggested by someone in answers, it may cause performance issue.
Avoid following code, It will create instance of same function again and again whenever function will be called (lamda statement creates new instance every time).
Note: and no need to pass event (e) explicitly to the function. you can access it with in the function without passing it.
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
_x000D_
https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578
From: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
This is what you need :)
The following code will return a JavaScript Object containing the URL parameters:
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
For example, if you have the URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
This code will return:
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
and you can do:
var me = getUrlVars()["me"];
var name2 = getUrlVars()["name2"];
if you are using a variable name in the shell command, you must concatenate it with +
sign.
for example :
if you have two files, and you are not going to hard code the file name, instead you want to use the variable name
"input.txt" = x
"output.txt" = y
then ('shell command within quotes' + x > + y)
it will work this way especially if you are using this inside a python program with os.system command probably
The most efficient way is to consider the exponential growth of the multiplications. Check this code for p^q:
template <typename T>
T expt(T p, unsigned q){
T r =1;
while (q != 0) {
if (q % 2 == 1) { // if q is odd
r *= p;
q--;
}
p *= p;
q /= 2;
}
return r;
}
LISKOV SUBSTITUTION PRINCIPLE (From Mark Seemann book) states that we should be able to replace one implementation of an interface with another without breaking either client or implementation.It’s this principle that enables to address requirements that occur in the future, even if we can’t foresee them today.
If we unplug the computer from the wall (Implementation), neither the wall outlet (Interface) nor the computer (Client) breaks down (in fact, if it’s a laptop computer, it can even run on its batteries for a period of time). With software, however, a client often expects a service to be available. If the service was removed, we get a NullReferenceException. To deal with this type of situation, we can create an implementation of an interface that does “nothing.” This is a design pattern known as Null Object,[4] and it corresponds roughly to unplugging the computer from the wall. Because we’re using loose coupling, we can replace a real implementation with something that does nothing without causing trouble.
You should initialize your variables outside the while loop. Outside the while loop, they currently have no scope. You are just relying on the good graces of php to let the values carry over outside the loop
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
while (...){}
alternatively, it looks like you are just expecting a single row back. so you could just say
$row = pg_fetch_array($result);
if(!row) {
return array();
}
$hn = $row["patient_hn"];
$pid = $row["patient_id"];
$datereg = $row["patient_date_register"];
$prefix = $row["patient_prefix"];
$fname = $row["patient_fname"];
$lname = $row["patient_lname"];
$age = $row["patient_age"];
$sex = $row["patient_sex"];
return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex) ;
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
For Python 3.2 scripts, the only choice is cx_Freeze. Build it from sources; otherwise it won't work.
For Python 2.x I suggest PyInstaller as it can package a Python program in a single executable, unlike cx_Freeze which outputs also libraries.
Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable
jQuery(function(){
//here it is a closure variable
var a_href;
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
To make the variable global, one solution is to declare the variable in global scope
var a_href;
jQuery(function(){
$('sth a').on('click', function(e){
a_href = $(this).attr('href');
console.log(a_href);
//output is "home"
e.preventDefault();
}
})
another is to set the variable as a property of the window object
window.a_href = $(this).attr('href')
Why console printing undefined
You are getting the output as undefined
because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a
element is clicked till that time the variable will have the value undefined
. If you are not declaring the variable it will throw a ReferenceError
Or can say whats fields not will expose with:
Gson gson = gsonBuilder.excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
on your class on attribute:
private **transient** boolean nameAttribute;
A "little" late to the party but the real answer to this - if you use Oracle.ManagedDataAccess
ODP.NET provider, you should forget about things like network\admin
, Oracle client
, Oracle_Home
, etc.
Here is what you need
C:\Program Files (x86)
. With full dev tools, under 60MbAt this point you have 2 options to connect.
a) In the connection string set datasource
in the following format
DataSource=ServerName:Port/SID . . .
or DataSource=IP:Port/SID . . .
b) Create tnsnames.ora
file (only it is going to be different from previous experiences). Have entry in it:
AAA = (DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ServerNameOrIP)(PORT = 1521))
(CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = SIDNAME)))
And place this file into your bin folder, where your application is running from.
Now you can connect using your connection name - DataSource=AAA . . .
So, even though you have tnsnames.ora, with ODP.net managed it works a bit different - you create local TNS file. And now, it is easy to manage it.
To summarize - with managed, no need for heavy Oracle Client, Oracle_home
or knowing depths of oracle installation folders. Everything can be done within your .net application structures.
I highly recommend using $.when() if you're starting from scratch.
Even though this question has over million answers, I still didn't find anything useful for my case. Let's say you have to deal with an existing codebase, already making some ajax calls and don't want to introduce the complexity of promises and/or redo the whole thing.
We can easily take advantage of jQuery .data
, .on
and .trigger
functions which have been a part of jQuery since forever.
The good stuff about my solution is:
it's obvious what the callback exactly depends on
the function triggerNowOrOnLoaded
doesn't care if the data has been already loaded or we're still waiting for it
it's super easy to plug it into an existing code
$(function() {_x000D_
_x000D_
// wait for posts to be loaded_x000D_
triggerNowOrOnLoaded("posts", function() {_x000D_
var $body = $("body");_x000D_
var posts = $body.data("posts");_x000D_
_x000D_
$body.append("<div>Posts: " + posts.length + "</div>");_x000D_
});_x000D_
_x000D_
_x000D_
// some ajax requests_x000D_
$.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {_x000D_
$("body").data("posts", data).trigger("posts");_x000D_
});_x000D_
_x000D_
// doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests _x000D_
$.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {_x000D_
$("body").data("users", data).trigger("users");_x000D_
});_x000D_
_x000D_
_x000D_
// wait for both types_x000D_
triggerNowOrOnLoaded(["posts", "users"], function() {_x000D_
var $body = $("body");_x000D_
var posts = $body.data("posts");_x000D_
var users = $body.data("users");_x000D_
_x000D_
$body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");_x000D_
});_x000D_
_x000D_
// works even if everything has already loaded!_x000D_
setTimeout(function() {_x000D_
_x000D_
// triggers immediately since users have been already loaded_x000D_
triggerNowOrOnLoaded("users", function() {_x000D_
var $body = $("body");_x000D_
var users = $body.data("users");_x000D_
_x000D_
$body.append("<div>Delayed Users: " + users.length + "</div>");_x000D_
});_x000D_
_x000D_
}, 2000); // 2 seconds_x000D_
_x000D_
});_x000D_
_x000D_
// helper function_x000D_
function triggerNowOrOnLoaded(types, callback) {_x000D_
types = $.isArray(types) ? types : [types];_x000D_
_x000D_
var $body = $("body");_x000D_
_x000D_
var waitForTypes = [];_x000D_
$.each(types, function(i, type) {_x000D_
_x000D_
if (typeof $body.data(type) === 'undefined') {_x000D_
waitForTypes.push(type);_x000D_
}_x000D_
});_x000D_
_x000D_
var isDataReady = waitForTypes.length === 0;_x000D_
if (isDataReady) {_x000D_
callback();_x000D_
return;_x000D_
}_x000D_
_x000D_
// wait for the last type and run this function again for the rest of the types_x000D_
var waitFor = waitForTypes.pop();_x000D_
$body.on(waitFor, function() {_x000D_
// remove event handler - we only want the stuff triggered once_x000D_
$body.off(waitFor);_x000D_
_x000D_
triggerNowOrOnLoaded(waitForTypes, callback);_x000D_
});_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>Hi!</body>
_x000D_
I had the same problem when using bootstrap-datewidget and i loaded jquery in the header instead of loading it at the end of the body and it worked.
Very possibly it's getting converted to a modified Base64, where the +
and /
characters are changed to -
and _
. See http://en.wikipedia.org/wiki/Base64#Implementations_and_history
If that's the case, you need to change it back:
string converted = base64String.Replace('-', '+');
converted = converted.Replace('_', '/');
You have to pass a function to expect
. Like this:
expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));
The way you are doing it, you are passing to expect
the result of calling model.get('z')
. But to test whether something is thrown, you have to pass a function to expect
, which expect
will call itself. The bind
method used above creates a new function which when called will call model.get
with this
set to the value of model
and the first argument set to 'z'
.
A good explanation of bind
can be found here.
Write the queue job information in long format to text file
qstat -f > queue.txt
Grep job names
grep 'Job_Name' queue.txt
In windows environment with Anconda. Go to anconda prompt from start. Then if you are behind proxy then .copndarc file needs to eb updated with the proxy details.
ssl_verify: false channels: - defaults proxy_servers: http: http://xx.xx.xx.xx:xxxx https: https://xx.xx.xx.xx:xxxx
I had ssl_verify initially marked as 'True' then I was getting ssl error. So i turned it to false as above and then ran the below commands
conda update conda conda update --all conda install --channel https://conda.anaconda.org/conda-forge keras conda install --channel https://conda.anaconda.org/conda-forge tensorflow
My python version is 3.6.7
You could try this:
$width:auto;
@mixin clearfix($width) {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
I'm not sure of your intended result, but setting a default value should return false.
This worked for me:
h1 {
display: inline;
overflow: hidden;
}
div {
position: relative;
float: right;
}
It's similar to the approach of the media object, by Stubbornella.
Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)
This will work. Define this, then call it from when you need it. (Good for button logic if you are making a clear button):
Sub ResetFilters()
On Error Resume Next
ActiveSheet.ShowAllData
End Sub
The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).
The practical difference comes when using a local branch named differently:
git checkout -b mybranch origin/abranch
will create mybranch
and track origin/abranch
git checkout --track origin/abranch
will only create 'abranch
', not a branch with a different name.(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch
)
Note: with Git 2.23 (Q3 2019), that would use the new command git switch
:
git switch -c <branch> --track <remote>/<branch>
If the branch exists in multiple remotes and one of them is named by the
checkout.defaultRemote
configuration variable, we'll use that one for the purposes of disambiguation, even if the<branch>
isn't unique across all remotes.
Set it to e.g.checkout.defaultRemote=origin
to always checkout remote branches from there if<branch>
is ambiguous but exists on the 'origin' remote.
Here, '-c
' is the new '-b
'.
First, some background: Tracking means that a local branch has its upstream set to a remote branch:
# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch
git checkout -b branch origin/branch
will:
branch
to the point referenced by origin/branch
.branch
(with git branch
) and track the remote tracking branch origin/branch
. When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the
branch.<name>.remote
andbranch.<name>.merge
configuration entries) so thatgit pull
will appropriately merge from the remote-tracking branch.
This behavior may be changed via the globalbranch.autosetupmerge
configuration flag. That setting can be overridden by using the--track
and--no-track
options, and changed later using git branch--set-upstream-to
.
And git checkout --track origin/branch
will do the same as git branch --set-upstream-to
):
# or, since 1.7.0
git branch --set-upstream upstream/branch branch
# or, since 1.8.0 (October 2012)
git branch --set-upstream-to upstream/branch branch
# the short version remains the same:
git branch -u upstream/branch branch
It would also set the upstream for 'branch
'.
(Note: git1.8.0 will deprecate git branch --set-upstream
and replace it with git branch -u|--set-upstream-to
: see git1.8.0-rc1 announce)
Having an upstream branch registered for a local branch will:
git status
and git branch -v
. git pull
without arguments to pull from the upstream when the new branch is checked out.See "How do you make an existing git branch track a remote branch?" for more.
plt.setp()
will do the job:
# plot something
fig, axs = plt.subplots(3,3, figsize=(15, 8), sharex=True, sharey=True)
for i, ax in enumerate(axs.flat):
ax.scatter(*np.random.normal(size=(2,200)))
ax.set_title(f'Title {i}')
# set labels
plt.setp(axs[-1, :], xlabel='x axis label')
plt.setp(axs[:, 0], ylabel='y axis label')
To get the location when the user clicks on a button call this method in the onClick-
void getCurrentLocation() {
Location myLocation = mMap.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
Log.i("APPLICATION"," : "+dLatitude);
Log.i("APPLICATION"," : "+dLongitude);
mMap.addMarker(new MarkerOptions().position(
new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}
Also make sure that the
setMyLocationEnabled
is set to true.
Try and see if this works...
I've used jQuery MultiSelect for implementing multiselect drop down menu with checkbox. You can see the implementation guide from here - Multi-select Dropdown List with Checkbox
Implementation is very simple, need only using the following code.
$('#transactionType').multiselect({
columns: 1,
placeholder: 'Select Transaction Type'
});
Open AVD manager and click on the drop down along side with your emulator and select the show in disk and delete the file with .lock extension. After deleted, run your emulator. That works for me.
if (rs == null || !rs.first()) { //empty } else { //not empty }
Note that after this method call, if the resultset is not empty, it is at the beginning.
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
I realize this is a belated answer, but looking through developer.android.com, it seems that the Toggle button would be ideal for your situation.
http://developer.android.com/guide/topics/ui/controls/togglebutton.html
And of course you can still use the other suggestions for having a background drawable to get a custom look you want.
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/custom_button_background"
android:textOn="On"
android:textOff="Off"
/>
Now if you want to go with your final edit and have a "halo" effect around your buttons, you can use another custom selector to do just that.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" > <!-- selected -->
<shape>
<solid
android:color="@android:color/white" />
<stroke
android:width="3px"
android:color="@android:color/holo_blue_bright" />
<corners
android:radius="5dp" />
</shape>
</item>
<item> <!-- default -->
<shape>
<solid
android:color="@android:color/white" />
<stroke
android:width="1px"
android:color="@android:color/darker_gray" />
<corners
android:radius="5dp" />
</shape>
</item>
</selector>
Vlookup
is good if the reference values (column A, sheet 1) are in ascending order. Another option is Index and Match, which can be used no matter the order (As long as the values in column a, sheet 1 are unique)
This is what you would put in column B on sheet 2
=INDEX(Sheet1!A$1:B$6,MATCH(A1,Sheet1!A$1:A$6),2)
Setting Sheet1!A$1:B$6
and Sheet1!A$1:A$6
as named ranges makes it a little more user friendly.
While I agree about not adhering blindly to dogmatic rules, does the "lock stealing" scenario seem so eccentric to you? A thread could indeed acquire the lock on your object "externally"(synchronized(theObject) {...}
), blocking other threads waiting on synchronized instance methods.
If you don't believe in malicious code, consider that this code could come from third parties (for instance if you develop some sort of application server).
The "accidental" version seems less likely, but as they say, "make something idiot-proof and someone will invent a better idiot".
So I agree with the it-depends-on-what-the-class-does school of thought.
Edit following eljenso's first 3 comments:
I've never experienced the lock stealing problem but here is an imaginary scenario:
Let's say your system is a servlet container, and the object we're considering is the ServletContext
implementation. Its getAttribute
method must be thread-safe, as context attributes are shared data; so you declare it as synchronized
. Let's also imagine that you provide a public hosting service based on your container implementation.
I'm your customer and deploy my "good" servlet on your site. It happens that my code contains a call to getAttribute
.
A hacker, disguised as another customer, deploys his malicious servlet on your site. It contains the following code in the init
method:
synchronized (this.getServletConfig().getServletContext()) { while (true) {} }
Assuming we share the same servlet context (allowed by the spec as long as the two servlets are on the same virtual host), my call on getAttribute
is locked forever. The hacker has achieved a DoS on my servlet.
This attack is not possible if getAttribute
is synchronized on a private lock, because 3rd-party code cannot acquire this lock.
I admit that the example is contrived and an oversimplistic view of how a servlet container works, but IMHO it proves the point.
So I would make my design choice based on security consideration: will I have complete control over the code that has access to the instances? What would be the consequence of a thread's holding a lock on an instance indefinitely?
You can use the built-in Dir function or the FileSystemObject.
Dir Function: VBA: Dir Function
FileSystemObject: VBA: FileSystemObject - Files Collection
They each have their own strengths and weaknesses.
Dir Function
The Dir Function is a built-in, lightweight method to get a list of files. The benefits for using it are:
The trick is to understand the difference between calling it with or without a parameter. Here is a very simple example to demonstrate:
Public Sub ListFilesDir(ByVal sPath As String, Optional ByVal sFilter As String)
Dim sFile As String
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
If sFilter = "" Then
sFilter = "*.*"
End If
'call with path "initializes" the dir function and returns the first file name
sFile = Dir(sPath & sFilter)
'call it again until there are no more files
Do Until sFile = ""
Debug.Print sFile
'subsequent calls without param return next file name
sFile = Dir
Loop
End Sub
If you alter any of the files inside the loop, you will get unpredictable results. It is better to read all the names into an array of strings before doing any operations on the files. Here is an example which builds on the previous one. This is a Function that returns a String Array:
Public Function GetFilesDir(ByVal sPath As String, _
Optional ByVal sFilter As String) As String()
'dynamic array for names
Dim aFileNames() As String
ReDim aFileNames(0)
Dim sFile As String
Dim nCounter As Long
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
If sFilter = "" Then
sFilter = "*.*"
End If
'call with path "initializes" the dir function and returns the first file
sFile = Dir(sPath & sFilter)
'call it until there is no filename returned
Do While sFile <> ""
'store the file name in the array
aFileNames(nCounter) = sFile
'subsequent calls without param return next file
sFile = Dir
'make sure your array is large enough for another
nCounter = nCounter + 1
If nCounter > UBound(aFileNames) Then
'preserve the values and grow by reasonable amount for performance
ReDim Preserve aFileNames(UBound(aFileNames) + 255)
End If
Loop
'truncate the array to correct size
If nCounter < UBound(aFileNames) Then
ReDim Preserve aFileNames(0 To nCounter - 1)
End If
'return the array of file names
GetFilesDir = aFileNames()
End Function
File System Object
The File System Object is a library for IO operations which supports an object-model for manipulating files. Pros for this approach:
You can add a reference to to "Windows Script Host Object Model" (or "Windows Scripting Runtime") and declare your objects like so:
Public Sub ListFilesFSO(ByVal sPath As String)
Dim oFSO As FileSystemObject
Dim oFolder As Folder
Dim oFile As File
Set oFSO = New FileSystemObject
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
Debug.Print oFile.Name
Next 'oFile
Set oFile = Nothing
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
If you don't want intellisense you can do like so without setting a reference:
Public Sub ListFilesFSO(ByVal sPath As String)
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
Debug.Print oFile.Name
Next 'oFile
Set oFile = Nothing
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
I just want to have a button on my website make a PHP file run
<form action="my.php" method="post">
<input type="submit">
</form>
Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.
<a href="my.php">run php</a>
(Although you should use link text that describes what happens from the user's point of view, not the servers)
I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.
This is tricker.
First, you do need to use a form and POST (since you are sending data to be stored).
Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.
Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.
<a href="showBlogEntry.php?entry_id=123">...</a>
Make sure you also read up on SQL injection and XSS.
Download this Sqlite manager its the easiest one to use Sqlite manager
and drag and drop your fetched file on its running instance
only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.
So i Use Firefox Plugin Side by side also which you can find at FireFox addons
No 3rd-party frameworks; Allows query string; Adds trailing slash; Handles 404
Create a public_html
subfolder and place all of your content in it.
Gist: https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3
var fs = require('fs');
require('http').createServer(function(request, response) {
var path = 'public_html'+ request.url.slice(0,
(request.url.indexOf('?')+1 || request.url.length+1) - 1);
fs.stat(path, function(bad_path, path_stat) {
if (bad_path) respond(404);
else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
response.setHeader('Location', path.slice(11)+'/');
respond(301);
} else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
function(bad_file, file_content) {
if (bad_file) respond(404);
else respond(200, file_content);
});
});
function respond(status, content) {
response.statusCode = status;
response.end(content);
}
}).listen(80, function(){console.log('Server running on port 80...')});
Remember to remove dummy elements in httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/Apache24/docs/dummy-host.example.com"
ServerName dummy-host.example.com
ServerAlias www.dummy-host.example.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common
</VirtualHost>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/Apache24/docs/dummy-host2.example.com"
ServerName dummy-host2.example.com
ErrorLog "logs/dummy-host2.example.com-error.log"
CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)
WeakReference: objects that are only weakly referenced are collected at every GC cycle (minor or full).
SoftReference: when objects that are only softly referenced are collected depends on:
-XX:SoftRefLRUPolicyMSPerMB=N flag (default value is 1000, aka 1 second)
Amount of free memory in the heap.
Example:
Then object which is referenced only by SoftReference will be collected if last time when it was accessed is greater then 10 seconds.
Here's how to visit each element in a 2-dimensional array. Is this what you were looking for?
for (int i=0;i<array.GetLength(0);i++)
{
for (int j=0;j<array.GetLength(1);j++)
{
int cell = array[i,j];
}
}
In the latest release of Google Play, Google removed the need to ask permission for internet as "most apps need it anyways nowadays". However, for users who have older versions, it is still recommended to leave the code below in your manifest
<uses-permission android:name="android.permission.INTERNET" />
for superclasses with many members I would suggest you to use @Delegate
@Data
public class A {
@Delegate public class AInner{
private final int x;
private final int y;
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
private final int z;
public B(A.AInner a, int z) {
super(a);
this.z = z;
}
}
You can do it using jsPDF
HTML:
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
JavaScript:
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
Seems question is not about strings equality, but of sets equality. You can compare them this way only by splitting strings and converting them to sets:
s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' '))
set2 = set(s2.split(' '))
print set1 == set2
Result will be
True
Yes, it means unsigned int
. It used to be that if you didn't specify a data type in C there were many places where it just assumed int
. This was try, for example, of function return types.
This wart has mostly been eradicated, but you are encountering its last vestiges here. IMHO, the code should be fixed to say unsigned int
to avoid just the sort of confusion you are experiencing.
Tested on Bootstrap version 3.3.2
$('#myModal').on('hide.bs.modal', function() {
$(this).removeData();
});
Slight modification to what was stated above. My Json format, which validates was
{
mycollection:{[
{
property0:value,
property1:value,
},
{
property0:value,
property1:value,
}
]
}
}
Using AlexDev's response, I did this Looping each child, creating reader from it
public partial class myModel
{
public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}
public class myModelList {
[JsonConverter(typeof(myModelConverter))]
public List<myModel> model { get; set; }
}
class myModelConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Children()) //mod here
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject); //mod here
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
with '0x' prefix, you might also use eval function
For example
>>a='0xff'
>>eval(a)
255
Using the ternary operator is the most simple, most efficient, and most readable way to do what you want. I encourage you to use this solution.
However, I can't resist to propose an alternative, contrived, inefficient, unreadable solution.
int boolToInt(Boolean b) {
return b.compareTo(false);
}
Hey, people like to vote for such cool answers !
Edit
By the way, I often saw conversions from a boolean to an int for the sole purpose of doing a comparison of the two values (generally, in implementations of compareTo
method). Boolean#compareTo
is the way to go in those specific cases.
Edit 2
Java 7 introduced a new utility function that works with primitive types directly, Boolean#compare
(Thanks shmosel)
int boolToInt(boolean b) {
return Boolean.compare(b, false);
}
It's worth looking at Pydb, "an expanded version of the Python debugger loosely based on the gdb command set". It includes signal managers which can take care of starting the debugger when a specified signal is sent.
A 2006 Summer of Code project looked at adding remote-debugging features to pydb in a module called mpdb.
Read five lines each time, just put your statement in if statement , thats it
String str1 = @"C:\Users\TEMP\Desktop\StaN.txt";
System.IO.StreamReader file = new System.IO.StreamReader(str1);
line = file.ReadLine();
Int32 ctn=0;
try
{
while ((line = file.ReadLine()) != null)
{
if (Counter == ctn)
{
MessageBox.Show("I am here");
ctn=ctn+5;
continue;
}
else
{
Counter++;
//MessageBox.Show(Counter.ToString());
MessageBox.Show(line.ToString());
}
}
file.Close();
}
catch (Exception er)
{
}
another useful way to replace values
library(plyr)
junk$nm <- revalue(junk$nm, c("B"="b"))
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
I know it's 5 years late, if you want to use nodemon.json
you may try this,
{
"verbose": true,
"ignore": ["*.test.js", "fixtures/*"],
"execMap": {
"js": "electron ." // 'js' is for the extension, and 'electron .' is command that I want to execute
}
}
The execMap
will execute like a script
in package.json, then you can run nodemon js
I use /bin/zsh
, and I changed vscode to do the same, but somehow vscode still use the path from /bin/bash
. So I created a .bash_profile file with node location in the path.
Simply run in terminal:
echo "PATH=$PATH
export \$PATH" >> ~/.bash_profile
Restart vscode, and it will work.
Try
this.router.navigate([], {
queryParams: {
query: value
}
});
will work for same route navigation other than single quotes.
I had the same problem but I use -w 0
option to send only one packet and quit.
You should use this command :
echo -n "hello" | nc -4u -w0 localhost 8000
INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select * from table;
is the correct answer.
If the number of records is really big, based on the number of files generated
the following command would give only partial result.
hive -e 'select * from some_table' > /home/yourfile.csv
Have a look at the HttpURLConnection
class API documentation, especially setInstanceFollowRedirects()
.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonUtils {
public static Map<String, Object> jsonToMap(JSONObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != null) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keySet().iterator();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.size(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
i used pixi.js and pixi-sound.js to achieve the auto play in chrome and firefox.
<script>
PIXI.sound.Sound.from({
url: 'audios/tuto.mp3',
loop:true,
preload: true,
loaded: function(err, sound) {
sound.play();
document.querySelector("#paused").addEventListener('click', function() {
const paused = PIXI.sound.togglePauseAll();
this.className = this.className.replace(/\b(on|off)/g, '');
this.className += paused ? 'on' : 'off';
});
}
});
</script>
HTML:
<button class="btn1 btn-lg off" id="paused">
<span class="glyphicon glyphicon-pause off"></span>
<span class="glyphicon glyphicon-play on"></span>
</button>
it also works on mobile devices but user have to touch somewhere on the screen to trigger the sound.
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
For people wondering, this also works for button click. For example:
private void btn_Click(object sender, EventArgs e)
{
MessageBox.Show("Test")
}
private void txb_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
btn_Click(sender, e);
}
When pressing Enter in the textfield(txb) in this case it will click the button which will active the MessageBox.
You can also try this
<li><%= link_to "", application_welcome_path, class: "navbar-brand metas-logo" %></li>
Where "metas-logo" is a css class with a background image
The StreamReader.CurrentEncoding
property rarely returns the correct text file encoding for me. I've had greater success determining a file's endianness, by analyzing its byte order mark (BOM). If the file does not have a BOM, this cannot determine the file's encoding.
*UPDATED 4/08/2020 to include UTF-32LE detection and return correct encoding for UTF-32BE
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
public static Encoding GetEncoding(string filename)
{
// Read the BOM
var bom = new byte[4];
using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
file.Read(bom, 0, 4);
}
// Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE
if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true); //UTF-32BE
// We actually have no idea what the encoding is if we reach this point, so
// you may wish to return null instead of defaulting to ASCII
return Encoding.ASCII;
}