Adding the margin details to the body will prevent scrolling if your content properly wraps, as so:
<body leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0">
Easy enough, and a lot less code + bug overhead :)
try this is your activity onCreate:
ScrollView sView = (ScrollView)findViewById(R.id.deal_web_view_holder);
// Hide the Scollbar
sView.setVerticalScrollBarEnabled(false);
sView.setHorizontalScrollBarEnabled(false);
In order to give spacing between views inside a listView please use padding on your inflate views.
You can use android:paddingBottom="(number)dp"
&& android:paddingTop="(number)dp"
on your view or views you're inflate inside your listview.
The divider solution is just a fix, because some day, when you'll want to use a divider color (right now it's transparent) you will see that the divider line is been stretched.
use below code:
model = forest.fit(train_fold, train_y.ravel())
if you are still getting slap by error as identical as below ?
Unknown label type: %r" % y
use this code:
y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
UICollectionView implementation is quite interesting. You can use the simple source code and watch a video tutorial using these links :
https://github.com/Ady901/Demo02CollectionView.git
https://www.youtube.com/watch?v=5SrgvZF67Yw
extension ViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return nameArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
cell.titleLabel.text = nameArr[indexPath.row]
cell.userImageView.backgroundColor = .blue
return cell
}
}
extension ViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let alert = UIAlertController(title: "Hi", message: "\(nameArr[indexPath.row])", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
Null is not an instance of any class.
However, you can assign null to variables of any (object or array) type:
// this is false
boolean nope = (null instanceof String);
// but you can still use it as a String
String x = null;
"abc".startsWith(null);
Please use this. You will get table names along with schema names:
SELECT SYSSCHEMA.NAME, SYSTABLE.NAME
FROM SYS.tables SYSTABLE
INNER JOIN SYS.SCHEMAS SYSSCHEMA
ON SYSTABLE.SCHEMA_ID = SYSSCHEMA.SCHEMA_ID
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
If you would like to add background color to the entire activity
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1de9b6"
tools:context="com.example.abc.myapplication.MainActivity">
</RelativeLayout>
If you would like to use background for a view
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Andrios"
android:background="@color/colorAccent" />
Hope this helps!
Instead of checking for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
as many answers suggest, there is a slightly simpler way -
Add the following line to the application
section of AndroidManifest.xml file as explained in the Set Up a Firebase Cloud Messaging Client App on Android doc:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
Then add a line with a channel name to the values/strings.xml file:
<string name="default_notification_channel_id">default</string>
After that you will be able to use the new version of NotificationCompat.Builder constructor with 2 parameters (since the old constructor with 1 parameter has been deprecated in Android Oreo):
private void sendNotification(String title, String body) {
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this,
0 /* Request code */,
i,
PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,
getString(R.string.default_notification_channel_id))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pi);
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
I had the same problem, needed a modification of [Required] attribute - make field required in dependence of http request.The solution was similar to Dan Hunex answer, but his solution didn't work correctly (see comments). I don't use unobtrusive validation, just MicrosoftMvcValidation.js out of the box. Here it is. Implement your custom attribute:
public class RequiredIfAttribute : RequiredAttribute
{
public RequiredIfAttribute(/*You can put here pararmeters if You need, as seen in other answers of this topic*/)
{
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
//You can put your logic here
return ValidationResult.Success;//I don't need its server-side so it always valid on server but you can do what you need
}
}
Then you need to implement your custom provider to use it as an adapter in your global.asax
public class RequreIfValidator : DataAnnotationsModelValidator <RequiredIfAttribute>
{
ControllerContext ccontext;
public RequreIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute)
: base(metadata, context, attribute)
{
ccontext = context;// I need only http request
}
//override it for custom client-side validation
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
//here you can customize it as you want
ModelClientValidationRule rule = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
//and here is what i need on client side - if you want to make field required on client side just make ValidationType "required"
ValidationType =(ccontext.HttpContext.Request["extOperation"] == "2") ? "required" : "none";
};
return new ModelClientValidationRule[] { rule };
}
}
And modify your global.asax with a line
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequreIfValidator));
and here it is
[RequiredIf]
public string NomenclatureId { get; set; }
The main advantage for me is that I don't have to code custom client validator as in case of unobtrusive validation. it works just as [Required], but only in cases that you want.
It should always work whichever JDK version you use:
System.out.println(Arrays.asList(array));
It will work if the Array
contains Objects. If the Array
contains primitive types, you can use wrapper classes instead storing the primitive directly as..
Example:
int[] a = new int[]{1,2,3,4,5};
Replace it with:
Integer[] a = new Integer[]{1,2,3,4,5};
Update :
Yes ! this is to be mention that converting an array to an object array OR to use the Object's array is costly and may slow the execution. it happens by the nature of java called autoboxing.
So only for printing purpose, It should not be used. we can make a function which takes an array as parameter and prints the desired format as
public void printArray(int [] a){
//write printing code
}
Ok, solved it myself;
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"
displays:
out> err> ls: cannot access /badDir: No such file or directory
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).
Something like:
StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
b.append("other_string");
}
return b.toString();
Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
To get just the string value within the spinner use the following:
spinner.getSelectedItem().toString();
Here is what I ended up doing and it worked great.
First I moved the file input outside of the form so that it is not submitted:
<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
... a few more inputs ...
</form>
Then I changed the uploadPhotos
function to handle only the resizing:
window.uploadPhotos = function(url){
// Read in file
var file = event.target.files[0];
// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');
// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};
As you can see I'm using canvas.toDataURL('image/jpeg');
to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl);
to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */
Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.
/* Handle image resized events */
$(document).on("imageResized", function (event) {
var data = new FormData($("form[id*='uploadImageForm']")[0]);
if (event.blob && event.url) {
data.append('image_data', event.blob);
$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});
This example uses Bash's built-in getopts
command and is from the Google Shell Style Guide:
a_flag=''
b_flag=''
files=''
verbose='false'
print_usage() {
printf "Usage: ..."
}
while getopts 'abf:v' flag; do
case "${flag}" in
a) a_flag='true' ;;
b) b_flag='true' ;;
f) files="${OPTARG}" ;;
v) verbose='true' ;;
*) print_usage
exit 1 ;;
esac
done
Note: If a character is followed by a colon (e.g. f:
), that option is expected to have an argument.
Example usage: ./script -v -a -b -f filename
Using getopts has several advantages over the accepted answer:
-a -b -c
? -abc
)However, a big disadvantage is that it doesn't support long options, only single-character options.
When I faced with a similar problem, I finished with the following code:
public bool IsFileLocked(string filePath)
{
try
{
using (File.Open(filePath, FileMode.Open)){}
}
catch (IOException e)
{
var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
return errorCode == 32 || errorCode == 33;
}
return false;
}
Sorry for reviving this old question. But when using bash
there is a very easy approach to create Unicode codepoints from plain ASCII input, which even does not fork at all:
unicode() { local -n a="$1"; local c; printf -vc '\\U%08x' "$2"; printf -va "$c"; }
unicodes() { local a c; for a; do printf -vc '\\U%08x' "$a"; printf "$c"; done; };
Use it as follows to define certain codepoints
unicode crossbones 0x2620
echo "$crossbones"
or to dump the first 65536 unicode codepoints to stdout (takes less than 2s on my machine. The additional space is to prevent certain characters to flow into each other due to shell's monospace font):
for a in {0..65535}; do unicodes "$a"; printf ' '; done
or to tell a little very typical parent's story (this needs Unicode 2010):
unicodes 0x1F6BC 32 43 32 0x1F62D 32 32 43 32 0x1F37C 32 61 32 0x263A 32 32 43 32 0x1F4A9 10
Explanation:
printf '\UXXXXXXXX'
prints out any Unicode characterprintf '\\U%08x' number
prints \UXXXXXXXX
with the number converted to Hex, this then is fed to another printf
to actually print out the Unicode characterprintf
recognizes octal (0oct), hex (0xHEX) and decimal (0 or numbers starting with 1 to 9) as numbers, so you can choose whichever representation fits bestprintf -v var ..
gathers the output of printf
into a variable, without fork (which tremendously speeds up things)local variable
is there to not pollute the global namespacelocal -n var=other
aliases var
to other
, such that assignment to var
alters other
. One interesting part here is, that var
is part of the local namespace, while other
is part of the global namespace.
local
or global
namespace in bash
. Variables are kept in the environment, and such are always global. Local just puts away the current value and restores it when the function is left again. Other functions called from within the function with local
will still see the "local" value. This is a fundamentally different concept than all the normal scoping rules found in other languages (and what bash
does is very powerful but can lead to errors if you are a programmer who is not aware of that).Prepared Statements are the best solution, but if you really need to do it manually you could also use the StringEscapeUtils
class from the Apache Commons-Lang library. It has an escapeSql(String)
method, which you can use:
import org.apache.commons.lang.StringEscapeUtils;
…
String escapedSQL = StringEscapeUtils.escapeSql(unescapedSQL);
You can do:
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]
plt.plot(x, y, style='.-')
plt.show()
This will return a graph with the data points marked with a dot
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
Use import javax.persistence.Entity; Instead of import org.hibernate.annotations.Entity;
often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.
Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.
Sorry for reviving an old thread but no one mentioned setting android:imeOptions="flagNoFullscreen"
in your EditText element
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
In my case, the image name defined in docker-compose.yml
contained uppercase letters. The fact that the error message mentioned repository
instead of image
did not help describe the problem and it took a while to figure out.
I faced same issue few days back, I followed the link mentioned below and I could able to overcome the problem
The ES6 way of require is import
. You can export
your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'
syntax.
import fs from 'fs';
export default class Animal {
constructor(name){
this.name = name ;
}
print(){
console.log('Name is :'+ this.name);
}
}
import Animal from 'path/to/Animal.js';
#pragma
is for compiler directives that are machine-specific or operating-system-specific, i.e. it tells the compiler to do something, set some option, take some action, override some default, etc. that may or may not apply to all machines and operating systems.
See msdn for more info.
$('.offer').click(function(){
if ($(this).find(':checkbox').is(':checked'))
{
$(this).find(':checkbox').attr('checked', false);
}else{
$(this).find(':checkbox').attr('checked', true);
}
});
You could add it:
public static IEnumerable<T> OrderBy( this IEnumerable<T> input, string queryString) {
//parse the string into property names
//Use reflection to get and sort by properties
//something like
foreach( string propname in queryString.Split(','))
input.OrderBy( x => GetPropertyValue( x, propname ) );
// I used Kjetil Watnedal's reflection example
}
The GetPropertyValue
function is from Kjetil Watnedal's answer
The issue would be why? Any such sort would throw exceptions at run-time, rather than compile time (like D2VIANT's answer).
If you're dealing with Linq to Sql and the orderby is an expression tree it will be converted into SQL for execution anyway.
No need to pass anything in. The function used for addEventListener
will automatically have this
bound to the current element. Simply use this
in your function:
productLineSelect.addEventListener('change', getSelection, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
Here's the fiddle: http://jsfiddle.net/dJ4Wm/
If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:
productLineSelect.addEventListener('change', function() {
foo('bar');
}, false);
function foo(message) {
alert(message);
}
Here's the fiddle: http://jsfiddle.net/t4Gun/
If you want to set the value of this
manually, you can use the call
method to call the function:
var self = this;
productLineSelect.addEventListener('change', function() {
getSelection.call(self);
// This'll set the `this` value inside of `getSelection` to `self`
}, false);
function getSelection() {
var value = this.options[this.selectedIndex].value;
alert(value);
}
Use strtotime() function:
$time = strtotime("-1 year", time());
$date = date("Y-m-d", $time);
I had a similar issue WhiteLabel Error message on my Angular SPA whenever I did a refresh.
The fix was to create a controller that implements ErrorController but instead of returning a String, I had to return a ModelAndView object that forwards to /
@CrossOrigin
@RestController
public class IndexController implements ErrorController {
private static final String PATH = "/error";
@RequestMapping(value = PATH)
public ModelAndView saveLeadQuery() {
return new ModelAndView("forward:/");
}
@Override
public String getErrorPath() {
return PATH;
}
}
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.
It is important to contrast the design philosophy of git with the philosophy of a more traditional source control tool like SVN.
Subversion was designed and built with a client/server model. There is a single repository that is the server, and several clients can fetch code from the server, work on it, then commit it back to the server. The assumption is that the client can always contact the server when it needs to perform an operation.
Git was designed to support a more distributed model with no need for a central repository (though you can certainly use one if you like). Also git was designed so that the client and the "server" don't need to be online at the same time. Git was designed so that people on an unreliable link could exchange code via email, even. It is possible to work completely disconnected and burn a CD to exchange code via git.
In order to support this model git maintains a local repository with your code and also an additional local repository that mirrors the state of the remote repository. By keeping a copy of the remote repository locally, git can figure out the changes needed even when the remote repository is not reachable. Later when you need to send the changes to someone else, git can transfer them as a set of changes from a point in time known to the remote repository.
git fetch
is the command that says "bring my local copy of the remote repository up to date."
git pull
says "bring the changes in the remote repository to where I keep my own code."
Normally git pull
does this by doing a git fetch
to bring the local copy of the remote repository up to date, and then merging the changes into your own code repository and possibly your working copy.
The take away is to keep in mind that there are often at least three copies of a project on your workstation. One copy is your own repository with your own commit history. The second copy is your working copy where you are editing and building. The third copy is your local "cached" copy of a remote repository.
when you are using POST method in HTML forms, you need to catch the data from req.body in the server side i.e. Node.js. and also add
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({extended: false}));
OR
use method='GET' in HTML and and catch the data by req.query in the server side i.e. Node.js
You will need to use the IO.Directory.GetFiles function.
Dim files() As String = IO.Directory.GetFiles("c:\")
For Each file As String In files
' Do work, example
Dim text As String = IO.File.ReadAllText(file)
Next
Either you can expose sanitizer to the view, or expose a method that forwards the call to bypassSecurityTrustUrl
<img class='photo-img' [hidden]="!showPhoto1"
[src]='sanitizer.bypassSecurityTrustUrl(theMediaItem.photoURL1)'>
Is this possible to assign a NaN to a double or float in C ...?
Yes, since C99, (C++11) <math.h>
offers the below functions:
#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);
which are like their strtod("NAN(n-char-sequence)",0)
counterparts and NAN
for assignments.
// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
Sample output: (Implementation dependent)
(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)
If you get the server response as a String, without using a third party library you can do
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
Here is the documentation
Otherwise to parse json you can use Gson or Jackson
EDIT without libraries (not tested)
class retrievedata extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL("http://myurlhere.com");
urlConnection.setRequestMethod("GET"); //Your method here
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "\n");
if (buffer.length() == 0)
return null;
return buffer.toString();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
exception = e;
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
exception = e;
Log.e(TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(String response) {
if(response != null) {
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
}
}
}
Have you got org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
configured in webapp's web.xml
(assuming your application is a webapp), or wrapping calls accordingly?
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
SELECT DISTINCT(column_name)
FROM table_name
ORDER BY column_name DESC limit N-1,1;
where N represents the nth highest salary ..
Third highest salary :
SELECT DISTINCT(column_name)
FROM table_name
ORDER BY column_name DESC limit 2,1;
You can send the parameters in the URL of the POST request itself.
Example URL:
localhost:8080/abc/getDetails?paramter1=value1¶meter2=value2
Once you copy such type of URL in Firefox REST client make a POST call to the server you want
I ran into the same issue and found that there was an extra pair of braces (curly brackets) enclosing public static void main(String args) { ... }. This method should really be at the top scope in the class and should not be enclosed around braces. It seems that it is possible to end up with braces around this method when working in Eclipse. This could be just one way you can see this issue when working with Eclipse. Happy coding!
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
You can directly set the content type like below:
res.writeHead(200, {'Content-Type': 'text/plain'});
For reference go through the nodejs Docs link.
get DLImageLoader and try folowing code
[DLImageLoader loadImageFromURL:imageURL
completed:^(NSError *error, NSData *imgData) {
imageView.image = [UIImage imageWithData:imgData];
[imageView setContentMode:UIViewContentModeCenter];
}];
Another typical real-world example of using DLImageLoader, which may help someone...
PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
@"http://graph.facebook.com/%@/picture?type=large",
[aFacebookUser objectForKey:@"id"] ];
__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
completed:^(NSError *error, NSData *imgData)
{
if ( loadMe == nil ) return;
if (error == nil)
{
UIImage *image = [UIImage imageWithData:imgData];
image = [image ourImageScaler];
loadMe.image = image;
}
else
{
// an error when loading the image from the net
}
}];
As I mention above another great library to consider these days is Haneke (unfortunately it's not as lightweight).
I found a different solution to this issue. Apparently my IIS 7 did not have 32bit mode enabled in my Application Pool by default.
To enable 32bit mode, open IIS and select your Application Pool. Mine was named "ASP.NET v4.0".
Right click, go to "Advanced Settings" and change the section named:
"Enabled 32-bit Applications" to true.
Restart your web server and try again.
I found the fix from this blog reference: http://darrell.mozingo.net/2009/01/17/running-iis-7-in-32-bit-mode/
Additionally, you can change the settings on Visual Studio. In my case, I went to Tools > Options > Projects and Solutions > Web Projects
and checked Use the 64 bit version of IIS Express for web sites and projects
- This was on VS Pro 2015. Nothing else fixed it but this.
First you have to check login existence using syslogins view:
IF NOT EXISTS
(SELECT name
FROM master.sys.server_principals
WHERE name = 'YourLoginName')
BEGIN
CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END
Then you have to check your database existence:
USE your_dbname
IF NOT EXISTS
(SELECT name
FROM sys.database_principals
WHERE name = 'your_dbname')
BEGIN
CREATE USER [your_dbname] FOR LOGIN [YourLoginName]
END
@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:
//-----------------------------------------
// @param begin Required. The index where
// to begin the extraction.
// 1st character is at index 0
//
// @param end Optional. Where to end the
// extraction. If omitted,
// slice() selects all
// characters from the begin
// position to the end of
// the string.
var str = '123-4';
alert(str.slice(0, -1));
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
This code sends array of integer values
Initialize array List
List<Integer> test = new ArrayList<Integer>();
Add values to array List
test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Send the array list values to target activity
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
here you get values on targetActivty
Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
Use the overflow-y: scroll
property on the element that contains the elements.
The overflow-y
property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.
Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:
<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
Arithmetic operations involving float
results in float
.
int + float = float
int * float = float
float * int = float
int / float = float
float / int = float
int / int = int
For more detail answer. Look at what the section §5/9 from the C++ Standard says
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result.
This pattern is called the usual arithmetic conversions, which are defined as follows:
— If either operand is of type long double, the other shall be converted to long double.
— Otherwise, if either operand is double, the other shall be converted to double.
— Otherwise, if either operand is float, the other shall be converted to float.
— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)
— Then, if either operand is unsigned long the other shall be converted to unsigned long.
— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.
— Otherwise, if either operand is long, the other shall be converted to long.
— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.
[Note: otherwise, the only remaining case is that both operands are int ]
I think that maybe it is because you are declaring a variable that you already declared:
var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue(); // <-- Here's the issue: 'var'
I think this should be like this:
var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();
Tell me if it works! ;)
Be sure to include the $route service into your scope and do this:
$route.reload();
See this:
To install Python package from github, you need to clone that repository.
git clone https://github.com/jkbr/httpie.git
Then just run the setup.py file from that directory,
sudo python setup.py install
I had to disable the File Publish Option "Precompile during publishing."
Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)
You could do
[A1].Value = "'O1/01/13 00:00"
if you really mean to add it as text (note the apostrophe as the first character).
The [A1].Value
is VBA shorthand for Range("A1").Value
.
If you want to enter a date, you could instead do (edited order with thanks to @SiddharthRout):
[A1].NumberFormat = "mm/dd/yyyy hh:mm;@"
[A1].Value = DateValue("01/01/2013 00:00")
Oracle VM ware has an update for Windows 10. I was getting this error until I installed this update.
To add some info that helped me today, a jQuery object/this
can also be passed in to the .not() selector.
$(document).ready(function(){_x000D_
$(".navitem").click(function(){_x000D_
$(".navitem").removeClass("active");_x000D_
$(".navitem").not($(this)).addClass("active");_x000D_
});_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
width: 100px;_x000D_
background: red;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
The above example can be simplified, but wanted to show the usage of this
in the not()
selector.
You could use :focus
which will remain the style as long as the user doesn't click elsewhere.
button:active {
border: 2px solid green;
}
button:focus {
border: 2px solid red;
}
please check this link : http://developer.android.com/guide/appendix/media-formats.html
videoview can't support some codec .
i suggested you to use mediaplayer , when get "sorry , can't play video"
Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.
$original = (
[0] => Array
(
[title] => Speed
[width] => 14
)
[1] => Array
(
[title] => Date
[width] => 18
)
[2] => Array
(
[title] => Pineapple
[width] => 30
)
)
Adding an item in same format to this array will add all new array indexes as items instead of just item.
$new = array(
'title' => 'Time',
'width' => 10
);
array_splice($original,1,0,array('random_string')); // can be more items
$original[1] = $new; // replaced with actual item
Note: Adding items directly to a multidimensional array with array_splice will add all its indexes as items instead of just that item.
I would check with another Java implementation/vendor. Preferrably Oracle/Sun Java: http://www.java.com/en/ . The open-source implementations unfortunately differ in weird ways.
You can use TreeSet
that automatically order list values:
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet <String>tree = new TreeSet<String>();
tree.add("aaa");
tree.add("acbbb");
tree.add("aab");
tree.add("c");
tree.add("a");
Iterator iterator;
iterator = tree.iterator();
System.out.print("Tree set data: ");
//Displaying the Tree set data
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
}
}
I lastly add 'a' but last element must be 'c'.
Set
android:focusable="true"
in your <EditText/>
As a cheap work around, I've used a label to cover up the tabs I wanted to hide.
We can then use the visible prop of the label as a substitute. If anyone does go this route, don't forget to handle keyboard strokes or visibility events. You wouldn't want the left right cursor keys exposing the tab you're trying to hide.
Following two options worked for me:
1) A function that returns the number of rows in your ResultSet.
private int resultSetCount(ResultSet resultSet) throws SQLException{
try{
int i = 0;
while (resultSet.next()) {
i++;
}
return i;
} catch (Exception e){
System.out.println("Error getting row count");
e.printStackTrace();
}
return 0;
}
2) Create a second SQL statement with the COUNT option.
The package you're looking for is confusingly named gcc-c++
.
Interface are nothing but a pure abstract class in C++. Ideally this interface class
should contain only pure virtual
public methods and static const
data. For example:
class InterfaceA
{
public:
static const int X = 10;
virtual void Foo() = 0;
virtual int Get() const = 0;
virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
Try this for truncating characters after setting it to max-width. I have used 75ch in this case
p {_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 75ch;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis etc.</p>
_x000D_
For multiline truncating, please follow the link.
An example: https://codepen.io/srekoble/pen/EgmyxV
We will be using webkit css for this. In short WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. This may be brower specific as every browser is backed by a rendering engine to draw the HTML/CSS web page.
Yes, c[i]=''
is not a valid code. We parenthesis character constant between '
'
, e.g. c[i] = 'A';
char A
. but you don't write any char in between ''
.
Empty space is nothing but suppose if you wants to assigned space then do:
c[i] = ' ';
// ^ space
if wants to assigned nul char
then do:
c[i] = '\0';
// ^ null symbol
Example: Suppose if c[]
a string (nul \0
terminated char array) if you having a string. for example:
char c[10] = {'a', '2', 'c', '\0'};
And you replace second char with space:
c[1] = ' ';
and if you print it using printf as follows:
printf("\n c: %s", c);
then output would be:
c: a c
// ^ space printed
And you replace second char with '\0':
c[1] = '\0';
then output would be:
c: a
because string terminated with \0
.
Logistic Regression is used in predicting categorical outputs like Yes/No, Low/Medium/High etc. You have basically 2 types of logistic regression Binary Logistic Regression (Yes/No, Approved/Disapproved) or Multi-class Logistic regression (Low/Medium/High, digits from 0-9 etc)
On the other hand, linear regression is if your dependent variable (y) is continuous. y = mx + c is a simple linear regression equation (m = slope and c is the y-intercept). Multilinear regression has more than 1 independent variable (x1,x2,x3 ... etc)
OR conditions can be generated like this:
$collection->addFieldToFilter(
array('field_1', 'field_2', 'field_3'), // columns
array( // conditions
array( // conditions for field_1
array('in' => array('text_1', 'text_2', 'text_3')),
array('like' => '%text')
),
array('eq' => 'exact'), // condition for field 2
array('in' => array('val_1', 'val_2')) // condition for field 3
)
);
This will generate an SQL WHERE condition something like:
... WHERE (
(field_1 IN ('text_1', 'text_2', 'text_3') OR field_1 LIKE '%text')
OR (field_2 = 'exact')
OR (field_3 IN ('val_1', 'val_2'))
)
Each nested array(<condition>) generates another set of parentheses for an OR condition.
The more general answer is
UPDATE mysql.user SET host = {newhost} WHERE user = {youruser}
Short answer: One package per module/feature, possibly with sub-packages. Put closely related things together in the same package. Avoid circular dependencies between packages.
Long answer: I agree with most of this article
There is another way.
Given that you write your own Index
class and a static method that returns an Iterable
over instances of this class you can
for (Index<String> each: With.index(stringArray)) {
each.value;
each.index;
...
}
Where the implementation of With.index
is something like
class With {
public static <T> Iterable<Index<T>> index(final T[] array) {
return new Iterable<Index<T>>() {
public Iterator<Index<T>> iterator() {
return new Iterator<Index<T>>() {
index = 0;
public boolean hasNext() { return index < array.size }
public Index<T> next() { return new Index(array[index], index++); }
...
}
}
}
}
}
Based on the answers provided, I decided to make a quick plugin to do this:
(function($){
$.fn.moveTo = function(selector){
return this.each(function(){
var cl = $(this).clone();
$(cl).appendTo(selector);
$(this).remove();
});
};
})(jQuery);
Usage:
$('#nodeToMove').moveTo('#newParent');
For debugging JavaScript code in VS2015, there is no need for
Attaching IE didn't work, but here is a workaround.
Select IE
and press F5. This will attach both worker process and IE as shown here-
If you are not interested in debugging server code, detach it from Processes window.
You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.
UPDATE: The stroke-alignment
attribute was on April 1st, 2015 moved to a completely new spec called SVG Strokes.
As of the SVG 2.0 Editor’s Draft of February 26th, 2015 (and possibly since February 13th), the with the values stroke-alignment
property is presentinner
, center
(default) and outer
.
It seems to work the same way as the stroke-location
property proposed by @Phrogz and the later stroke-position
suggestion. This property has been planned since at least 2011, but apart from an annotation that said
SVG 2 shall include a way to specify stroke position
, it has never been detailed in the spec as it was deferred - until now, it seems.
No browser support this property, or, as far as I know, any of the new SVG 2 features, yet, but hopefully they will soon as the spec matures. This has been a property I personally have been urging to have, and I'm really happy that it's finally there in the spec.
There seems to be some issues as to how to the property should behave on open paths as well as loops. These issues will, most probably, prolong implementations across browsers. However, I will update this answer with new information as browsers begin to support this property.
In Android tests I'm doing so: InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi enable") InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")
A numpy single-element array is mutable and yet for most purposes, it can be evaluated as if it was a numerical python variable. Therefore, it's a more convenient by-reference number container than a single-element list.
import numpy as np
def triple_var_by_ref(x):
x[0]=x[0]*3
a=np.array([2])
triple_var_by_ref(a)
print(a+1)
output:
3
Typical implementation:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
You are free to do what you want with the stdout
data in the pipe. In fact, you can simply omit those parameters (stdout=
and stderr=
) and it'll behave like os.system()
.
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
The book seems to indicate that those commands yield the same effect:
The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:
$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch serverfix from origin.
Switched to a new branch 'serverfix'
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
$ git checkout -b sf origin/serverfix
That's particularly handy when your bash or oh-my-zsh git completions are able to pull the origin/serverfix
name for you - just append --track
(or -t
) and you are on your way.
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
You cannot do that with the native confirm()
as it is the browser’s method.
You have to create a plugin for a confirm box (or try one created by someone else). And they often look better, too.
Additional Tip: Change your English sentence to something like
Really, Delete this Thing?
Ok solved it.
Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting
In my app.js routing config:
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
Then in my CMS controller:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
With #views being my <div id="views" ng-view></div>
So now it works with standard routing and dynamic routing.
To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio
into my browser and hey presto portfolio.html was displayed....
Updated Added $apply and $compile to the html so that dynamic content can be injected.
The curly braces are inside the string, so it is being evaluated as string. They need to be outside, so this should work:
<div className={"btn-group pull-right " + (this.props.showBulkActions ? 'show' : 'hidden')}>
Note the space after "pull-right". You don't want to accidentally provide the class "pull-rightshow" instead of "pull-right show". Also the parentheses needs to be there.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction
[\s-[\r\n]]
or, including Eiríkr Útlendi's solution, you get
[\s\u3000-[\r\n]]
Variables have scope, so yes it is appropriate to have variables that are specific to your function. You don't always have to be explicit about their definition; usually you can just use them. Only if you want to do something specific to the type of the variable, like append for a list, do you need to define them before you start using them. Typical example of this.
list = []
for i in stuff:
list.append(i)
By the way, this is not really a good way to setup the list. It would be better to say:
list = [i for i in stuff] # list comprehension
...but I digress.
Your other question. The custom object should be a class itself.
class CustomObject(): # always capitalize the class name...this is not syntax, just style.
pass
customObj = CustomObject()
Just you need to use
//for bold
android:textStyle="bold"
//for italic
android:textStyle="italic"
//for normal
android:textStyle="normal"
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/userName"
android:layout_gravity="left"
android:textSize="16sp"
/>
It's the same. Your international format is already correct, and is recommended for use in all cases, where possible.
REST is easier to use for the most part and is more flexible. Unlike SOAP, REST doesn’t have to use XML to provide the response. We can find REST-based Web services that output the data in the Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS) formats.
We can obtain the output we need in a form that’s easy to parse within the language we need for our application.REST is more efficient (use smaller message formats), fast and closer to other Web technologies in design philosophy.
mvn -Dschemaname=public liquibase:update
use <textarea></textarea>
instead of leaving a space between the opening and closing tags as <textarea>
</textarea>
This is the way it should be:
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$html = file_get_contents_curl("http://example.com/");
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
if($meta->getAttribute('name') == 'keywords')
$keywords = $meta->getAttribute('content');
}
echo "Title: $title". '<br/><br/>';
echo "Description: $description". '<br/><br/>';
echo "Keywords: $keywords";
More simple
sender side
Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
i.putExtra("id","string data");
startActivity(i)
receiver side
Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
String strData = i.getStringExtra("id");
For the best performance and zero garbage, use this:
using System;
using T = MyNamespace.MyFlags;
namespace MyNamespace
{
[Flags]
public enum MyFlags
{
None = 0,
Flag1 = 1,
Flag2 = 2
}
static class MyFlagsEx
{
public static bool Has(this T type, T value)
{
return (type & value) == value;
}
public static bool Is(this T type, T value)
{
return type == value;
}
public static T Add(this T type, T value)
{
return type | value;
}
public static T Remove(this T type, T value)
{
return type & ~value;
}
}
}
try this:
split(das, cut(das$anim, 3))
if you want to split based on the value of wt
, then
library(Hmisc) # cut2
split(das, cut2(das$wt, g=3))
anyway, you can do that by combining cut
, cut2
and split
.
UPDATED
if you want a group index as an additional column, then
das$group <- cut(das$anim, 3)
if the column should be index like 1, 2, ..., then
das$group <- as.numeric(cut(das$anim, 3))
UPDATED AGAIN
try this:
> das$wt2 <- as.numeric(cut2(das$wt, g=3))
> das
anim wt wt2
1 1 181.0 1
2 2 179.0 1
3 3 180.5 1
4 4 201.0 2
5 5 201.5 2
6 6 245.0 2
7 7 246.4 3
8 8 189.3 1
9 9 301.0 3
10 10 354.0 3
11 11 369.0 3
12 12 205.0 2
13 13 199.0 1
14 14 394.0 3
15 15 231.3 2
I think the easiest way to do it is:
rmdir /s /q "C:\FolderToNotToDelete\"
The last "\" in the path is the important part.
Adding plain DOS commands, if someone is so inclined. Yes, this still works for Win 8 and Server 2008 + Server 2012.
Query session /server:Server100
Will return:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
rdp-tcp#0 Bob 3 Active rdpwd
rdp-tcp#5 Jim 9 Active rdpwd
rdp-tcp 65536 Listen
And to log off a session, use:
Reset session 3 /server:Server100
See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
Is there any better choice in this kind of scenario?
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
PHP have a built in function called empty()
the test is done by typing
if(empty($string)){...}
Reference php.net : php empty
Emacs has comment-dwim (Do What I Mean) - just select the block and do a:
M-;
It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).
With recent Bash (version = 4.2), you can use the builtin printf
with the format modifier %(strftime_format)T
:
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")
2017-11-10
$ printf '%(%F)T\n' -1 # Synonym of the above
2017-11-10
$ printf -v date '%(%F)T' -1 # Capture as var $date
printf
is much faster than date
since it's a Bash builtin while date
is an external command.
As well, printf -v date ...
is faster than date=$(printf ...)
since it doesn't require forking a subshell.
As of Python 3.7 the following code works fine:
from json import dumps
result = {"symbol": "ƒ"}
json_string = dumps(result, sort_keys=True, indent=2, ensure_ascii=False)
print(json_string)
Output:
{"symbol": "ƒ"}
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
If you want to fetch + merge, run
git pull
if you want simply to fetch :
git fetch
I found some solution for this, it might useful for you
Below is the code snippet for, count the no.of lines from the file.
File file = new File("/mnt/sdcard/abc.txt");
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(file));
lineNumberReader.skip(Long.MAX_VALUE);
int lines = lineNumberReader.getLineNumber();
lineNumberReader.close();
find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash
bash 4 (recursive)
shopt -s globstar
for xls in /path/**/*.xls
do
xls2csv "$xls" "${xls%.xls}.csv"
done
This is a peculiar question because it's not supposed to be a matter of choice.
When you launch the JVM, you specify a class to run, and it is the main()
of this class where your program starts.
By init()
, I assume you mean the JApplet method. When an applet is launched in the browser, the init()
method of the specified applet is executed as the first order of business.
By run()
, I assume you mean the method of Runnable. This is the method invoked when a new thread is started.
If Eclipse is running your run()
method even though you have no main()
, then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.
read
without any parameters will only continue if you press enter.
The DOS pause
command will continue if you press any key. Use read –n1
if you want this behaviour.
If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true
in your tsconfig.json
file.
Check this out as well: using xml path
and pivot
| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
| Asset | 205 | 142 | 421 |
| Equity | 365 | 214 | 163 |
| Profit | 524 | 421 | 325 |
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period)
FROM demo c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT account, ' + @cols + ' from
(
select account
, value
, period
from demo
) x
pivot
(
max(value)
for period in (' + @cols + ')
) p '
execute(@query)
Use command substitution instead of quotes to execute find instead of passing the command as a string:
for line in $(find . -iname '*.txt'); do
echo $line
ls -l $line;
done
This is a simple program to capture an image from using a default camera. Also, It can Detect a human face.
import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log',level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: "+str(len(faces))+" at "+str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('s'):
check, frame = video_capture.read()
cv2.imshow("Capturing", frame)
cv2.imwrite(filename='saved_img.jpg', img=frame)
video_capture.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
print("Image Saved")
print("Program End")
cv2.destroyAllWindows()
break
elif cv2.waitKey(1) & 0xFF == ord('q'):
print("Turning off camera.")
video_capture.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
output
Also, You can check out my GitHub code
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
Because if people can get at your object instance (ie: your this
) pointer, then they can also try to lock that same object. Now they might not be aware that you're locking on this
internally, so this may cause problems (possibly a deadlock)
In addition to this, it's also bad practice, because it's locking "too much"
For example, you might have a member variable of List<int>
, and the only thing you actually need to lock is that member variable. If you lock the entire object in your functions, then other things which call those functions will be blocked waiting for the lock. If those functions don't need to access the member list, you'll be causing other code to wait and slow down your application for no reason at all.
I had a similar situation when reading from Oracle in a Spark job. This connection reset error was caused by an incompatibility between the Oracle server and the JDBC driver used. Worth checking it.
You could simply use ^[\w.]+
to match A-Z, a-z, 0-9 and _
the easy way is the "values" property df.iloc[:,1:].values
a=df.iloc[:,1:]
b=df.iloc[:,1:].values
print(type(df))
print(type(a))
print(type(b))
so, you can get type
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>
You can use btn-lg
, btn-sm
and btn-xs
classes for manipulating with its size.
btn-block
Also, there is a class btn-block
which will extend your button to the whole block. It is very convenient in combination with Bootstrap grid.
For example, this code will show a button with the width equal to half of screen for medium and large screens; and will show a full-width button for small screens:
<div class="container">
<div class="col-xs-12 col-xs-offset-0 col-sm-offset-3 col-sm-6">
<button class="btn btn-group">Click me!</button>
</div>
</div>
Check this JSFiddle out. Try to resize frame.
If it is not enough, you can easily create your custom class.
for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.
replace now.getTime() with your long value.
//GET UTC time for current date
Date now= new Date();
//LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
This answer is an attempt to address: how to control java version system-wide (not just in currently running shell) when several versions of JDK are installed for development purposes on macOS El Capitan or newer (Sierra, High Sierra, Mojave). As far as I can tell, none of the current answers do that (*).
As a developer, I use several JDKs, and I want to switch from one to the other easily. Usually I have the latest stable one for general use, and others for tests. But I don't want the system (e.g. when I start my IDE) to use the latest "early access" version I have for now. I want to control system's default, and that should be latest stable.
The following approach works with Java 7 to 12 at least (early access at the time of this writing), with Oracle JDK or OpenJDK (including builds by AdoptOpenJDK produced after mid-October 2018).
/Library/Java/JavaVirtualMachines
. The system will pick the highest version by default. Contents/Info.plist
to Info.plist.disabled
. That JDK can still be used when $JAVA_HOME
points to it, or explicitly referenced in a script or configuration. It will simply be ignored by system's java
command.System launcher will use the JDK with highest version among those that have an Info.plist
file.
When working in a shell with alternate JDK, pick your method among existing answers (jenv
, or custom aliases/scripts around /usr/libexec/java_home
, etc).
Details of investigation in this gist.
(*) Current answers are either obsolete (no longer valid for macOS El Capitan or Sierra), or only address a single JDK, or do not address the system-wide aspect. Many explain how to change $JAVA_HOME
, but this only affects the current shell and what is launched from there. It won't affect an application started from OS launcher (unless you change the right file and logout/login, which is tedious). Same for jenv, it's cool and all, but as far as I can tell it merely changes environment variables, so it has the same limitation.
This is how I learned it from "The Big Nerd Ranch Guide (4th edition)":
@throw [NSException exceptionWithName:@"Something is not right exception"
reason:@"Can't perform this operation because of this or that"
userInfo:nil];
for FULLSCREEN width table:
table width MUST be 100%
if need N colunms, then THs MUST be N+1
example for 3 columns:
table.fixed {_x000D_
table-layout: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
table.fixed td {_x000D_
overflow: hidden;_x000D_
}
_x000D_
<table class="fixed">_x000D_
<col width=20 />_x000D_
<col width=20 />_x000D_
<col width=20 />_x000D_
<tr>_x000D_
<th>1</th>_x000D_
<th>2</th>_x000D_
<th>3</th>_x000D_
<th>FREE</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>text111111111</td>_x000D_
<td>text222222222</td>_x000D_
<td>text3333333</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Use ToArray()
on List<T>
.
It may be time consuming to get all the application Ids from YARN and kill them one by one. You can use a Bash for loop to accomplish this repetitive task quickly and more efficiently as shown below:
Kill all applications on YARN which are in ACCEPTED state:
for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
Kill all applications on YARN which are in RUNNING state:
for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
Not clear on what you do and don't have control over at this point. If you can interpose a different OutputStream class on the destination file, you could use a subtype of OutputStream which converts Strings to bytes under a charset you define, say UTF-8 by default. If modified UTF-8 is suffcient for your needs, you can use DataOutputStream.writeUTF(String)
:
byte inbytes[] = new byte[1024];
FileInputStream fis = new FileInputStream("response.txt");
fis.read(inbytes);
String in = new String(inbytes, "UTF8");
DataOutputStream out = new DataOutputStream(new FileOutputStream("response-2.txt"));
out.writeUTF(in); // no getBytes() here
If this approach is not feasible, it may help if you clarify here exactly what you can and can't control in terms of data flow and execution environment (though I know that's sometimes easier said than determined). Good luck.
Some people may find an async
example useful:
var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited
json()
converts the response's body from a ReadableStream
to a json object.
The await
statements must be wrapped in an async
function, however you can run await
statements directly in the console of Chrome (as of version 62).
Read this https://docs.djangoproject.com/en/dev/howto/static-files/:
For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.
And try:
~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp
Then add 'myapp'
to INSTALLED_APPS
(myprj/settings.py
).
~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html
Edit myprj/urls.py
:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class HelloView(TemplateView):
template_name = "hello.html"
urlpatterns = patterns('',
url(r'^$', HelloView.as_view(), name='hello'),
)
And run it:
~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver
It works!
Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entry in the Dev Guide, consider reading it for details.
In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.
This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.
You can use setBackgroundResource()
instead which is in API level 1.
It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"]
.
I reproduced here the text from OpenQA concerning this issue (found here):
HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "
") with a single space. All visible newlines (<br>
,<p>
, and<pre>
formatted new lines) should be preserved.We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "
" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "
" markers in your test case to assertText on a field that contains "
".) You may also put extra newlines and spaces in your Selenese<td>
tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "
foo
". But if you simply write<td>foo </td>
in your Selenese test case, we'll replace your extra spaces with just one space.This problem has a simple workaround. We've defined a variable in Selenese,
${space}
, whose value is a single space. You can use${space}
to insert a space that won't be automatically trimmed, like this:<td>foo${space}${space}${space}</td>
. We've also included a variable${nbsp}
, that you can use to insert a non-breaking space.Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like
//div[text()="hello world"]
but the HTML of the link is really "hello world
", you'll need to insert a real "
" into your Selenese test case to get it to match, like this://div[text()="hello${nbsp}world"]
.
Here is a relatively clean solution for others looking up this topic:
// run when eventlistener is triggered
$("#CompanyList").on( "autocompletechange", function(event,ui) {
// post value to console for validation
console.log($(this).val());
});
Per api.jqueryui.com/autocomplete/, this binds a function to the eventlistener. It is triggered both when the user selects a value from the autocomplete list and when they manually type in a value. The trigger fires when the field loses focus.
You don't need to test if $?
is not 0
. The shell provides &&
and ||
so you can easily branch based on implicit result of that test:
some_command && {
# executes this block of code,
# if some_command would result in: $? -eq 0
} || {
# executes this block of code,
# if some_command would result in: $? -ne 0
}
You can remove either branch, depending on what you want. So if you just want to test for failure (i.e. $? -ne 0
):
some_command_returning_nonzero || {
# executes this block of code when: $? -ne 0
# and nothing if the command succeeds: $? -eq 0
}
However, the code you provided in the question works, as is. I'm confused that you got syntax errors & concluded that $?
was a string. It's most likely that the errant code causing the syntax error was not provided with the question. This is especially evident because you claim that no one else's solutions work either. When this happens, you have to re-evaluate your assumptions.
NB: The code above may give confusing results if the code inside the braces returns an error. In that case simply use the if command instead, like this:
if some_command; then
# executes this block of code,
# if some_command would result in: $? -eq 0
else
# executes this block of code,
# if some_command would result in: $? -ne 0
fi
I had this problem working with pycurl and I solved it using
c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0)
like Eric Caron says.
For this thing you can use @property
as an decorator, so you could use instance methods as attributes. For example:
class Word_Parser:
def __init__(self, sentences):
self.sentences = sentences
@property
def parser(self):
self.word_list = self.sentences.split()
@property
def sort_word_list(self):
self.sorted_word_list = self.word_list.sort()
@property
def num_words(self):
self.num_words = len(self.word_list)
test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words
so you can use access the attributes without calling (i.e., without the ()
).
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
The R-squared is not dependent on the number of variables in the model. The adjusted R-squared is.
The adjusted R-squared adds a penalty for adding variables to the model that are uncorrelated with the variable your trying to explain. You can use it to test if a variable is relevant to the thing your trying to explain.
Adjusted R-squared is R-squared with some divisions added to make it dependent on the number of variables in the model.
Check out Marker Clusterer for V3 - this library clusters nearby points into a group marker. The map zooms in when the clusters are clicked. I'd imagine when zoomed right in you'd still have the same problem with markers on the same spot though.
I see this is old but I needed the code from SingleNegationElimination however I had issue with the data containing non utf-8 characters. These appeared in fields I was not overly concerned with so I chose to ignore them. However that took some effort. I am new to python so with some trial and error I got it to work. The code is a copy of SingleNegationElimination with the extra handling of utf-8. I tried to do it with https://docs.python.org/2.7/library/csv.html but in the end gave up. The below code worked.
import csv, json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("Scope","Comment","OOS Code","In RMF","Code","Status","Name","Sub Code","CAT","LOB","Description","Owner","Manager","Platform Owner")
reader = csv.DictReader(csvfile , fieldnames)
code = ''
for row in reader:
try:
print('+' + row['Code'])
for key in row:
row[key] = row[key].decode('utf-8', 'ignore').encode('utf-8')
json.dump(row, jsonfile)
jsonfile.write('\n')
except:
print('-' + row['Code'])
raise
Starting an Activity is not the right approach for this behavior. Instead have your BroadcastReceiver use an intent to start a Service which can continue to run as long as possible. (See http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle)
See also Persistent service
Sorry i know this is a bit late... But i have a much easier way... To binary string :
//Add 128 to get a value from 0 - 255
String bs = Integer.toBinaryString(data[i]+128);
bs = getCorrectBits(bs, 8);
getCorrectBits method :
private static String getCorrectBits(String bitStr, int max){
//Create a temp string to add all the zeros
StringBuilder sb = new StringBuilder();
for(int i = 0; i < (max - bitStr.length()); i ++){
sb.append("0");
}
return sb.toString()+ bitStr;
}
If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:
ActiveCell.DisplayFormat.Interior.Color
This also seems to work just fine on regular cells.
Another solution could be something like following (works depending on your element's display property):
HTML:
<div class="left-align">Left</div>
<div class="right-align">Right</div>
CSS:
.left-align {
margin-left: 0;
margin-right: auto;
}
.right-align {
margin-left: auto;
margin-right: 0;
}
There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.
You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:
Top level classes:
1 public class
0 private class
any number of default/protected classes
Inner classes:
any number of inner classes with any visibility (default, private, protected, public)
Please correct me if I am wrong.
This is a simple ping I use in one of the projects:
public static class Ping {
public String net = "NO_CONNECTION";
public String host = "";
public String ip = "";
public int dns = Integer.MAX_VALUE;
public int cnt = Integer.MAX_VALUE;
}
public static Ping ping(URL url, Context ctx) {
Ping r = new Ping();
if (isNetworkConnected(ctx)) {
r.net = getNetworkType(ctx);
try {
String hostAddress;
long start = System.currentTimeMillis();
hostAddress = InetAddress.getByName(url.getHost()).getHostAddress();
long dnsResolved = System.currentTimeMillis();
Socket socket = new Socket(hostAddress, url.getPort());
socket.close();
long probeFinish = System.currentTimeMillis();
r.dns = (int) (dnsResolved - start);
r.cnt = (int) (probeFinish - dnsResolved);
r.host = url.getHost();
r.ip = hostAddress;
}
catch (Exception ex) {
Timber.e("Unable to ping");
}
}
return r;
}
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
@Nullable
public static String getNetworkType(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
return activeNetwork.getTypeName();
}
return null;
}
Usage: ping(new URL("https://www.google.com:443/"), this);
Result: {"cnt":100,"dns":109,"host":"www.google.com","ip":"212.188.10.114","net":"WIFI"}
You have installed a toolchain which was compiled for i686 on a box which is running an x86_64 userland.
Use an i686 VM.
Try using the html() function.
$('#<%=Label1.ClientID%>').html();
You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.
Use this to get the page scroll position.
var screenTop = $(document).scrollTop();
$('#content').css('top', screenTop);
On Mac press Ctrl+\ to quit a python process attached to a terminal.
Your json string is wrapped within square brackets ([]
), hence it is interpreted as array instead of single RetrieveMultipleResponse
object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse
, for example :
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
I think that substitution is an indirect way of getting to the solution. If you want to retrieve all the numbers, I recommend gregexpr
:
matches <- regmatches(years, gregexpr("[[:digit:]]+", years))
as.numeric(unlist(matches))
If you have multiple matches in a string, this will get all of them. If you're only interested in the first match, use regexpr
instead of gregexpr
and you can skip the unlist
.
Ended up to have a file named polyfill.js in projectpath\src\polyfill.js That file only contains this line: import 'core-js'; this polyfills not only es-6, but is the correct way to use core-js since version 3.0.0.
I added the polyfill.js to my webpack-file entry attribute like this:
entry: ['./src/main.scss', './src/polyfill.js', './src/main.jsx']
Works perfectly.
I also found some more information here : https://github.com/zloirock/core-js/issues/184
The library author (zloirock) claims:
ES6 changes behaviour almost all features added in ES5, so core-js/es6 entry point includes almost all of them. Also, as you wrote, it's required for fixing broken browser implementations.
(Quotation https://github.com/zloirock/core-js/issues/184 from zloirock)
So I think import 'core-js'; is just fine.
In fact, the class library you are implementing, is retrieving information from app.config inside the application that is consuming it, so, the most correct way to implement configuration for class libraries at .net in VS is to prepare app.config in the application to configure everything it consumes, like libraries configuration.
I have worked a little with log4net, and I found that the one who prepared the application always had a section for log4net configuration inside main app.config.
I hope you find this information useful.
See you, and post comments about the solution you found.
EDIT:
At the next link you have an app.config with the section for log4net:
http://weblogs.asp.net/tgraham/archive/2007/03/15/a-realistic-log4net-config.aspx
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
Well, display: none;
will not display the table at all, try display: inline-block;
with the width and min-width declarations remaining 'auto'.
Nobody mentioned it, but you can also simply use loc
with the index and column labels.
df.loc[2, 'Letters']
# 'C'
Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.
df.set_index('Numbers').loc[3, 'Letters']
I had the same problem, my code is below:
private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
private Statement stmt = conn.createStatement();
I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:
No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud
so I loaded the driver class, as below, when I saw other answers posted:
Class.forName("com.mysql.jdbc.Driver");
It works now! I don't know why it works well locally, I need your help, thank you so much!
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
I was able to get my similar command working using the following approach:
msdeploy.exe -verb=sync "-source=dbFullSql=Server=THESERVER;Database=myDB;UID=sa;Pwd=saPwd" -dest=dbFullSql=c:\temp\test.sql
For your command (not that it helps much now), things would look something like this:
msdeploy.exe -verb=sync "-source=dbfullsql=Server=mysource;Trusted_Connection=false;UID=sa;Pwd=sapass!;Database=mydb;" "-dest=dbfullsql=Server=mydestsource;Trusted_Connection=false;UID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass
The key points are:
I didn't try adding the "computername" part at the end of the command line, but hopefully this info will help others reading this now get closer to their desired result.
The answer depends on what do you need a loop for.
of course you can have a loop similar to Java:
for i in xrange(len(my_list)):
but I never actually used loops like this,
because usually you want to iterate
for obj in my_list
or if you need an index as well
for index, obj in enumerate(my_list)
or you want to produce another collection from a list
map(some_func, my_list)
[somefunc[x] for x in my_list]
also there are itertools
module that covers most of iteration related cases
also please take a look at the builtins like any
, max
, min
, all
, enumerate
I would say - do not try to write Java-like code in python. There is always a pythonic way to do it.
The solution is in the link that you provided in your question:
datetime.combine(date.today(), time()) + timedelta(hours=1)
Full example:
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()
Output:
00:25:00
Use this :
#Inputs
L1 = [1, 2]
L2 = [3,4,5]
#Code
L1+L2
#Output
[1, 2, 3, 4, 5]
By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.
Happy Learning...:)
Quoted at the bottom of the Wikipedia page on BOM: http://en.wikipedia.org/wiki/Byte-order_mark#cite_note-2
"Use of a BOM is neither required nor recommended for UTF-8, but may be encountered in contexts where UTF-8 data is converted from other encoding forms that use a BOM or where the BOM is used as a UTF-8 signature"
Push always unique value in array
ab = [
{"id":"1","val":"value1"},
{"id":"2","val":"value2"},
{"id":"3","val":"value3"}
];
var clickId = [];
var list = JSON.parse(ab);
$.each(list, function(index, value){
if(clickId.indexOf(value.id) < 0){
clickId.push(value.id);
}
});
To complement the previous stated solution, use:
str = str.replace("%", "%%");
One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:
c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
10: File (RW-) C:\Windows
1C: File (RW-) D:\some\locked\path\OpenFile.txt
[...]
c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls
Base Size Version Path
0x00400000 0x29000 2.25.0000.0000 D:\opt\SysinternalsSuite\Listdlls.exe
0x76ed0000 0x180000 6.01.7601.17725 C:\Windows\SysWOW64\ntdll.dll
[...]
c:\SysInternals>listdlls
Unfortunately, you have to "run as Administrator" to be able to use them.
Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename>
should get you very close with both utilities, though
c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
188: File (RW-) D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]
Here we can see that gvim.exe is the one having this file open.
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
$array = json_decode(json_encode((array)simplexml_load_string($xml)),true);
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
The easiest way to do this, is using cstdio's printf. Actually, i'm surprised that anyone mentioned printf! anyway, you need to include the library, like this...
#include<cstdio>
int main() {
double total;
cin>>total;
printf("%.2f\n", total);
}
This will print the value of "total" (that's what %
, and then ,total
does) with 2 floating points (that's what .2f
does). And the \n
at the end, is just the end of line, and this works with UVa's judge online compiler options, that is:
g++ -lm -lcrypt -O2 -pipe -DONLINE_JUDGE filename.cpp
the code you are trying to run will not run with this compiler options...
Your query should be SELECT * FROM `table` WHERE find_in_set(interests, "sports,pub")>0
What I understand is that you store the interests in one field of your table, which is a misconception. You should definitively have an "interest" table.
-XX:PermSize -XX:MaxPermSize
are used to set size for Permanent Generation.
Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
I am currently working on a Linq-like library for Typescript and wanted to implement something like GetProperties of C# in Typescript / Javascript. The more I work with Typescript and generics, the clearer picture I get of that you usually have to have an instantiated object with intialized properties to get any useful information out at runtime about properties of a class. But it would be nice to retrieve information anyways just from the constructor function object, or an array of objects and be flexible about this.
Here is what I ended up with for now.
First off, I define Array prototype method ('extension method' for you C# developers).
export { } //creating a module of below code
declare global {
interface Array<T> {
GetProperties<T>(TClass: Function, sortProps: boolean): string[];
} }
The GetProperties method then looks like this, inspired by madreason's answer.
if (!Array.prototype.GetProperties) {
Array.prototype.GetProperties = function <T>(TClass: any = null, sortProps: boolean = false): string[] {
if (TClass === null || TClass === undefined) {
if (this === null || this === undefined || this.length === 0) {
return []; //not possible to find out more information - return empty array
}
}
// debugger
if (TClass !== null && TClass !== undefined) {
if (this !== null && this !== undefined) {
if (this.length > 0) {
let knownProps: string[] = Describer.describe(this[0]).Where(x => x !== null && x !== undefined);
if (sortProps && knownProps !== null && knownProps !== undefined) {
knownProps = knownProps.OrderBy(p => p);
}
return knownProps;
}
if (TClass !== null && TClass !== undefined) {
let knownProps: string[] = Describer.describe(TClass).Where(x => x !== null && x !== undefined);
if (sortProps && knownProps !== null && knownProps !== undefined) {
knownProps = knownProps.OrderBy(p => p);
}
return knownProps;
}
}
}
return []; //give up..
}
}
The describer method is about the same as madreason's answer. It can handle both class Function and if you get an object instead. It will then use Object.getOwnPropertyNames if no class Function is given (i.e. the class 'type' for C# developers).
class Describer {
private static FRegEx = new RegExp(/(?:this\.)(.+?(?= ))/g);
static describe(val: any, parent = false): string[] {
let isFunction = Object.prototype.toString.call(val) == '[object Function]';
if (isFunction) {
let result = [];
if (parent) {
var proto = Object.getPrototypeOf(val.prototype);
if (proto) {
result = result.concat(this.describe(proto.constructor, parent));
}
}
result = result.concat(val.toString().match(this.FRegEx));
result = result.Where(r => r !== null && r !== undefined);
return result;
}
else {
if (typeof val == "object") {
let knownProps: string[] = Object.getOwnPropertyNames(val);
return knownProps;
}
}
return val !== null ? [val.tostring()] : [];
}
}
Here you see two specs for testing this out with Jasmine.
class Hero {
name: string;
gender: string;
age: number;
constructor(name: string = "", gender: string = "", age: number = 0) {
this.name = name;
this.gender = gender;
this.age = age;
}
}
class HeroWithAbility extends Hero {
ability: string;
constructor(ability: string = "") {
super();
this.ability = ability;
}
}
describe('Array Extensions tests for TsExtensions Linq esque library', () => {
it('can retrieve props for a class items of an array', () => {
let heroes: Hero[] = [<Hero>{ name: "Han Solo", age: 44, gender: "M" }, <Hero>{ name: "Leia", age: 29, gender: "F" }, <Hero>{ name: "Luke", age: 24, gender: "M" }, <Hero>{ name: "Lando", age: 47, gender: "M" }];
let foundProps = heroes.GetProperties(Hero, false);
//debugger
let expectedArrayOfProps = ["name", "age", "gender"];
expect(foundProps).toEqual(expectedArrayOfProps);
expect(heroes.GetProperties(Hero, true)).toEqual(["age", "gender", "name"]);
});
it('can retrieve props for a class only knowing its function', () => {
let heroes: Hero[] = [];
let foundProps = heroes.GetProperties(Hero, false);
let expectedArrayOfProps = ["this.name", "this.gender", "this.age"];
expect(foundProps).toEqual(expectedArrayOfProps);
let foundPropsThroughClassFunction = heroes.GetProperties(Hero, true);
//debugger
expect(foundPropsThroughClassFunction.SequenceEqual(["this.age", "this.gender", "this.name"])).toBe(true);
});
And as madreason mentioned, you have to initialize the props to get any information out from just the class Function itself, or else it is stripped away when Typescript code is turned into Javascript code.
Typescript 3.7 is very good with Generics, but coming from a C# and Reflection background, some fundamental parts of Typescript and generics still feels somewhat loose and unfinished business. Like my code here, but at least I got out the information I wanted - a list of property names for a given class or instance of objects.
SequenceEqual is this method btw:
if (!Array.prototype.SequenceEqual) {
Array.prototype.SequenceEqual = function <T>(compareArray: T): boolean {
if (!Array.isArray(this) || !Array.isArray(compareArray) || this.length !== compareArray.length)
return false;
var arr1 = this.concat().sort();
var arr2 = compareArray.concat().sort();
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
}
My understanding is that adding r+
opens for both read and write (just like w+
, though as pointed out in the comment, will truncate the file). The b
just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).
You can just go to Breakpoints in the chrome developer console, right click and remove breakpoints. Simple.
you can use System.Diagnostics.Process.Start as well as WIN32 ShellExecute function by means of interop, for opening PDF files using the default viewer:
System.Diagnostics.Process.Start("SOMEAPP.EXE","Path/SomeFile.Ext");
[System.Runtime.InteropServices.DllImport("shell32. dll")]
private static extern long ShellExecute(Int32 hWnd, string lpOperation,
string lpFile, string lpParameters,
string lpDirectory, long nShowCmd);
Another approach is to place a WebBrowser Control into your Form and then use the Navigate method for opening the PDF file:
ThewebBrowserControl.Navigate(@"c:\the_file.pdf");
I am using this linq query for my application. if this match your requirement you can refer this. here i have joined(Left outer join) with 3 tables.
Dim result = (From csL In contractEntity.CSLogin.Where(Function(cs) cs.Login = login AndAlso cs.Password = password).DefaultIfEmpty
From usrT In contractEntity.UserType.Where(Function(uTyp) uTyp.UserTypeID = csL.UserTyp).DefaultIfEmpty ' <== makes join left join
From kunD In contractEntity.EmployeeMaster.Where(Function(kunDat) kunDat.CSLoginID = csL.CSLoginID).DefaultIfEmpty
Select New With {
.CSLoginID = csL.CSLoginID,
.UserType = csL.UserTyp}).ToList()
var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
No idea how you got your results, since it would not sort by string value... You should reverse a1
and a2
in your example
Best way in any case (as per Mladen) is:
metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
# ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]
If you need a hash as a result, you can use to_h
(in Ruby 2.0+)
metrics.sort_by {|_key, value| value}.to_h
# ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}
Simlpy close and re-open the PR if you do not have the write access.
You can hit Ctrl+Break on the keyboard to cancel/stop a build that is currently in progress.