You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
Set Copy Enbale to true in netstandard.dll properties.
Open Solution Explorer and right click on netstandard.dll. Set Copy Local to true.
Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.
If your method is returning something back, you can solve this error by putting
.Result
to the end of the job and
.Wait()
if it doesn't return anything.
You can get a client
with new session directly like below.
s3_client = boto3.client('s3',
aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
region_name=REGION_NAME
)
I've tried all possible solutions offered but unluckly my vscode settings won't changed its linter path. So, I tride to explore vscode settings in settings > User Settings > python. Find Linting: Pylint Path and change it to "pylint_django". Don't forget to change the linter to "pylint_django" at settings > User Settings > python configuration from "pyLint" to "pylint_django".
You also can Redirect
within the Route
as follows. This is for handle invalid routes.
<Route path='*' render={() =>
(
<Redirect to="/error"/>
)
}/>
I had similar symptoms, but my problem was that I was nesting BrowserRouter
Do not nest BrowserRouter
, because the history
object will refer to the nearest BrowserRouter
parent. So when you do a history.push(targeturl)
and that targeturl it's not in that particular BrowserRouter
it won't match any of it's route, so it will not load any sub-component.
Nest the Switch
without wrapping it with a BrowserRouter
App.js
file<BrowserRouter>
<Switch>
<Route exact path="/nestedrouter" component={NestedRouter} />
<Route exact path="/target" component={Target} />
</Switch>
</BrowserRouter>
NestedRouter.js
file<BrowserRouter>
<Switch>
<Route exact path="/nestedrouter/" component={NestedRouter} />
<Route exact path="/nestedrouter/subroute" component={SubRoute} />
</Switch>
</BrowserRouter>
BrowserRouter
from NestedRouter.js
file <Switch>
<Route exact path="/nestedrouter/" component={NestedRouter} />
<Route exact path="/nestedrouter/subroute" component={SubRoute} />
</Switch>
Got same problem with project porting from VS2013 to VS2017,
Fix: change "Properties->General->Windows SDK Version" to 10
None of the answers worked until I removed the HasNoKey() method from the entity. Dont forget to remove this from your data context or the [Key] attribute will not fix anything.
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!
produces a value of the type ofx
withnull
andundefined
excluded. Similar to type assertions of the forms<T>x
andx as T
, the!
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
If you want to include render prop components:
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
PropTypes.func
])
What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.
In your component
[
{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})
And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.
Take a look at my answer at mapping an array to jsx
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
You can also use Destructuring assignment.
class AddAddressComponent extends React.Component {
render() {
const {
province="insertDefaultValueHere1",
city="insertDefaultValueHere2"
} = this.props
return (
<div>{province}</div>
<div>{city}</div>
)
}
}
I like this approach as you don't need to write much code.
I myself landed on these answers last day, trying to find a way to deep copy complex structures, which may include recursive links. As I wasn't satisfied with anything being suggested before, I implemented this wheel myself. And it works quite well. Hope it helps someone.
Example usage:
OriginalStruct.deep_copy = deep_copy; // attach the function as a method
TheClone = OriginalStruct.deep_copy();
Please look at https://github.com/latitov/JS_DeepCopy for live examples how to use it, and also deep_print() is there.
If you need it quick, right here's the source of deep_copy() function:
function deep_copy() {
'use strict'; // required for undef test of 'this' below
// Copyright (c) 2019, Leonid Titov, Mentions Highly Appreciated.
var id_cnt = 1;
var all_old_objects = {};
var all_new_objects = {};
var root_obj = this;
if (root_obj === undefined) {
console.log(`deep_copy() error: wrong call context`);
return;
}
var new_obj = copy_obj(root_obj);
for (var id in all_old_objects) {
delete all_old_objects[id].__temp_id;
}
return new_obj;
//
function copy_obj(o) {
var new_obj = {};
if (o.__temp_id === undefined) {
o.__temp_id = id_cnt;
all_old_objects[id_cnt] = o;
all_new_objects[id_cnt] = new_obj;
id_cnt ++;
for (var prop in o) {
if (o[prop] instanceof Array) {
new_obj[prop] = copy_array(o[prop]);
}
else if (o[prop] instanceof Object) {
new_obj[prop] = copy_obj(o[prop]);
}
else if (prop === '__temp_id') {
continue;
}
else {
new_obj[prop] = o[prop];
}
}
}
else {
new_obj = all_new_objects[o.__temp_id];
}
return new_obj;
}
function copy_array(a) {
var new_array = [];
if (a.__temp_id === undefined) {
a.__temp_id = id_cnt;
all_old_objects[id_cnt] = a;
all_new_objects[id_cnt] = new_array;
id_cnt ++;
a.forEach((v,i) => {
if (v instanceof Array) {
new_array[i] = copy_array(v);
}
else if (v instanceof Object) {
new_array[i] = copy_object(v);
}
else {
new_array[i] = v;
}
});
}
else {
new_array = all_new_objects[a.__temp_id];
}
return new_array;
}
}
Cheers@!
Quickfix
I had similar issue and I resolved it doing the following
Alternative 1: Disable sandbox
As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.
Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script:
Alternative 2: Disable script security
As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:
-Dpermissive-script-security.enabled=true
So you jenkins.xml will look something like this:
<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>
Make sure you know what you are doing if you implement this!
Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct
"wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name
rather than by String
. For more details see the now legacy Migrating to Swift 3 guide
Swift 2.2 usage:
// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"
// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)
Swift 3 & 4 usage:
// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)
All of the system notification types are now defined as static constants on Notification.Name
; i.e. .UIApplicationDidFinishLaunching
, .UITextFieldTextDidChange
, etc.
You can extend Notification.Name
with your own custom notifications in order to stay consistent with the system notifications:
// Definition:
extension Notification.Name {
static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
Swift 4.2 usage:
Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication
with your own custom notifications instead of Notification.Name :
// Definition:
UIApplication {
public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)
The values()
method returns a QuerySet containing dictionaries:
<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>
The values_list()
method returns a QuerySet containing tuples:
<QuerySet [(1,), (2,)]>
If you are using values_list()
with a single field, you can use flat=True
to return a QuerySet of single values instead of 1-tuples:
<QuerySet [1, 2]>
It changes in angular 2.1.0
In something.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
{
path: '',
component: BlogComponent
},
{
path: 'add',
component: AddComponent
},
{
path: 'edit/:id',
component: EditComponent,
data: {
type: 'edit'
}
}
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes),
MaterialModule.forRoot(),
FormsModule
],
declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }
To get the data or params in edit component
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit() {
this.route.snapshot.params['id'];
this.route.snapshot.data['type'];
}
}
A friendly method to use is the following, once prop updates it will automatically rerender component:
render {
let textWhenComponentUpdate = this.props.text
return (
<View>
<Text>{textWhenComponentUpdate}</Text>
</View>
)
}
Reason : Old versions of Tomcat 6 JSP compiler don't seem to be aware of JDK 8 constant pool enhancements - eg. method handles. New code in JDK 8u is using a method handle instead of creating an anonymous class. This will cause the method handle to be listed in the constant pool and the eclipse compiler will choke on this - https://bz.apache.org/bugzilla/show_bug.cgi?id=56613
It worked for me with version 3.0.0-M1.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
You might need to run it with sudo.
If you hafe upload your file in media than:
media
example-input-file.txt
views.py
def download_csv(request):
file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
urls.py
path('download_csv/', views.download_csv, name='download_csv'),
download.html
a href="{% url 'download_csv' %}" download=""
It took me a lot of time to figure out, but finally here is a simple way to list contents of a subfolder in S3 bucket using boto3. Hope it helps
prefix = "folderone/foldertwo/"
s3 = boto3.resource('s3')
bucket = s3.Bucket(name="bucket_name_here")
FilesNotFound = True
for obj in bucket.objects.filter(Prefix=prefix):
print('{0}:{1}'.format(bucket.name, obj.key))
FilesNotFound = False
if FilesNotFound:
print("ALERT", "No file in {0}/{1}".format(bucket, prefix))
Even though this answer was too late, I'm adding it because I also went through a horrible time finding answer for the same matter. Only different was, I was struggling with AWS Comprehend Medical API.
At the moment I'm writing this answer, if anyone come across the same issue with any AWS SDKs please downgrade jackson-annotaions or any jackson dependencies to 2.8.* versions. The latest 2.9.* versions does not working properly with AWS SDK for some reason. Anyone have any idea about the reason behind that feel free to comment below.
Just in case if anyone is lazy to google maven repos, I have linked down necessary repos.Check them out!
mybe your hive metastore are inconsistent! I'm in this scene.
first. I run
$ schematool -dbType mysql -initSchema
then I found this
Error: Duplicate key name 'PCS_STATS_IDX' (state=42000,code=1061) org.apache.hadoop.hive.metastore.HiveMetaException: Schema initialization FAILED! Metastore state would be inconsistent !!
then I run
$ schematool -dbType mysql -info
found this error
Hive distribution version: 2.3.0 Metastore schema version: 1.2.0 org.apache.hadoop.hive.metastore.HiveMetaException: Metastore schema version is not compatible. Hive Version: 2.3.0, Database Schema Version: 1.2.0
hive_db
schematool -dbType mysql -initSchema
for initialize metadataIn my case I had the following by mistake in my connection string:
Encrypt=True
Changing to
Encrypt=False
Solved the problem
"Server=***;Initial Catalog=***;Persist Security Info=False;User ID=***;Password=***;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;"
Try df['quantity'] = df['quantity'] * -1
.
I had to delete the bin and obj folders from each folder in order to resolve this.
I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:
interface TestObject {
name:string;
value:number;
}
@Component({
selector: 'app',
template: `
<h4>Select Object via 2-way binding</h4>
<select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
<option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
</select>
<h4>You selected:</h4> {{selectedObject }}
`,
directives: [FORM_DIRECTIVES]
})
export class App {
objArray:TestObject[];
selectedObject:TestObject;
constructor(){
this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
this.selectedObject = this.objArray[1];
}
updateSelectedValue(event:string): void{
this.selectedObject = JSON.parse(event);
}
}
For future readers, another cause for NPE when using mocks is forgetting to initialize the mocks like so:
@Mock
SomeMock someMock;
@InjectMocks
SomeService someService;
@Before
public void setup(){
MockitoAnnotations.initMocks(this); //without this you will get NPE
}
@Test
public void someTest(){
Mockito.when(someMock.someMethod()).thenReturn("some result");
// ...
}
Also make sure you are using JUnit for all annotations. I once accidently created a test with @Test from testNG so the @Before didn't work with it (in testNG the annotation is @BeforeTest)
A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.
...
constructor(props){
...
//create a ref
this.someRefName = React.createRef();
}
onScroll(){
let offsetTop = this.someRefName.current.offsetTop;
}
render(){
...
<Component ref={this.someRefName} />
}
"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:
<Button Content="Edit"
Command="{Binding EditCommand}"
CommandParameter="{Binding ViewModelItem}" >
And then this in your view model:
private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
get
{
return this._ViewModelItem;
}
set
{
this._ViewModelItem = value;
RaisePropertyChanged(() => this.ViewModelItem);
}
}
public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
... do something here...
}
Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.
It could be that something else is running on port 8080, and you're actually connecting to it by mistake.
Definitely check that out, especially if you have dockers that are bringing up other services you don't control, and are port forwarding those services.
Update only works on updating querysets. If you want to update multiple fields at the same time, say from a dict for a single object instance you can do something like:
obj.__dict__.update(your_dict)
obj.save()
Bear in mind that your dictionary will have to contain the correct mapping where the keys need to be your field names and the values the values you want to insert.
Use the pre-compiled SDL2main.lib and SDL.lib for your VS2015 project's library : https://buildbot.libsdl.org/sdl-builds/sdl-visualstudio/sdl-visualstudio-2225.zip
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
What solved this problem for me was changing WSGIPassAuthorization
to 'On'
in wsgi.conf
.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
boto3 now has a nicer interface than the client:
resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)
This by itself isn't tremendously better than the client
in the accepted answer (although the docs say that it does a better job retrying uploads and downloads on failure) but considering that resources are generally more ergonomic (for example, the s3 bucket and object resources are nicer than the client methods) this does allow you to stay at the resource layer without having to drop down.
Resources
generally can be created in the same way as clients, and they take all or most of the same arguments and just forward them to their internal clients.
I recently migrated one of our corporate projects from Eclipse to Android Studio.
We too got the below error during the migration:
Error:Execution failed for task ':appName:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
To resolve it, we had to do a few things:
compile 'com.android.support:support-v4:23' compile 'com.google.android.gms:play-services:9.0.0'
to compile 'com.google.android.gms:play-services:9.0.0'
defaultConfig { multiDexEnabled true }
dexOptions { incremental true javaMaxHeapSize "4g" }
"(SqlConnection)context"
-- This type-casting no longer works. You can do: "SqlConnection context;
".AsSqlServer()"
-- Does not Exist.
"command.ExecuteNonQuery();"
-- Does not return results. reader=command.ExecuteReader()
does work.
With dt.load(reader)... then you have to switch the framework out of 5.0 and back to 4.51, as 5.0 does not support datatables/datasets, yet. Note: This is VS2015 RC.
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
What do I need to do to make this function wait for the result of the promise?
Use async/await
(NOT Part of ECMA6, but
available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN
async function waitForPromise() {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:
async function waitForPromise(): Promise<string> {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
I think this approach is the right one:
public List<Class> getClasses() throws ClassNotFoundException {
List<Class> classes;
try {
classes = Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String").map(className -> {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new UndeclaredThrowableException(e);
}
}).collect(Collectors.toList());
} catch (UndeclaredThrowableException e) {
if (e.getCause() instanceof ClassNotFoundException) {
throw (ClassNotFoundException) e.getCause();
} else {
// this should never happen
throw new IllegalStateException(e.getMessage(), e);
}
}
return classes;
}
Wrapping the checked exception inside the Callable
in a UndeclaredThrowableException
(that’s the use case for this exception) and unwrapping it outside.
Yes, I find it ugly, and I would advise against using lambdas in this case and just fall back to a good old loop, unless you are working with a parallel stream and paralellization brings an objective benefit that justifies the unreadability of the code.
As many others have pointed out, there are solutions to this situation, and I hope one of them will make it into a future version of Java.
UPDATE 15.3.2017:
I have opened a Django-issue on this and it seems to be preliminary accepted here: https://code.djangoproject.com/ticket/27825
My experience is that when using the Constructor
(ORM
) class by references with Django 1.10.5
there might be some inconsistencies in the data (i.e. the attributes of the created object may get the type of the input data instead of the casted type of the ORM object property)
example:
models
class Payment(models.Model):
amount_cash = models.DecimalField()
some_test.py
- object.create
Class SomeTestCase:
def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
objs = []
if not base_data:
base_data = {'amount_case': 123.00}
for modifier in modifiers:
actual_data = deepcopy(base_data)
actual_data.update(modifier)
# Hacky fix,
_obj = _constructor.objects.create(**actual_data)
print(type(_obj.amount_cash)) # Decimal
assert created
objs.append(_obj)
return objs
some_test.py
- Constructor()
Class SomeTestCase:
def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
objs = []
if not base_data:
base_data = {'amount_case': 123.00}
for modifier in modifiers:
actual_data = deepcopy(base_data)
actual_data.update(modifier)
# Hacky fix,
_obj = _constructor(**actual_data)
print(type(_obj.amount_cash)) # Float
assert created
objs.append(_obj)
return objs
You can install scipy and numpy using their wheels.
First install wheel package if it's already not there...
pip install wheel
Just select the package you want from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
Example: if you're running python3.5
32 bit on Windows choose scipy-0.18.1-cp35-cp35m-win_amd64.whl
then it will automatically download.
Then go to the command line and change the directory to the downloads folder and install the above wheel using pip
.
Example:
cd C:\Users\[user]\Downloads
pip install scipy-0.18.1-cp35-cp35m-win_amd64.whl
In Java I had to set a property
System.setProperty(SDKGlobalConfiguration.ENFORCE_S3_SIGV4_SYSTEM_PROPERTY, "true")
and add the region to the s3Client instance.
s3Client.setRegion(Region.getRegion(Regions.EU_CENTRAL_1))
Let's focus on the error:
Exception Value: no such column: snippets_snippet.owner_id
Let's see if that's true...
You can use the manage.py command to access your db shell (this will use the settings.py variables, so you're sure to connect to the right one).
manage.py dbshell
You can now show the details of your table by typing:
.schema TABLE_NAME
Or in your case:
.schema snippets_snippet
More sqlite commands can be found here or by issuing a:
.help
Lastly, end your session by typing:
.quit
This doesn't get you out of the woods, but it helps you know what end of the problem to work on :)
Good luck!
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
For django 1.10 you may have to do python manage.py makemigrations appname
.
You can use Environment
Class to get data :
@Autowired
private Environment env;
String prop= env.getProperty('some.prop');
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
Spring boot doc 'was' wrong (they have since fixed it) :
To switch it off you can set error.whitelabel.enabled=false
should be
To switch it off you can set server.error.whitelabel.enabled=false
If you are working with Swift 5+ you have to use UserDefaults.standard.setValue(value, forKey: key)
and to get saved data you have to use UserDefaults.standard.dictionary(forKey: key)
.
For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer
you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with
entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();
Better Way to Provide Choice inside a django Model :
from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
GRADUATE = 'GR'
YEAR_IN_SCHOOL_CHOICES = [
(FRESHMAN, 'Freshman'),
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
(GRADUATE, 'Graduate'),
]
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
It seems like a Android Runtime bug. There seems to be finalizer that runs in its separate thread and calls finalize() method on objects if they are not in the current frame of the stacktrace. For example following code(created to verify this issue) ended with the crash.
Let's have some cursor that do something in finalize method(e.g. SqlCipher ones, do close() which locks to the database that is currently in use)
private static class MyCur extends MatrixCursor {
public MyCur(String[] columnNames) {
super(columnNames);
}
@Override
protected void finalize() {
super.finalize();
try {
for (int i = 0; i < 1000; i++)
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And we do some long running stuff having opened cursor:
for (int i = 0; i < 7; i++) {
new Thread(new Runnable() {
@Override
public void run() {
MyCur cur = null;
try {
cur = new MyCur(new String[]{});
longRun();
} finally {
cur.close();
}
}
private void longRun() {
try {
for (int i = 0; i < 1000; i++)
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
This causes following error:
FATAL EXCEPTION: FinalizerWatchdogDaemon
Process: la.la.land, PID: 29206
java.util.concurrent.TimeoutException: MyCur.finalize() timed out after 10 seconds
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:371)
at java.lang.Thread.sleep(Thread.java:313)
at MyCur.finalize(MessageList.java:1791)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:222)
at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:209)
at java.lang.Thread.run(Thread.java:762)
The production variant with SqlCipher is very similiar:
12-21 15:40:31.668: E/EH(32131): android.content.ContentResolver$CursorWrapperInner.finalize() timed out after 10 seconds_x000D_
12-21 15:40:31.668: E/EH(32131): java.util.concurrent.TimeoutException: android.content.ContentResolver$CursorWrapperInner.finalize() timed out after 10 seconds_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Object.wait(Native Method)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Thread.parkFor$(Thread.java:2128)_x000D_
12-21 15:40:31.668: E/EH(32131): at sun.misc.Unsafe.park(Unsafe.java:325)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.LockSupport.park(LockSupport.java:161)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:840)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued(AbstractQueuedSynchronizer.java:873)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(AbstractQueuedSynchronizer.java:1197)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.ReentrantLock$FairSync.lock(ReentrantLock.java:200)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.util.concurrent.locks.ReentrantLock.lock(ReentrantLock.java:262)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteDatabase.lock(SourceFile:518)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteProgram.close(SourceFile:294)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteQuery.close(SourceFile:136)_x000D_
12-21 15:40:31.668: E/EH(32131): at net.sqlcipher.database.SQLiteCursor.close(SourceFile:510)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.database.CursorWrapper.close(CursorWrapper.java:50)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.database.CursorWrapper.close(CursorWrapper.java:50)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.content.ContentResolver$CursorWrapperInner.close(ContentResolver.java:2746)_x000D_
12-21 15:40:31.668: E/EH(32131): at android.content.ContentResolver$CursorWrapperInner.finalize(ContentResolver.java:2757)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:222)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:209)_x000D_
12-21 15:40:31.668: E/EH(32131): at java.lang.Thread.run(Thread.java:762)
_x000D_
Resume: Close cursors ASAP. At least on Samsung S8 with Android 7 where the issue have been seen.
Add following class into your code
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author vaquar khan
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable();
}
}
And insie of application.properties add
security.ignored=/**
security.basic.enabled=false
management.security.enabled=false
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
I too got this error. Incidentally, i typed __int__ instead of __init__.
I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.
The exception occurred due to the fact that any of the inner classes or other referenced classes didn't implement the serializable implementation. So make sure that all the referenced classes must implement the serializable implementation.
I had this problem in a solution with a Web API project and several library projects. One of the library projects was borking on build, with errors that said the Unity attributes weren't "valid" attributes, and then one error said I needed to reference System.Runtime.
After much searching, reinstalling the 4.5.2 Developer Pack, and nothing working, I figured maybe it was just a version mismatch. So I looked at the properties of every project, and one of the very base libraries was targeting 4.5 while every other one was targeting 4.5.2. I changed that one to also target 4.5.2 and the errors went away.
Check all the references carefully
For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.
Don't :-
xyz = Blogs.objects.get(user_id=id)
Use:-
xyz = Blogs.objects.all().filter(user_id=id)
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
There is only one way to represent null
; that is with null
.
console.log(null === null); // true
console.log(null === true); // false
console.log(null === false); // false
console.log(null === 'null'); // false
console.log(null === "null"); // false
console.log(null === ""); // false
console.log(null === []); // false
console.log(null === 0); // false
That is to say; if any of the clients that consume your JSON representation use the ===
operator; it could be a problem for them.
If you want to convey that you have an object whose attribute myCount
has no value:
{ "myCount": null }
What if you to convey that you have an object with no attributes:
{}
Client code will try to access myCount
and get undefined
; it's not there.
What if you to convey that you have an object with an attribute myCount
that is an empty list:
{ "myCount": [] }
These days something like the following will suffice:
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
restTemplate.exchange(RequestEntity.get(new URI(url)).headers(headers).build(), returnType);
Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:
.Where(y => y.ResponseId.Equals(item.ResponseId))
so you can't call
.First()
on it. Maybe try
.FirstOrDefault()
if it solves the issue.
Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.
You may try removing the table from the model and adding it again. You can do this visually by opening the .edmx file from the Solution Explorer.
Steps:
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
Dim box = New AboutBox1()
box.Show()
End Sub
The issue is that you are serializing your bean with a custom Gson
object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper
(within MappingJackson2HttpMessageConverter
).
If you open up your server logs, you should see something like
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])
among other stack traces.
One solution is to set your Gson
date format to one of the above (in the stacktrace).
The alternative is to register your own MappingJackson2HttpMessageConverter
by configuring your own ObjectMapper
to have the same date format as your Gson
.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource
Problem is
(List<SwitcherServiceSource>) LoadSource.list();
This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource
table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.
List<Object> result = (List<Object>) LoadSource.list();
Iterator itr = result.iterator();
while(itr.hasNext()){
Object[] obj = (Object[]) itr.next();
//now you have one array of Object for each row
String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String
Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
//same way for all obj[2], obj[3], obj[4]
}
from rest_framework import status
from rest_framework.response import Response
class FileUpload(APIView):
def put(request):
try:
file = request.FILES['filename']
#now upload to s3 bucket or your media file
except Exception as e:
print e
return Response(status,
status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(status, status.HTTP_200_OK)
You can't do
LivingRoom.objects.create(user=instance)
because you have an __init__
method that does NOT take user
as argument.
You need something like
#signal function: if a user is created, add control livingroom to the user
def create_control_livingroom(sender, instance, created, **kwargs):
if created:
my_room = LivingRoom()
my_room.user = instance
Update
But, as bruno has already said it, Django's models.Model
subclass's initializer is best left alone, or should accept *args
and **kwargs
matching the model's meta fields.
So, following better principles, you should probably have something like
class LivingRoom(models.Model):
'''Living Room object'''
user = models.OneToOneField(User)
def __init__(self, *args, temp=65, **kwargs):
self.temp = temp
return super().__init__(*args, **kwargs)
Note - If you weren't using temp
as a keyword argument, e.g. LivingRoom(65)
, then you'll have to start doing that. LivingRoom(user=instance, temp=66)
or if you want the default (65), simply LivingRoom(user=instance)
would do.
Place the Utils.objectToJson(entity); call before session closing.
Or you can try to set fetch mode and play with code like this
Session s = ...
DetachedCriteria dc = DetachedCriteria.forClass(MyEntity.class).add(Expression.idEq(id));
dc.setFetchMode("innerTable", FetchMode.EAGER);
Criteria c = dc.getExecutableCriteria(s);
MyEntity a = (MyEntity)c.uniqueResult();
The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.
To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.
I had a similar issue with mongoose :
fields:
[ '[object Object]',
'[object Object]',
'[object Object]',
'[object Object]' ] }
In fact, I was using "type" as a property name in my schema :
fields: [
{
name: String,
type: {
type: String
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
To avoid that behavior, you have to change the parameter to :
fields: [
{
name: String,
type: {
type: { type: String }
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
for each project in your solution make sure that
Properties > Config. Properties > General > Platform Toolset
is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012
you also may be working on v100 from visual studio 2012
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
UseMethod("t")
is telling you that t()
is a (S3) generic function that has methods for different object classes.
For S3 classes, you can use the methods
function to list the methods for a particular generic function or class.
> methods(t)
[1] t.data.frame t.default t.ts*
Non-visible functions are asterisked
> methods(class="ts")
[1] aggregate.ts as.data.frame.ts cbind.ts* cycle.ts*
[5] diffinv.ts* diff.ts kernapply.ts* lines.ts
[9] monthplot.ts* na.omit.ts* Ops.ts* plot.ts
[13] print.ts time.ts* [<-.ts* [.ts*
[17] t.ts* window<-.ts* window.ts*
Non-visible functions are asterisked
"Non-visible functions are asterisked" means the function is not exported from its package's namespace. You can still view its source code via the :::
function (i.e. stats:::t.ts
), or by using getAnywhere()
. getAnywhere()
is useful because you don't have to know which package the function came from.
> getAnywhere(t.ts)
A single object matching ‘t.ts’ was found
It was found in the following places
registered S3 method for t from namespace stats
namespace:stats
with value
function (x)
{
cl <- oldClass(x)
other <- !(cl %in% c("ts", "mts"))
class(x) <- if (any(other))
cl[other]
attr(x, "tsp") <- NULL
t(x)
}
<bytecode: 0x294e410>
<environment: namespace:stats>
The S4 system is a newer method dispatch system and is an alternative to the S3 system. Here is an example of an S4 function:
> library(Matrix)
Loading required package: lattice
> chol2inv
standardGeneric for "chol2inv" defined from package "base"
function (x, ...)
standardGeneric("chol2inv")
<bytecode: 0x000000000eafd790>
<environment: 0x000000000eb06f10>
Methods may be defined for arguments: x
Use showMethods("chol2inv") for currently available ones.
The output already offers a lot of information. standardGeneric
is an indicator of an S4 function. The method to see defined S4 methods is offered helpfully:
> showMethods(chol2inv)
Function: chol2inv (package base)
x="ANY"
x="CHMfactor"
x="denseMatrix"
x="diagonalMatrix"
x="dtrMatrix"
x="sparseMatrix"
getMethod
can be used to see the source code of one of the methods:
> getMethod("chol2inv", "diagonalMatrix")
Method Definition:
function (x, ...)
{
chk.s(...)
tcrossprod(solve(x))
}
<bytecode: 0x000000000ea2cc70>
<environment: namespace:Matrix>
Signatures:
x
target "diagonalMatrix"
defined "diagonalMatrix"
There are also methods with more complex signatures for each method, for example
require(raster)
showMethods(extract)
Function: extract (package raster)
x="Raster", y="data.frame"
x="Raster", y="Extent"
x="Raster", y="matrix"
x="Raster", y="SpatialLines"
x="Raster", y="SpatialPoints"
x="Raster", y="SpatialPolygons"
x="Raster", y="vector"
To see the source code for one of these methods the entire signature must be supplied, e.g.
getMethod("extract" , signature = c( x = "Raster" , y = "SpatialPolygons") )
It will not suffice to supply the partial signature
getMethod("extract",signature="SpatialPolygons")
#Error in getMethod("extract", signature = "SpatialPolygons") :
# No method found for function "extract" and signature SpatialPolygons
In the case of ts.union
, .cbindts
and .makeNamesTs
are unexported functions from the stats
namespace. You can view the source code of unexported functions by using the :::
operator or getAnywhere
.
> stats:::.makeNamesTs
function (...)
{
l <- as.list(substitute(list(...)))[-1L]
nm <- names(l)
fixup <- if (is.null(nm))
seq_along(l)
else nm == ""
dep <- sapply(l[fixup], function(x) deparse(x)[1L])
if (is.null(nm))
return(dep)
if (any(fixup))
nm[fixup] <- dep
nm
}
<bytecode: 0x38140d0>
<environment: namespace:stats>
Note that "compiled" does not refer to byte-compiled R code as created by the compiler package. The <bytecode: 0x294e410>
line in the above output indicates that the function is byte-compiled, and you can still view the source from the R command line.
Functions that call .C
, .Call
, .Fortran
, .External
, .Internal
, or .Primitive
are calling entry points in compiled code, so you will have to look at sources of the compiled code if you want to fully understand the function. This GitHub mirror of the R source code is a decent place to start. The function pryr::show_c_source
can be a useful tool as it will take you directly to a GitHub page for .Internal
and .Primitive
calls. Packages may use .C
, .Call
, .Fortran
, and .External
; but not .Internal
or .Primitive
, because these are used to call functions built into the R interpreter.
Calls to some of the above functions may use an object instead of a character string to reference the compiled function. In those cases, the object is of class "NativeSymbolInfo"
, "RegisteredNativeSymbol"
, or "NativeSymbol"
; and printing the object yields useful information. For example, optim
calls .External2(C_optimhess, res$par, fn1, gr1, con)
(note that's C_optimhess
, not "C_optimhess"
). optim
is in the stats package, so you can type stats:::C_optimhess
to see information about the compiled function being called.
If you want to view compiled code in a package, you will need to download/unpack the package source. The installed binaries are not sufficient. A package's source code is available from the same CRAN (or CRAN compatible) repository that the package was originally installed from. The download.packages()
function can get the package source for you.
download.packages(pkgs = "Matrix",
destdir = ".",
type = "source")
This will download the source version of the Matrix package and save the corresponding .tar.gz
file in the current directory. Source code for compiled functions can be found in the src
directory of the uncompressed and untared file. The uncompressing and untaring step can be done outside of R
, or from within R
using the untar()
function. It is possible to combine the download and expansion step into a single call (note that only one package at a time can be downloaded and unpacked in this way):
untar(download.packages(pkgs = "Matrix",
destdir = ".",
type = "source")[,2])
Alternatively, if the package development is hosted publicly (e.g. via GitHub, R-Forge, or RForge.net), you can probably browse the source code online.
Certain packages are considered "base" packages. These packages ship with R and their version is locked to the version of R. Examples include base
, compiler
, stats
, and utils
. As such, they are not available as separate downloadable packages on CRAN as described above. Rather, they are part of the R source tree in individual package directories under /src/library/
. How to access the R source is described in the next section.
If you want to view the code built-in to the R interpreter, you will need to download/unpack the R sources; or you can view the sources online via the R Subversion repository or Winston Chang's github mirror.
Uwe Ligges's R news article (PDF) (p. 43) is a good general reference of how to view the source code for .Internal
and .Primitive
functions. The basic steps are to first look for the function name in src/main/names.c
and then search for the "C-entry" name in the files in src/main/*
.
WebDav-SchmebDav.. ..make sure you create the url with the ID correctly. Don't send it like http://www.fluff.com/api/Fluff?id=MyID, send it like http://www.fluff.com/api/Fluff/MyID.
Eg.
PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
Host: www.fluff.com
Content-Length: 11
{"Data":"1"}
This was busting my balls for a small eternity, total embarrassment.
Something like this should work (it did for me). The reason for wanting to use -Filter
instead of -Include
is that include takes a huge performance hit compared to -Filter
.
Below just loops each file type and multiple servers/workstations specified in separate files.
##
## This script will pull from a list of workstations in a text file and search for the specified string
## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside
$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'
##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'
foreach ($server in $servers)
{
foreach ($filetype in $filetypes)
{
## below creates the search path. This could be further improved to exclude the windows directory
$serverString = "\\"+$server+"\c$\Program Files"
## Display the server being queried
write-host “Server:” $server "searching for " $filetype in $serverString
Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
#-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt
$os = gwmi win32_operatingsystem -computer $server
$sp = $os | % {$_.servicepackmajorversion}
$a = $os | % {$_.caption}
## Below will list again the server name as well as its OS and SP
## Because the script may not be monitored, this helps confirm the machine has been successfully scanned
write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp
}
}
#end script
PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.
[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}
Or shorter
[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
% {$_.Node.'#text'}
You're missing comma (,
) inbetween:
>>> ((1,2) (2,3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
Put comma:
>>> ((1,2), (2,3))
((1, 2), (2, 3))
I started to save this as a function, and call it as needed for whatever reactions require it:
function Remove(){
while(scene.children.length > 0){
scene.remove(scene.children[0]);
}
}
Now you can call the Remove(); function where appropriate.
To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:
Given the following function to test, located in module.a_function.to_test.py
:
from some_other.module import SomeOtherClass
def add_results():
my_object = SomeOtherClass('some_contextual_parameters')
result_a = my_object.method_a()
result_b = my_object.method_b()
return result_a + result_b
To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass
by using patch.object()
in combination with sys.modules
:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
mocked_other_class().method_a.return_value = 4
mocked_other_class().method_b.return_value = 7
self.assertEqual(add_results(), 11)
This works no matter the number of methods of SomeOtherClass
you need to patch, with independent results.
Also, using the same patching method, an actual instance of SomeOtherClass
can be returned if need be:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
other_class_instance = SomeOtherClass('some_controlled_parameters')
mocked_other_class.return_value = other_class_instance
...
Not going to be everyone's fix, but it was for me:
So, i ran across this exact issue. The problem I seemed to have was when my DataTable didnt have an ID column, but the target destination had one with a primary key.
When i adapted my DataTable to have an id, the copy worked perfectly.
In my scenario, the Id column isnt very important to have the primary key so i deleted this column from the target destination table and the SqlBulkCopy is working without issue.
Have you installed a different version JRE after , while using previous version of JRE in Eclipse .
if Not than :
if Yes than .
It sounds like the populate method is what your looking for. First make small change to your post schema:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Then make your model:
var Post = mongoose.model('Post', postSchema);
Then, when you make your query, you can populate references like this:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
You can do it with following code(track by),
<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>
You can use this:
comment = Comment.objects.filter(pk=comment_id)
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
I had the same error, in my case adding method_decorator helps:
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
method_decorator(csrf_protect)
def post(self, request):
...
Try this.
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
I got this error when I was messing around with string and dictionary.
dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required
So what you actually got to do to get dict from string is:
dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}
Or in matter of security we can use literal_eval
from ast import literal_eval
You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.
I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.
Alternative and fast solution : I faced the same error. I reopened the "wierd" csv file in GNUMERIC on my lubuntu machine and exported the file as csv file. This corrected the issue.
Short answer: use mongoose.Types.ObjectId.
Mongoose (but not mongo) can accept object Ids as strings and "cast" them properly for you, so just use:
MyClass.findById(req.params.id)
However, the caveat is if req.params.id
is not a valid format for a mongo ID string, that will throw an exception which you must catch.
So the main confusing thing to understand is that mongoose.SchemaTypes
has stuff you only use when defining mongoose schemas, and mongoose.Types
has the stuff you use when creating data objects you want to store in the database or query objects. So mongoose.Types.ObjectId("51bb793aca2ab77a3200000d")
works, will give you an object you can store in the database or use in queries, and will throw an exception if given an invalid ID string.
findOne
takes a query object and passes a single model instance to the callback. And findById
is literally a wrapper of findOne({_id: id})
(see source code here). Just find
takes a query object and passes an array of matching model instances to the callback.
Just go slow. It's confusing but I can guarantee you you are getting confused and not hitting bugs in mongoose at this point. It's a pretty mature library, but it takes some time to get the hang of it.
The other suspect thing I see in your snippet is not using new
when instantiating ChildClass
. Beyond that, you'll need to post your schema code in order for us to help you tract down any CastErrors that remain.
You can format your output in Java as described in below code snippet.
public class TestFormat {
public static void main(String[] args) {
long n = 461012;
System.out.format("%d%n", n); // --> "461012"
System.out.format("%08d%n", n); // --> "00461012"
System.out.format("%+8d%n", n); // --> " +461012"
System.out.format("%,8d%n", n); // --> " 461,012"
System.out.format("%+,8d%n%n", n); // --> "+461,012"
}
}
You can read more here.
Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.
Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal
' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
If Input < 0 Then Input = 0
if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.
End Function
Using ng-class inside ng-repeat
<table>
<tbody>
<tr ng-repeat="task in todos"
ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
<td>{{$index + 1}}</td>
<td>{{task.name}}</td>
<td>{{task.date|date:'yyyy-MM-dd'}}</td>
<td>{{task.status}}</td>
</tr>
</tbody>
</table>
For each status in task.status a different class is used for the row.
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
This line
except Vehicle.vehicledevice.device.DoesNotExist
means look for device instance for DoesNotExist exception, but there's none, because it's on class level, you want something like
except Device.DoesNotExist
The return value def __unicode __ should be similar to the return value of the related models (tables) for correct viewing of "some_field" in django admin panel. You can also use:
def __str__(self):
return self.some_field
You can use JsonResponse with values. Simple example:
from django.http import JsonResponse
def some_view(request):
data = list(SomeModel.objects.values()) # wrap in list(), because QuerySet is not JSON serializable
return JsonResponse(data, safe=False) # or JsonResponse({'data': data})
Or another approach with Django's built-in serializers:
from django.core import serializers
from django.http import HttpResponse
def some_view(request):
qs = SomeModel.objects.all()
qs_json = serializers.serialize('json', qs)
return HttpResponse(qs_json, content_type='application/json')
In this case result is slightly different (without indent by default):
[
{
"model": "some_app.some_model",
"pk": 1,
"fields": {
"name": "Elon",
"age": 48,
...
}
},
...
]
I have to say, it is good practice to use something like marshmallow to serialize queryset.
...and a few notes for better performance:
objects.values()
to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields
to serializers.serialize
);Some general notes.
$obj | Select-Object
? $obj | Select-Object -Property *
The latter will show all non-intrinsic, non-compiler-generated properties. The former does not appear to (always) show all Property types (in my tests, it does appear to show the CodeProperty
MemberType
consistently though -- no guarantees here).
Get-Member
does not get static members by default. You also cannot (directly) get them along with the non-static members. That is, using the switch causes only static members to be returned:
PS Y:\Power> $obj | Get-Member -Static
TypeName: System.IsFire.TurnUpProtocol
Name MemberType Definition
---- ---------- ----------
Equals Method static bool Equals(System.Object objA, System.Object objB)
...
Use the -Force
.
The
Get-Member
command uses the Force parameter to add the intrinsic members and compiler-generated members of the objects to the display.Get-Member
gets these members, but it hides them by default.
PS Y:\Power> $obj | Get-Member -Static
TypeName: System.IsFire.TurnUpProtocol
Name MemberType Definition
---- ---------- ----------
...
pstypenames CodeProperty System.Collections.ObjectModel.Collection...
psadapted MemberSet psadapted {AccessRightType, AccessRuleType,...
...
ConvertTo-Json
for depth and readable "serialization"I do not necessary recommend saving objects using JSON (use Export-Clixml
instead).
However, you can get a more or less readable output from ConvertTo-Json
, which also allows you to specify depth.
Note that not specifying Depth
implies -Depth 2
PS Y:\Power> ConvertTo-Json $obj -Depth 1
{
"AllowSystemOverload": true,
"AllowLifeToGetInTheWay": false,
"CantAnyMore": true,
"LastResortOnly": true,
...
And if you aren't planning to read it you can -Compress
it (i.e. strip whitespace)
PS Y:\Power> ConvertTo-Json $obj -Depth 420 -Compress
-InputObject
if you can (and are willing)99.9% of the time when using PowerShell: either the performance won't matter, or you don't care about the performance. However, it should be noted that avoiding the pipe when you don't need it can save some overhead and add some speed (piping, in general, is not super-efficient).
That is, if you all you have is a single $obj
handy for printing (and aren't too lazy like me sometimes to type out -InputObject
):
# select is aliased (hardcoded) to Select-Object
PS Y:\Power> select -Property * -InputObject $obj
# gm is aliased (hardcoded) to Get-Member
PS Y:\Power> gm -Force -InputObject $obj
Caveat for Get-Member -InputObject
:
If $obj is a collection (e.g. System.Object[]
), You end up getting information about the collection object itself:
PS Y:\Power> gm -InputObject $obj,$obj2
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
...
If you want to Get-Member
for each TypeName
in the collection (N.B. for each TypeName
, not for each object--a collection of N objects with all the same TypeName
will only print 1 table for that TypeName
, not N tables for each object)......just stick with piping it in directly.
You can do comparison with this down here.
latest('created')
is same as order_by('-created').first()
Please correct me if I am wrong
just add /FORCE as linker flag and you're all set.
for instance, if you're working on CMakeLists.txt. Then add following line:
SET(CMAKE_EXE_LINKER_FLAGS "/FORCE")
Click "view details" to find the inner exception.
This is not a compiler error: the error is coming from the linker. After compilation, the linker will merge the object files resulting from the compilation of each of your translation units (.cpp
files).
The linker finds out that you have the same symbol defined multiple times in different translation units, and complains about it (it is a violation of the One Definition Rule).
The reason is most certainly that main.cpp
includes client.cpp
, and both these files are individually processed by the compiler to produce two separate object files. Therefore, all the symbols defined in the client.cpp
translation unit will be defined also in the main.cpp
translation unit. This is one of the reasons why you do not usually #include
.cpp
files.
Put the definition of your class in a separate client.hpp
file which does not contain also the definitions of the member functions of that class; then, let client.cpp
and main.cpp
include that file (I mean #include
). Finally, leave in client.cpp
the definitions of your class's member functions.
client.h
#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif
class SocketClient // Or whatever the name is...
{
// ...
bool read(int, char*); // Or whatever the name is...
// ...
};
#endif
client.cpp
#include "Client.h"
// ...
bool SocketClient::read(int, char*)
{
// Implementation goes here...
}
// ... (add the definitions for all other member functions)
main.h
#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
// ^^ Notice this!
main.cpp
#include "main.h"
How about:
<table>
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
</table>
This method is listed in the docs: https://docs.angularjs.org/api/ng/directive/ngRepeat
JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"
System.out.println("id : "+node.findValues("id").get(0).asText());
this also done the trick.
I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency.
The conversion was probably not successful. The only thing that was successful was the running of VCUpgrade. The actual conversion itself failed but you don't know until you experience the errors you are seeing. For some of the details, see Visual Studio on the Crypto++ wiki.
Any ideas how to fix this?
To resolve your issues, you should download vs2010.zip
if you want static C/C++ runtime linking (/MT
or /MTd
), or vs2010-dynamic.zip
if you want dynamic C/C++ runtime linking (/MT
or /MTd
). Both fix the latent, silent failures produced by VCUpgrade.
vs2010.zip
, vs2010-dynamic.zip
and vs2005-dynamic.zip
are built from the latest GitHub sources. As of this writing (JUN 1 2016), that's effectively pre-Crypto++ 5.6.4. If you are using the ZIP files with a down level Crypto++, like 5.6.2 or 5.6.3, then you will run into minor problems.
There are two minor problems I am aware. First is a rename of bench.cpp
to bench1.cpp
. Its error is either:
C1083: Cannot open source file: 'bench1.cpp': No such file or directory
LNK2001: unresolved external symbol "void __cdecl OutputResultOperations(char const *,char const *,bool,unsigned long,double)" (?OutputResultOperations@@YAXPBD0_NKN@Z)
The fix is to either (1) open cryptest.vcxproj
in notepad, find bench1.cpp
, and then rename it to bench.cpp
. Or (2) rename bench.cpp
to bench1.cpp
on the filesystem. Please don't delete this file.
The second problem is a little trickier because its a moving target. Down level releases, like 5.6.2 or 5.6.3, are missing the latest classes available in GitHub. The missing class files include HKDF (5.6.3), RDRAND (5.6.3), RDSEED (5.6.3), ChaCha (5.6.4), BLAKE2 (5.6.4), Poly1305 (5.6.4), etc.
The fix is to remove the missing source files from the Visual Studio project files since they don't exist for the down level releases.
Another option is to add the missing class files from the latest sources, but there could be complications. For example, many of the sources subtly depend upon the latest config.h
, cpu.h
and cpu.cpp
. The "subtlety" is you won't realize you are getting an under-performing class.
An example of under-performing class is BLAKE2. config.h
adds compile time ARM-32 and ARM-64 detection. cpu.h
and cpu.cpp
adds runtime ARM instruction detection, which depends upon compile time detection. If you add BLAKE2 without the other files, then none of the detection occurs and you get a straight C/C++ implementation. You probably won't realize you are missing the NEON opportunity, which runs around 9 to 12 cycles-per-byte versus 40 cycles-per-byte or so for vanilla C/C++.
Try this request:
Query
SELECT name
FROM sys.procedures
WHERE Object_definition(object_id) LIKE '%strHell%'
java.io.NotSerializableException
can occur when you serialize an inner class instance because:
serializing such an inner class instance will result in serialization of its associated outer class instance as well
Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged
Normally it happens when the target is null. So better check the invoke target first then do the linq query.
@user1417684 and @chris-foster are right!
excerpt from working code (without error handling):
var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel = mongoose.model('items', ItemSchema);
var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {
var new_item = new ItemModel(new_item);
new_item.subitem = new_sub_item._id;
new_item.save(function (error, new_item) {
// so this is a valid way to populate via the Model
// as documented in comments above (here @stack overflow):
ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
callback(new_item.toObject());
});
// or populate directly on the result object
new_item.populate('subitem', function(error, new_item) {
callback(new_item.toObject());
});
});
});
Your CAST() looks correct.
Your CONVERT() is not correct. You are quoting the column as a string. You will want something like
CONVERT(INT, A.my_NvarcharColumn)
** notice without the quotes **
The only other reason why this could fail is if you have a non-numeric character in the field value or if it's out of range.
You can try something like the following to verify it's numeric and return a NULL if it's not:
SELECT
CASE
WHEN ISNUMERIC(A.my_NvarcharColumn) = 1 THEN CONVERT(INT, A.my_NvarcharColumn)
ELSE NULL
END AS my_NvarcharColumn
Setting the spring.jackson.default-property-inclusion=non_null
option is the simplest solution and it works well.
However, be careful if you implement WebMvcConfigurer somewhere in your code, then the property solution will not work and you will have to setup NON_NULL serialization in the code as the following:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
// some of your config here...
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
converters.add(jsonConverter);
}
}
If you want to set the same value on a collection of rows, you can use the update() method combined with any query term to update all rows in one query:
some_list = ModelClass.objects.filter(some condition).values('id')
ModelClass.objects.filter(pk__in=some_list).update(foo=bar)
If you want to update a collection of rows with different values depending on some condition, you can in best case batch the updates according to values. Let's say you have 1000 rows where you want to set a column to one of X values, then you could prepare the batches beforehand and then only run X update-queries (each essentially having the form of the first example above) + the initial SELECT-query.
If every row requires a unique value there is no way to avoid one query per update. Perhaps look into other architectures like CQRS/Event sourcing if you need performance in this latter case.
It means that the number of values specified in your VALUES
clause on the INSERT
statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.
Another one, since you are using ADO.Net
, always parameterized your query to avoid SQL Injection
. What you are doing right now is you are defeating the use of sqlCommand
.
ex
Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= " colBranch, colCourse, coldblFee) "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"
Using conn as New SqlConnection("connectionStringHere")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@colName", strName)
.Parameters.AddWithValue("@colID", strId)
.Parameters.AddWithValue("@colPhone", strPhone)
.Parameters.AddWithValue("@colBranch", strBranch)
.Parameters.AddWithValue("@colCourse", strCourse)
.Parameters.AddWithValue("@coldblFee", dblFee)
End With
Try
conn.open()
comm.ExecuteNonQuery()
Catch(ex as SqlException)
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
End USing
PS: Please change the column names specified in the query to the original column found in your table.
First make sure you have SessionMiddleware
and AuthenticationMiddleware
middlewares added to your MIDDLEWARE_CLASSES
setting.
The current user
is in request
object, you can get it by:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
will give you a User
object representing the currently logged-in user. If a user isn't currently logged in, request.user
will be set to an instance of AnonymousUser
. You can tell them apart with the field is_authenticated
, like so:
if request.user.is_authenticated:
# Do something for authenticated users.
else:
# Do something for anonymous users.
With the advent of Django 1.7, there is now a new update_or_create
QuerySet method, which should do exactly what you want. Just be careful of potential race conditions if uniqueness is not enforced at the database level.
Example from the documentation:
obj, created = Person.objects.update_or_create(
first_name='John', last_name='Lennon',
defaults={'first_name': 'Bob'},
)
The
update_or_create
method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in thedefaults
dictionary.
Pre-Django 1.7:
Change the model field values as appropriate, then call .save()
to persist the changes:
try:
obj = Model.objects.get(field=value)
obj.field = new_value
obj.save()
except Model.DoesNotExist:
obj = Model.objects.create(field=new_value)
# do something else with obj if need be
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
the boolean value of an empty QuerySet is also False, so you could also just do...
...
if not user_object:
do insert or whatever etc.
I was able to resolve this by writing the code below. I used executeUpdate instead of .delete()
def publicSupport = caseObj?.client?.publicSupport
if(publicSupport)
PublicSupport.executeUpdate("delete PublicSupport c where c.id = :publicSupportId", [publicSupportId:publicSupport.id])
//publicSupport.delete()
If you are using oc4j to deploy the ear.
Make sure you set in the project the correct path for deploy.home=
You can fiind deploy.home in common.properties file
The oc4j needs to reload the new created class in the ear so that the server class and the client class have the same serialVersionUID
This is usually the problem with web.xml descriptor file. May be you have mixed up the annotations and web.xml servlet description definitions. Please check the console for more information.
The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..
from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
email='[email protected]',
password='glass onion')
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
All we need:
console.clear();_x000D_
function App(){ // name of my constant is App_x000D_
return {_x000D_
a: {_x000D_
b: {_x000D_
c: ()=>{ // very important here, use arrow function _x000D_
console.log(this.constructor.name)_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
const obj = new App(); // usage_x000D_
_x000D_
obj.a.b.c(); // App_x000D_
_x000D_
// usage with react props etc, _x000D_
// For instance, we want to pass this callback to some component_x000D_
_x000D_
const myComponent = {};_x000D_
myComponent.customProps = obj.a.b.c;_x000D_
myComponent.customProps(); // App
_x000D_
In the Project’s Settings, add /FORCE:MULTIPLE
to the Linker’s Command Line options.
From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."
Less than or equal:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than. You can find them all in the documentation.
I had an error where my project was compiled as x64 project. and I've used a Library that was compiled as x86.
I've recompiled the library as x64 and it solved it.
A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.
It works removing .all()
:
Reserved.objects.filter(client=client_id).order_by('-check_in')
The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on
SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner = <<owner of the table>>
AND table_name = <<name of the table>>
Once you know what column(s) are affected, you can compare the data you're trying to INSERT
or UPDATE
against the data already in the table to determine why the constraint is being violated.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
your str_carSql should be exactly like this:
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"
Good Luck
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
public static string JSONSerialize<T>(T obj)
{
string retVal = String.Empty;
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(ms, obj);
var byteArray = ms.ToArray();
retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
}
return retVal;
}
A Java String
is an Object
. (String
extends Object
.)
So you can get an Object
reference via assignment/initialisation:
String a = "abc";
Object b = a;
You can use a similar construct by using the sys.columns
table io sys.objects
.
IF NOT EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = OBJECT_ID(N'[dbo].[Person]')
AND name = 'ColumnName'
)
The solution involved putting the gtest source directory as a subdirectory of your project. I've included the working CMakeLists.txt below if it is helpful to anyone.
cmake_minimum_required(VERSION 2.6)
project(basic_test)
################################
# GTest
################################
ADD_SUBDIRECTORY (gtest-1.6.0)
enable_testing()
include_directories(${gtest_SOURCE_DIR}/include ${gtest_SOURCE_DIR})
################################
# Unit Tests
################################
# Add test cpp file
add_executable( runUnitTests testgtest.cpp )
# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests gtest gtest_main)
add_test( runUnitTests runUnitTests )
@Naftule - with "defiant.js", it is possible to query a JSON structure with XPath expressions. Check out this evaluator to get an idea of how it works:
http://www.defiantjs.com/#xpath_evaluator
Unlike JSONPath, "defiant.js" delivers the full-scale support of the query syntax - of XPath on JSON structures.
The source code of defiant.js can be found here:
https://github.com/hbi99/defiant.js
From Django docs :
To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.
filter()
are applied simultaneously.
That means that doing :objs = Mymodel.objects.filter(a=True, b=False)
will return a queryset with raws from model Mymodel
where a=True
AND b=False
.
filter()
, in some case, will provide the same result. Doing :objs = Mymodel.objects.filter(a=True).filter(b=False)
will return a queryset with raws from model Mymodel
where a=True
AND b=False
too. Since you obtain "first" a queryset with records which have a=True
and then it's restricted to those who have b=False
at the same time.
filter()
comes when there are multi-valued relations
, which means you are going through other models (such as the example given in the docs, between Blog and Entry models). It is said that in that case (...) they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.
Which means that it applies the successives filter()
on the target model directly, not on previous filter()
If I take the example from the docs :
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
remember that it's the model Blog
that is filtered, not the Entry
. So it will treat the 2 filter()
independently.
It will, for instance, return a queryset with Blogs, that have entries that contain 'Lennon' (even if they are not from 2008) and entries that are from 2008 (even if their headline does not contain 'Lennon')
THIS ANSWER goes even further in the explanation. And the original question is similar.
The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:
let UserSchema = new Schema({
username: {
type: String
},
events: {
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}
})
Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.
Well in general:
List<String> names = new ArrayList<String>();
names.add("john");
names.add("ann");
String[] namesArr = new String[names.size()];
for (int i = 0; i < names.size(); i++) {
namesArr[i] = names.get(i);
}
Or better yet, using built in:
List<String> names = new ArrayList<String>();
String[] namesArr = names.toArray(new String[names.size()]);
DECLARE
CTABLE USER_OBJECTS.OBJECT_NAME%TYPE;
CCOLUMN ALL_TAB_COLS.COLUMN_NAME%TYPE;
V_ALL_COLS VARCHAR2(5000);
CURSOR CURSOR_TABLE
IS
SELECT OBJECT_NAME
FROM USER_OBJECTS
WHERE OBJECT_TYPE='TABLE'
AND OBJECT_NAME LIKE 'STG%';
CURSOR CURSOR_COLUMNS (V_TABLE_NAME IN VARCHAR2)
IS
SELECT COLUMN_NAME
FROM ALL_TAB_COLS
WHERE TABLE_NAME = V_TABLE_NAME;
BEGIN
OPEN CURSOR_TABLE;
LOOP
FETCH CURSOR_TABLE INTO CTABLE;
OPEN CURSOR_COLUMNS (CTABLE);
V_ALL_COLS := NULL;
LOOP
FETCH CURSOR_COLUMNS INTO CCOLUMN;
V_ALL_COLS := V_ALL_COLS || CCOLUMN;
IF CURSOR_COLUMNS%FOUND THEN
V_ALL_COLS := V_ALL_COLS || ', ';
ELSE
EXIT;
END IF;
END LOOP;
close CURSOR_COLUMNS ;
DBMS_OUTPUT.PUT_LINE(V_ALL_COLS);
EXIT WHEN CURSOR_TABLE%NOTFOUND;
END LOOP;`enter code here`
CLOSE CURSOR_TABLE;
END;
I have added Close of second cursor. It working and getting output as well...
If the source code will not have issues with LF to be replaced by CRLF, No debugging is required by following simple codes outputs.
--http://stackoverflow.com/questions/7850477/how-to-print-varcharmax-using-print-statement
--Bill Bai
SET @SQL=replace(@SQL,char(10),char(13)+char(10))
SET @SQL=replace(@SQL,char(13)+char(13)+char(10),char(13)+char(10) )
DECLARE @Position int
WHILE Len(@SQL)>0
BEGIN
SET @Position=charindex(char(10),@SQL)
PRINT left(@SQL,@Position-2)
SET @SQL=substring(@SQL,@Position+1,len(@SQL))
end;
Last chance (if other ways don't work): define _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH macro in all projects. It will disable "#pragma detect_mismatch" feature which is used in CRT headers.
Use SemaphoreSlim.WaitAsync
method.
await mySemaphoreSlim.WaitAsync();
try {
await Stuff();
} finally {
mySemaphoreSlim.Release();
}
Daniel answer is right on the spot. If you want to query more than one field do this:
Employee.objects.values_list('eng_name','rank')
This will return list of tuples. You cannot use named=Ture when querying more than one field.
Moreover if you know that only one field exists with that info and you know the pk id then do this:
Employee.objects.values_list('eng_name','rank').get(pk=1)
My problem was int Main() instead of int main()
good luck
You can create a util method that converts any collection to a java list
public static List<?> convertObjectToList(Object obj) {
List<?> list = new ArrayList<>();
if (obj.getClass().isArray()) {
list = Arrays.asList((Object[])obj);
} else if (obj instanceof Collection) {
list = new ArrayList<>((Collection<?>)obj);
}
return list;
}
you can also mix with this validation below:
public static boolean isCollection(Object obj) {
return obj.getClass().isArray() || obj instanceof Collection;
}
Alternatively, as long as permissions are not given, the good old <noscript>
tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.
As the others mentioned you can change the SubSystem to Console and the error will go away.
Or if you want to keep the Windows subsystem you can just hint at what your entry point is, because you haven't defined ___tmainCRTStartup
. You can do this by adding the following to Properties -> Linker -> Command line:
/ENTRY:"mainCRTStartup"
This way you get rid of the console window.
At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:
"_OBJC_CLASS_$_RadioKit", referenced from:
objc-class-ref in RadioPlayerViewController.o
If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that
Radiokit *rk;
has "Radiokit" in green when the actual decalaration should be:
RadioKit *rk;
This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.
As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10]
as slicing will return the first 10 elements of the list, not the last 10...
To get the last 10 you should do [-10:]
instead (see here). This will help you avoid using order_by('-id')
with the -
to reverse the elements.
Just adding this for multiple filters attaching to Q
object, if someone might be looking to it.
If a Q
object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.
an example would be
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')
Here the OR condition and a filter with category of income is taken into account
However, will it automatically remove these committed files from the repository?
No.
The 'best' recipe to do this is using git filter-branch
as written about here:
The man page for git-filter-branch contains comprehensive examples.
Note You'll be re-writing history. If you had published any revisions containing the accidentally added files, this could create trouble for users of those public branches. Inform them, or perhaps think about how badly you need to remove the files.
Note In the presence of tags, always use the --tag-name-filter cat
option to git filter-branch
. It never hurts and will save you the head-ache when you realize later taht you needed it
Try this piece of code, rather than ObjectInputStream
.
BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
String cominginText = "";
try
{
cominginText = in.readLine ();
System.out.println (cominginText);
}
catch (IOException e)
{
//error ("System: " + "Connection to server lost!");
System.exit (1);
break;
}
}
After running eclipse:clean eclipse:eclipse its worked for me.
This can happen if you execute a query while iterating over the results from another query. It is not clear from your example where this happens because the example is not complete.
One thing that can cause this is lazy loading triggered when iterating over the results of some query.
This can be easily solved by allowing MARS in your connection string. Add MultipleActiveResultSets=true
to the provider part of your connection string (where Data Source, Initial Catalog, etc. are specified).
The correct answer is usually to use require, but in a few cases it's not possible.
The following code will do the trick, but use it with care:
var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext(__dirname+"/models/car.js");
I liked the answer from kays1 but I couldn't implement it. So I built my own version using his concept.
public class JsonListHelper{
public static final <T> List<T> getList(String json) throws Exception {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Type typeOfList = new TypeToken<List<T>>(){}.getType();
return gson.fromJson(json, typeOfList);
}
}
Usage:
List<MyClass> MyList= JsonListHelper.getList(jsonArrayString);
I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)
To resolve this during development, I used
request.session.flush()
Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:
Item.objects.values("contest").annotate(Count("id"))
I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.
IWebElement element = _browserInstance.Driver.FindElement(By.XPath("//Select"));
IList<IWebElement> AllDropDownList = element.FindElements(By.XPath("//option"));
int DpListCount = AllDropDownList.Count;
for (int i = 0; i < DpListCount; i++)
{
if (AllDropDownList[i].Text == "nnnnnnnnnnn")
{
AllDropDownList[i].Click();
_browserInstance.ScreenCapture("nnnnnnnnnnnnnnnnnnnnnn");
}
}
If you plan to get first element often - you can extend QuerySet in this direction:
class FirstQuerySet(models.query.QuerySet):
def first(self):
return self[0]
class ManagerWithFirstQuery(models.Manager):
def get_query_set(self):
return FirstQuerySet(self.model)
Define model like this:
class MyModel(models.Model):
objects = ManagerWithFirstQuery()
And use it like this:
first_object = MyModel.objects.filter(x=100).first()
I've been verifying calls in the same manner - I believe it is the right way to do it.
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
), Times.Once());
If your lambda expression becomes unwieldy, you could create a function that takes MyObject
as input and outputs true
/false
...
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => MyObjectFunc(mo))
), Times.Once());
private bool MyObjectFunc(MyObject myObject)
{
return myObject.Id == 5 && myObject.description == "test";
}
Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.
EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).
foreach (var item in myList)
mockRepository.Verify(mr => mr.Update(
It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
Times.Once());
Same approach for setup...
foreach (var item in myList) {
var stuff = ... // some result specific to the item
this.mockRepository
.Setup(mr => mr.GetStuff(item.itemId))
.Returns(stuff);
}
So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.
this.mockRepository
.Setup(mr => mr.GetStuff(It.IsAny<int>()))
.Returns((int id) => SomeFunctionThatReturnsStuff(id));
One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.
There's a clone snippet here, which you can add to your model which does this:
def clone(self):
new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != old._meta.pk]);
return self.__class__.objects.create(**new_kwargs)
Using shell,
1) For Deleting the table:
python manage.py dbshell
>> DROP TABLE {app_name}_{model_name}
2) For removing all data from table:
python manage.py shell
>> from {app_name}.models import {model_name}
>> {model_name}.objects.all().delete()
The following works for me:
class Fruits: pass
banana = Fruits()
banana.color = 'yellow'
banana.value = 30
import pickle
filehandler = open("Fruits.obj","wb")
pickle.dump(banana,filehandler)
filehandler.close()
file = open("Fruits.obj",'rb')
object_file = pickle.load(file)
file.close()
print(object_file.color, object_file.value, sep=', ')
# yellow, 30
You could do this:
import itertools
ids = set(existing_answer.answer.id for existing_answer in existing_question_answers)
answers = itertools.ifilter(lambda x: x.id not in ids, answers)
Read when QuerySets are evaluated and note that it is not good to load the whole result into memory (e.g. via list()
).
Reference: itertools.ifilter
Update with regard to the comment:
There are various ways to do this. One (which is probably not the best one in terms of memory and time) is to do exactly the same :
answer_ids = set(answer.id for answer in answers)
existing_question_answers = filter(lambda x: x.answer.id not in answers_id, existing_question_answers)
If your application third party redirect internally, so it is better to mock HttpContext in below way :
HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("","","","",new StringWriter(CultureInfo.InvariantCulture));
System.Web.HttpContext.Current = new HttpContext(initWorkerRequest);
System.Web.HttpContext.Current.Request.Browser = new HttpBrowserCapabilities();
System.Web.HttpContext.Current.Request.Browser.Capabilities = new Dictionary<string, string> { { "requiresPostRedirectionHandling", "false" } };
I had the same problem. See if you are using hibernatesession.load()
. If so, try converting to hibernatesession.get()
. This solved my problem.
It looks like you were on the right track - get_FOO_display()
is most certainly what you want:
In templates, you don't include ()
in the name of a method. Do the following:
{{ person.get_gender_display }}
At times, if we forget the
return self.cleaned_data
in the clean function of django forms, we will not have any data though the form.is_valid()
will return True
.
In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404
importing by from django.shortcuts import get_object_or_404
.
Use example:
def myFunc(request, my_pk):
my_var = get_object_or_404(CLASS_NAME, pk=my_pk)
Do like this
List<Object[]> list = HQL.list(); // get your lsit here but in Object array
your query is : "SELECT houses.id, addresses.country, addresses.region,..."
for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
After spending hours, I found that I missed 's'
letter in table name
It was [Table("Employee")]
instead of [Table("Employees")]
Bro, I had the same problem. Thing is I built a query builder, quite an complex one that build his predicates dynamically pending on what parameters had been set and cached the queries. Anyways, before I built my query builder, I had a non object oriented procedural code build the same thing (except of course he didn't cache queries and use parameters) that worked flawless. Now when my builder tried to do the very same thing, my PostgreSQL threw this fucked up error that you received too. I examined my generated SQL code and found no errors. Strange indeed.
My search soon proved that it was one particular predicate in the WHERE clause that caused this error. Yet this predicate was built by code that looked like, well almost, exactly as how the procedural code looked like before this exception started to appear out of nowhere.
But I saw one thing I had done differently in my builder as opposed to what the procedural code did previously. It was the order of the predicates he put in the WHERE clause! So I started to move this predicate around and soon discovered that indeed the order of predicates had much to say. If I had this predicate all alone, my query worked (but returned an erroneous result-match of course), if I put him with just one or the other predicate it worked sometimes, didn't work other times. Moreover, mimicking the previous order of the procedural code didn't work either. What finally worked was to put this demonic predicate at the start of my WHERE clause, as the first predicate added! So again if I haven't made myself clear, the order my predicates where added to the WHERE method/clause was creating this exception.
as the exception says there is already another server running on the same port. you can either kill that service or change glassfish to run on another poet
For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:
<weblogic_jdk_home>\jre\lib\ext
Do you want [classname] to be 'one' and [objectname] to be 'A'?
If so, this is not possible. These names are only abstractions for the programmer, and aren't actually used in the binary code that is generated. You could give the class a static variable classname, which you set to 'one' and a normal variable objectname which you would assign either directly, through a method or the constructor. You can then query these methods for the class and object names.
If you are here because of the Liquibase error saying:
Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short
and you are using
not {
indexExists()
}
precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342
We can try to execute an above check using bare sqlCheck
(Postgres):
SELECT COUNT(i.relname)
FROM
pg_class t,
pg_class i,
pg_index ix
WHERE
t.oid = ix.indrelid
and i.oid = ix.indexrelid
and t.relkind = 'r'
and t.relname = 'tableName'
and i.relname = 'indexName';
where tableName
- is an index table name and indexName
- is an index name
You can declare the field as a first-class attribute of your form and just set choices dynamically:
class WaypointForm(forms.Form):
waypoints = forms.ChoiceField(choices=[])
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
self.fields['waypoints'].choices = waypoint_choices
You can also use a ModelChoiceField and set the queryset on init in a similar manner.
System.out.println
System
is a class in the java.lang
package.
out
is a static
data member of the System
class and references a variable of the PrintStream
class.
Use String.Equals Method
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.Equals(description, StringComparison.OrdinalIgnoreCase));
}
I use Django 2.2.16. And this is how I solve this problem:
from typing import Any
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.base import ModelBase
from django.db.models.manager import Manager
class SManager(Manager):
def get_if_exist(self, *args: Any, **kwargs: Any):
try:
return self.get(*args, **kwargs)
except ObjectDoesNotExist:
return None
class SModelBase(ModelBase):
def _prepare(cls):
manager = SManager()
manager.auto_created = True
cls.add_to_class("objects", manager)
super()._prepare()
class Meta:
abstract = True
class SModel(models.Model, metaclass=SModelBase):
managers = False
class Meta:
abstract = True
And after that, in every models, you just need to import in:
from custom.models import SModel
class SUser(SModel):
pass
And in views
, you can call like this:
SUser.objects.get_if_exist(id=1)
An update to i00g's and Thomas' answers, this time for VS2012 (some names have changed). After copying x86 settings over into an x64 target with the configuration manager, you'll have the problem for the same reason as was the case earlier (lib targets aren't correct in the x64 config). Open your .vcxproj (text editor) and replace MachineX86 with MachineX64 where appropriate. (I still haven't found where this is on the property sheets....) This only seems to be necessary with static libs.
it looks like datetime.now()
is being evaluated when the model is defined, and not each time you add a record.
Django has a feature to accomplish what you are trying to do already:
date = models.DateTimeField(auto_now_add=True, blank=True)
or
date = models.DateTimeField(default=datetime.now, blank=True)
The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now
without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now()
, then you are just evaluating the function and passing it the return value.
More information is available at Django's model field reference
It's a buzzword that refers to things like the normal Web architecture with e.g., Javascript - ASP.Net - Middleware - Database layer. Each of these things is a "tier".
document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();
It's throwing this error for me today because I have an app with a min sdk of 28 and am hitting play on an emulator with an SDK version of 23. Usually this is not possible (AS gray's out the play button), but today not so much.
You need to edit the Tomcat/conf/server.xml
and change the connector port. The connector setting should look something like this:
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" />
Just change the connector port from default 8080 to another valid port number.
In short just replace the content of config.inc.php from line 50-69 with...
$cfg['Servers'][$i]['pma__bookmark'] = 'pma__bookmark';
$cfg['Servers'][$i]['pma__relation'] = 'pma__relation';
$cfg['Servers'][$i]['pma__table_info'] = 'pma__table_info';
$cfg['Servers'][$i]['pma__table_coords'] = 'pma__table_coords';
$cfg['Servers'][$i]['pma__pdf_pages'] = 'pma__pdf_pages';
$cfg['Servers'][$i]['pma__column_info'] = 'pma__column_info';
$cfg['Servers'][$i]['pma__table_uiprefs'] = 'pma__history';
$cfg['Servers'][$i]['pma__table_uiprefs'] = 'pma__table_uiprefs';
$cfg['Servers'][$i]['pma__tracking'] = 'pma__tracking';
$cfg['Servers'][$i]['pma__userconfig'] = 'pma__userconfig';
$cfg['Servers'][$i]['pma__recent'] = 'pma__recent';
$cfg['Servers'][$i]['pma__users'] = 'pma__users';
$cfg['Servers'][$i]['pma__usergroups'] = 'pma__usergroups';
$cfg['Servers'][$i]['pma__navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['pma__savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['pma__central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['pma__designer_coords'] = 'pma__designer_coords';
$cfg['Servers'][$i]['pma__designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['pma__export_templates'] = 'pma__export_templates';
$cfg['Servers'][$i]['pma__favorite'] = 'pma__favorite';
If you want true random data, then unfortunately you have to wait for it. This includes the seed for a SecureRandom
PRNG. Uncommon Maths can't gather true random data any faster than SecureRandom
, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than /dev/random
where that's available.
If you want a PRNG, do something like this:
SecureRandom.getInstance("SHA1PRNG");
What strings are supported depends on the SecureRandom
SPI provider, but you can enumerate them using Security.getProviders()
and Provider.getService()
.
Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.
The exception is that if you don't call setSeed()
before getting data, then the PRNG will seed itself once the first time you call next()
or nextBytes()
. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.
For example:
hr {
border:none;
border-top:1px dotted #f00;
color:#fff;
background-color:#fff;
height:1px;
width:50%;
}
See also Styling <hr>
with CSS.
If you have lots of commits and you only want to squash the last X commits, find the commit ID of the commit from which you want to start squashing and do
git rebase -i <that_commit_id>
Then proceed as described in leopd's answer, changing all the pick
s to squash
es except the first one.
871adf OK, feature Z is fully implemented --- newer commit --+
0c3317 Whoops, not yet... |
87871a I'm ready! |
643d0e Code cleanup |-- Join these into one
afb581 Fix this and that |
4e9baa Cool implementation |
d94e78 Prepare the workbench for feature Z -------------------+
6394dc Feature Y --- older commit
You can either do this (write the number of commits):
git rebase --interactive HEAD~[7]
Or this (write the hash of the last commit you don't want to squash):
git rebase --interactive 6394dc
As @borayeris said,
yum install glibc.i686
But if you cannot find glibc.i686 or libstdc++ package, try -
sudo yum search glibc
sudo yum search libstd
and then,
sudo yum install {package}
The npm module anyid provides flexible API to generate various kinds of string ID / code.
const id = anyid().encode('Aa0').length(5).random().id();
No obsfuscator can protect your application, not even any one described here. See this link, it's an deobsfuscator which can deobsfuscate almost every obsfuscator out there.
https://github.com/0xd4d/de4dot
The best way which can help you (but remember that they are also not full prof) is to use mixed codes, code your important codes in unmanaged language and make a DLL like in C or C++ and then protect them either with Armageddon or Themida. Themida is not for every cracker, it's one of the best protector in the market, it can also protect your .NET software.
I always use the following code to make it work. There are some notes:
.background-gradient {_x000D_
background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -moz-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -webkit-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -webkit-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -o-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, -ms-linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
background: url('http://trungk18.github.io/img/trungk18.png') no-repeat, linear-gradient(135deg, #6ec575 0, #3b8686 100%);_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
}
_x000D_
<div class="background-gradient"></div>
_x000D_
.background-gradient {_x000D_
background: -moz-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
background: -webkit-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
background: -webkit-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
background: -o-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
background: -ms-linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
background: linear-gradient(135deg, #6ec575 0, #3b8686 100%), url('http://trungk18.github.io/img/trungk18.png') no-repeat;_x000D_
width: 500px;_x000D_
height: 500px;_x000D_
}
_x000D_
<div class="background-gradient"></div>
_x000D_
This technique is just the same as we have multiple background images as describe here
DateTime
is a non-nullable value type
DateTime? newdate = null;
You can use a Nullable<DateTime>
Or alternatively, you could use this:
WHERE CHARINDEX(N'Apples', someColumn) = 0
Not sure which one performs better - you gotta test it! :-)
Marc
UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.
I recommend reading this post.
When using AnyCPU, the semantics are the following:
- If the process runs on a 32-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.
- If the process runs on a 64-bit Windows system, it runs as a 32-bit process. CIL is compiled to x86 machine code.
- If the process runs on an ARM Windows system, it runs as a 32-bit process. CIL is compiled to ARM machine code.
I see in the documentation page an example like this:
<source src="foo.ogg" type="video/ogg; codecs="dirac, speex"">
Maybe you should enclose the codec
information with "
entities instead of actual quotes and the type
attribute with quotes instead of apostrophes.
You can also try removing the codec info altogether.
Another way to check if FB has initialized is by using the following code:
ns.FBInitialized = function () {
return typeof (FB) != 'undefined' && window.fbAsyncInit.hasRun;
};
Thus in your page ready event you could check ns.FBInitialized and defer the event to later phase by using setTimeOut.
As Chris suggests, you can do it like this:
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Or like this:
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
and if you really want to create a new XmlDocument
then do this
XmlDocument newxmlDoc= myxml
I managed to load an application.properties file in external path while using -jar option.
The key was PropertiesLauncher.
To use PropertiesLauncher, pom.xml file must be changed like this:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <!-- added -->
<layout>ZIP</layout> <!-- to use PropertiesLaunchar -->
</configuration>
</plugin>
</plugins>
</build>
For this, I referenced the following StackOverflow question: spring boot properties launcher unable to use . BTW, In Spring Boot Maven Plugin document(http://docs.spring.io/spring-boot/docs/1.1.7.RELEASE/maven-plugin/repackage-mojo.html), there is no mention that specifying ZIP triggers that PropertiesLauncher is used. (Perhaps in another document?)
After the jar file had been built, I could see that the PropertiesLauncher is used by inspecting Main-Class property in META-INF/MENIFEST.MF in the jar.
Now, I can run the jar as follows(in Windows):
java -Dloader.path=file:///C:/My/External/Dir,MyApp-0.0.1-SNAPSHOT.jar -jar MyApp-0.0.1-SNAPSHOT.jar
Note that the application jar file is included in loader.path.
Now an application.properties file in C:\My\External\Dir\config is loaded.
As a bonus, any file (for example, static html file) in that directory can also be accessed by the jar since it's in the loader path.
As for the non-jar (expanded) version mentioned in UPDATE 2, maybe there was a classpath order problem.
See http://www.basarat.com/2013/04/typescript-static-constructors-for.html
This is a way to 'fake' a static constructor. It's not without its dangers - see the referenced codeplex item.
class Test {
static foo = "orig";
// Non void static function
static stat() {
console.log("Do any static construction here");
foo = "static initialized";
// Required to make function non void
return null;
}
// Static variable assignment
static statrun = Test.stat();
}
// Static construction will have been done:
console.log(Test.foo);
I think people have put too much weight into the application logic versus protocol matter. The important thing is that the response should make sense. What if you have an API that serves a dynamic resource and a request is made for X which is derived from template Y with data Z and either Y or Z isn't currently available? Is that a business logic error or a technical error? The correct answer is, "who cares?"
Your API and your responses need to be intelligible and consistent. It should conform to some kind of spec, and that spec should define what a valid response is. Something that conforms to a valid response should yield a 200 code. Something that does not conform to a valid response should yield a 4xx or 5xx code indicative of why a valid response couldn't be generated.
If your spec's definition of a valid response permits { "error": "invalid ID" }
, then it's a successful response. If your spec doesn't make that accommodation, it would be a poor decision to return that response with a 200 code.
I'd draw an analogy to calling a function parseFoo
. What happens when you call parseFoo("invalid data")
? Does it return an error result (maybe null)? Or does it throw an exception? Many will take a near-religious position on whether one approach or the other is correct, but ultimately it's up to the API specification.
"The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request"
Obviously there's a difference of opinion with regards to whether "successfully returning an error" constitutes an HTTP success or error. I see different people interpreting the same specs different ways. So pick a side, sure, but also accept that either way the whole world isn't going to agree with you. Me? I find myself somewhere in the middle, but I'll offer some commonsense considerations.
500 Internal Server Error
. This seems to be OP's situation. The application should not return a 200
for unexpected errors, but also see point 3.In OP's situation, it sounds like you have a de-facto standard that unhandled exceptions yield a 200 with a distinguishable response body. It's not ideal, but if it's not breaking things and actively causing problems, you probably have bigger, more important problems to solve.
I just tested the code at the bottom and it prints 16384
twice (I'm on Excel 2010) and the first row gets selected. Your problem seems to be somewhere else.
Have you tried to get rid of the selects:
Sheets("BOM").Rows(copyFromRow).Copy
With Sheets("Proposal")
.Paste Destination:=.Rows(copyToRow)
copyToRow = copyToRow + 1
Application.CutCopyMode = False
.Rows(copyToRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Test code to get convinced that the problem does not seem to be what you think it is.
Sub test()
Dim r
Dim i As Long
i = 1
r = Rows(i & ":" & i)
Debug.Print UBound(r, 2)
r = Rows(i)
Debug.Print UBound(r, 2)
Rows(i).Select
End Sub
HTTP and HTTPS:
const getScript = (url) => {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(data);
});
}).on("error", (err) => {
reject(err);
});
});
};
(async (url) => {
console.log(await getScript(url));
})('https://sidanmor.com/');
Maybe because other languages do this as well, so it is generally-accepted behavior. (For good reasons, as shown in the other answers)
Use Rational class from JScience library. It's the best thing for fractional arithmetic I seen in Java.
You can also ask the user for the credentials and set them dynamically once the server starts (very effective when you need to publish the solution on a customer environment):
@EnableWebSecurity
public class SecurityConfig {
private static final Logger log = LogManager.getLogger();
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
log.info("Setting in-memory security using the user input...");
Scanner scanner = new Scanner(System.in);
String inputUser = null;
String inputPassword = null;
System.out.println("\nPlease set the admin credentials for this web application");
while (true) {
System.out.print("user: ");
inputUser = scanner.nextLine();
System.out.print("password: ");
inputPassword = scanner.nextLine();
System.out.print("confirm password: ");
String inputPasswordConfirm = scanner.nextLine();
if (inputUser.isEmpty()) {
System.out.println("Error: user must be set - please try again");
} else if (inputPassword.isEmpty()) {
System.out.println("Error: password must be set - please try again");
} else if (!inputPassword.equals(inputPasswordConfirm)) {
System.out.println("Error: password and password confirm do not match - please try again");
} else {
log.info("Setting the in-memory security using the provided credentials...");
break;
}
System.out.println("");
}
scanner.close();
if (inputUser != null && inputPassword != null) {
auth.inMemoryAuthentication()
.withUser(inputUser)
.password(inputPassword)
.roles("USER");
}
}
}
(May 2018) An update - this will work on spring boot 2.x:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger log = LogManager.getLogger();
@Override
protected void configure(HttpSecurity http) throws Exception {
// Note:
// Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
// Note that the CSRf token is disabled for all requests
log.info("Disabling CSRF, enabling basic authentication...");
http
.authorizeRequests()
.antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
.and()
.httpBasic();
http.csrf().disable();
}
@Bean
public UserDetailsService userDetailsService() {
log.info("Setting in-memory security using the user input...");
String username = null;
String password = null;
System.out.println("\nPlease set the admin credentials for this web application (will be required when browsing to the web application)");
Console console = System.console();
// Read the credentials from the user console:
// Note:
// Console supports password masking, but is not supported in IDEs such as eclipse;
// thus if in IDE (where console == null) use scanner instead:
if (console == null) {
// Use scanner:
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Username: ");
username = scanner.nextLine();
System.out.print("Password: ");
password = scanner.nextLine();
System.out.print("Confirm Password: ");
String inputPasswordConfirm = scanner.nextLine();
if (username.isEmpty()) {
System.out.println("Error: user must be set - please try again");
} else if (password.isEmpty()) {
System.out.println("Error: password must be set - please try again");
} else if (!password.equals(inputPasswordConfirm)) {
System.out.println("Error: password and password confirm do not match - please try again");
} else {
log.info("Setting the in-memory security using the provided credentials...");
break;
}
System.out.println("");
}
scanner.close();
} else {
// Use Console
while (true) {
username = console.readLine("Username: ");
char[] passwordChars = console.readPassword("Password: ");
password = String.valueOf(passwordChars);
char[] passwordConfirmChars = console.readPassword("Confirm Password: ");
String passwordConfirm = String.valueOf(passwordConfirmChars);
if (username.isEmpty()) {
System.out.println("Error: Username must be set - please try again");
} else if (password.isEmpty()) {
System.out.println("Error: Password must be set - please try again");
} else if (!password.equals(passwordConfirm)) {
System.out.println("Error: Password and Password Confirm do not match - please try again");
} else {
log.info("Setting the in-memory security using the provided credentials...");
break;
}
System.out.println("");
}
}
// Set the inMemoryAuthentication object with the given credentials:
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
if (username != null && password != null) {
String encodedPassword = passwordEncoder().encode(password);
manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
}
return manager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
The $innerListItem.position().top
is actually relative to the .scrollTop()
of its first positioned ancestor. So the way to calculate the correct $parentDiv.scrollTop()
value is to begin by making sure that $parentDiv
is positioned. If it doesn't already have an explicit position
, use position: relative
. The elements $innerListItem
and all its ancestors up to $parentDiv
need to have no explicit position. Now you can scroll to the $innerListItem
with:
// Scroll to the top
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top);
// Scroll to the center
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top
- $parentDiv.height()/2 + $innerListItem.height()/2);
I had the same issue with my MySQL database but finally, I got a solution which worked for me.
Since in my table everything was fine from the mysql point of view(both tables should use InnoDB engine and the datatype of each column should be of the same type which takes part in foreign key constraint).
The only thing that I did was to disable the foreign key check and later on enabled it after performing the foreign key operation.
Steps that I took:
SET foreign_key_checks = 0;
alter table tblUsedDestination add constraint f_operatorId foreign key(iOperatorId) references tblOperators (iOperatorId); Query
OK, 8 rows affected (0.23 sec) Records: 8 Duplicates: 0 Warnings: 0
SET foreign_key_checks = 1;
^X-F completes using filenames from the current directory. No more copying/pasting from the terminal or painful double checking.
^X-P completes using words in the current file
:set scrollbind forces one buffer to scroll alongside another. e.g. split your window into two vertical panes. Load one file in each (perhaps different versions of the same file). Do :set scrollbind
in each. Now when you scroll in one, both panes will scroll together. Ideal for comparing files.
IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.
The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY
property value of the BindingProvider
(every proxy implements javax.xml.ws.BindingProvider
interface):
...
EchoService service = new EchoService();
Echo port = service.getEchoPort();
/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
System.out.println("Server said: " + echo.echo(args[0]));
...
The drawback is that this only works when the original WSDL is still accessible. Not recommended.
The second option is to get the endpoint URL from the WSDL.
...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService");
EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();
System.out.println("Server said: " + echo.echo(args[0]));
...
Since I cannot comment on the answer, I'd build on Jin Izzraeel's answer
var myBuffer = []; var str = 'Stack Overflow'; var buffer = new Buffer(str, 'utf16le'); for (var i = 0; i < buffer.length; i++) { myBuffer.push(buffer[i]); } console.log(myBuffer);
by saying that you could use this if you want to use a Node.js buffer in your browser.
https://github.com/feross/buffer
Therefore, Tom Stickel's objection is not valid, and the answer is indeed a valid answer.
To solve your question definitely need to use the Style
and Template
for the Button
. But how exactly does he look like? Decisions may be several. For example, Button
are two texts to better define the relevant TextBlocks
? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter
. I decided to do things differently, to identify one ContentPresenter
with an icon in the form of a Path
, and the content is set using the buttons on the side.
The style:
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="#373737" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="15" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}">
<Grid>
<Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#E59400" />
<Setter Property="Foreground" Value="White" />
<Setter TargetName="PathIcon" Property="Fill" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="OrangeRed" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Sample of using:
<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
<Button.Content>
<StackPanel>
<TextBlock Text="Watch Now" FontSize="20" />
<TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
</StackPanel>
</Button.Content>
</Button>
Output
It is best to StackPanel
determine the Resources
and set the Button
so:
<Window.Resources>
<StackPanel x:Key="MyStackPanel">
<TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
<TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
</StackPanel>
</Window.Resources>
<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />
The question remains with setting the value for TextBlock Duration
, because this value must be dynamic. I implemented it using attached DependencyProperty
. Set it to the window, like that:
<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />
Using in TextBlock
:
<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
In fact, there is no difference for anyone to determine the attached DependencyProperty
, because it is the predominant feature.
Example of set value:
private void Button_Click(object sender, RoutedEventArgs e)
{
MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}
A complete listing of examples:
XAML
<Window x:Class="ButtonHelp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ButtonHelp"
Name="MyWindow"
Title="MainWindow" Height="350" Width="525"
WindowStartupLocation="CenterScreen"
local:MyDependencyClass.CurrentDuration="Duration: 50m">
<Window.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="#373737" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="15" />
<Setter Property="FontFamily" Value="./#Segoe UI" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}">
<Grid>
<Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#E59400" />
<Setter Property="Foreground" Value="White" />
<Setter TargetName="PathIcon" Property="Fill" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="OrangeRed" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<StackPanel x:Key="MyStackPanel">
<TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
</StackPanel>
</Window.Resources>
<Grid>
<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />
<Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>
Code behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}
}
public class MyDependencyClass : DependencyObject
{
public static readonly DependencyProperty CurrentDurationProperty;
public static void SetCurrentDuration(DependencyObject DepObject, string value)
{
DepObject.SetValue(CurrentDurationProperty, value);
}
public static string GetCurrentDuration(DependencyObject DepObject)
{
return (string)DepObject.GetValue(CurrentDurationProperty);
}
static MyDependencyClass()
{
PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");
CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
typeof(string),
typeof(MyDependencyClass),
MyPropertyMetadata);
}
}
The chosen answer looks like does not apply to modern browsers, at least on Firefox 52. What I observed is that the requests of loading resources like css, javascript are issued before HTML parser reaches the element, for example
<html>
<head>
<!-- prints the date before parsing and blocks HTMP parsering -->
<script>
console.log("start: " + (new Date()).toISOString());
for(var i=0; i<1000000000; i++) {};
</script>
<script src="jquery.js" type="text/javascript"></script>
<script src="abc.js" type="text/javascript"></script>
<link rel="stylesheets" type="text/css" href="abc.css"></link>
<style>h2{font-wight:bold;}</style>
<script>
$(document).ready(function(){
$("#img").attr("src", "kkk.png");
});
</script>
</head>
<body>
<img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
<script src="kkk.js" type="text/javascript"></script>
</body>
</html>
What I found that the start time of requests to load css and javascript resources were not being blocked. Looks like Firefox has a HTML scan, and identify key resources(img resource is not included) before starting to parse the HTML.
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
If you want to check if both objects have the same properties name, you can do this:
function hasSameProps( obj1, obj2 ) {
return Object.keys( obj1 ).every( function( prop ) {
return obj2.hasOwnProperty( prop );
});
}
var obj1 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] },
obj2 = { prop1: 'hello', prop2: 'world', prop3: [1,2,3,4,5] };
console.log(hasSameProps(obj1, obj2));
In this way you are sure to check only iterable and accessible properties of both the objects.
EDIT - 2013.04.26:
The previous function can be rewritten in the following way:
function hasSameProps( obj1, obj2 ) {
var obj1Props = Object.keys( obj1 ),
obj2Props = Object.keys( obj2 );
if ( obj1Props.length == obj2Props.length ) {
return obj1Props.every( function( prop ) {
return obj2Props.indexOf( prop ) >= 0;
});
}
return false;
}
In this way we check that both the objects have the same number of properties (otherwise the objects haven't the same properties, and we must return a logical false) then, if the number matches, we go to check if they have the same properties.
Bonus
A possible enhancement could be to introduce also a type checking to enforce the match on every property.
It happens mostly when JQuery
is not installed in your project.
Install JQuery in your project by following commands according to your package manager.
yarn add jquery
npm i jquery --save
After this just import $
in your project file.
import $ from 'jquery'
Try the load() function.
$('#content').load("http://vnexpress.net");
Please not that for this to work, the URL to be loaded must either be on the same domain as the page that's calling it, or enable cross-origin HTTP requests ("Cross-Origin Resource Sharing", short CORS) on the server. This involves sending an additional HTTP header, in its most basic form:
Access-Control-Allow-Origin:*
to allow requests from everywhere.
stat's "%s" format gives you the actual number of bytes in a file.
find . -type f |
xargs stat --format=%s |
awk '{s+=$1} END {print s}'
Feel free to substitute your favourite method for summing numbers.
var otherInput = $(this).closest('.row').find('.inputQty');
That goes up to a row level, then back down to .inputQty
.
Here's a one-liner that comes in just under the 80 char line max.
import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())
For me, it just was that service console restart didn't work after tomcat ran into an error. Only stop/start brought it back.
If you just want to prevent the sleep mode on a specific View
, just call setKeepScreenOn(true)
on that View
or set the keepScreenOn
property to true
. This will prevent the screen from going off while the View
is on the screen. No special permission required for this.
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type="text/javascript">
function targetMeBlank() {
document.forms[0].target = "_blank";
}
</script>
<asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/>
I found "gradle 1.11 com.android.tools.build:gradle:0.9.+" supports pre-build ndk now, you can just put the *.so in the dir src/main/jniLibs. when building gradle will package the ndk to the right place.
here is my project
Project: |--src |--|--main |--|--|--java |--|--|--jniLibs |--|--|--|--armeabi |--|--|--|--|--.so files |--libs |--|--other.jar
One more way to add view from Activity
ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);
In Ubuntu18.04, the most easist way to get a core file is inputing the command below to stop the apport service.
sudo service apport stop
Then rerun the application, you will get dump file in current directory.
Here's the correct code. If you're using zybooks this will answer all the problems.
for (int i = 0; i<passCode.length(); i++)
{
char letter = passCode.charAt(i);
if (letter == ' ' )
{
System.out.println("Space at " + i);
}
}
It's not a cut and paste. The CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:
SELECT * FROM [Purchasing].[Vendor] WHERE
CASE
WHEN @url IS null OR @url = '' OR @url = 'ALL'
THEN PurchasingWebServiceURL LIKE '%'
WHEN @url = 'blank'
THEN PurchasingWebServiceURL = ''
WHEN @url = 'fail'
THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
ELSE PurchasingWebServiceURL = '%' + @url + '%'
END
I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since @url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?
use the below code.
alert(+(Math.round(number + "e+2") + "e-2"));
There are two different types of Java to download: The JDK, which is used to write Java programs, and the RE (runtime environment), which is used to actually run Java programs. Are you sure that you installed the RE instead of the SDK?
To search for multiple matches in each file, we can sequence several Select-String calls:
Get-ChildItem C:\Logs |
where { $_ | Select-String -Pattern 'VendorEnquiry' } |
where { $_ | Select-String -Pattern 'Failed' } |
...
At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.
Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:
filter MultiSelect-String( [string[]]$Patterns ) {
# Check the current item against all patterns.
foreach( $Pattern in $Patterns ) {
# If one of the patterns does not match, skip the item.
$matched = @($_ | Select-String -Pattern $Pattern)
if( -not $matched ) {
return
}
}
# If all patterns matched, pass the item through.
$_
}
Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...
Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:
function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
$time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}
PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True
Your JRE_HOME does not need to point to the "bin" directory. Just set it to C:\Program Files\Java\jre1.8.0_25
The following worked for me, I'm not sure what part did the trick:
julian:project$ sudo service docker status
julian:varys$ sudo service docker status
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2020-07-15 01:21:16 UTC; 24min ago
Docs: https://docs.docker.com
Main PID: 6762 (dockerd)
Tasks: 25
CGroup: /system.slice/docker.service
+-6762 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
julian:project$ export DOCKER_HOST=unix:///run/containerd/containerd.sock
julian:project$ sudo groupadd docker
groupadd: group 'docker' already exists
julian:project$ sudo gpasswd -a $USER docker
Adding user ubuntu to group docker
julian:project$ newgrp docker
julian:project$ ls -ln /var/run/ | grep docker
drwx------ 5 0 0 120 Jul 15 01:10 docker
-rw-r--r-- 1 0 0 4 Jul 15 01:10 docker.pid
srw-rw---- 1 0 999 0 Jul 15 01:10 docker.sock
julian:project$ sudo rm /var/run/docker.sock
julian:project$ sudo rm /var/run/docker.pid
julian:project$ sudo service docker restart
The location is in the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps
Source: http://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx
The difference between a non-lateral
and a lateral
join lies in whether you can look to the left hand table's row. For example:
select *
from table1 t1
cross join lateral
(
select *
from t2
where t1.col1 = t2.col1 -- Only allowed because of lateral
) sub
This "outward looking" means that the subquery has to be evaluated more than once. After all, t1.col1
can assume many values.
By contrast, the subquery after a non-lateral
join can be evaluated once:
select *
from table1 t1
cross join
(
select *
from t2
where t2.col1 = 42 -- No reference to outer query
) sub
As is required without lateral
, the inner query does not depend in any way on the outer query. A lateral
query is an example of a correlated
query, because of its relation with rows outside the query itself.
BalusC's answer is right! but I have to mention according to the user instance variable such as:
rSet.last();
total = rSet.getRow();
and then which you are missing
rSet.beforeFirst();
the remaining code is same you will get your desire result.
The OP did not ask for cleanup for all remotes, rather for all branches of default remote.
So git fetch --prune
is what should be used.
Setting git config remote.origin.prune true
makes --prune
automatic. In that case just git fetch
will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.
Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
This is a guess. Generally recursion probably doesn't beat looping often or ever on problems of decent size if both are using really good algorithms(not counting implementation difficulty) , it may be different if used with a language w/ tail call recursion(and a tail recursive algorithm and with loops also as part of the language)-which would probably have very similar and possibly even prefer recursion some of the time.
If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc
This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array
import numpy as np
from sklearn.metrics import auc
dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)
print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))
both output the same area: 4607.5
the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
The accepted answer needs an Option 3
ALSO Option 2 is TERRIBLE. It should NEVER be used (esp. in production) since it provides a FALSE sense of security. Just use HTTP instead of Option 2.
OPTION 3
Use the self-signed certificate to make the Https connection.
Here is an example:
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.KeyStore;
/*
* Use a SSLSocket to send a HTTP GET request and read the response from an HTTPS server.
* It assumes that the client is not behind a proxy/firewall
*/
public class SSLSocketClientCert
{
private static final String[] useProtocols = new String[] {"TLSv1.2"};
public static void main(String[] args) throws Exception
{
URL inputUrl = null;
String certFile = null;
if(args.length < 1)
{
System.out.println("Usage: " + SSLSocketClient.class.getName() + " <url>");
System.exit(1);
}
if(args.length == 1)
{
inputUrl = new URL(args[0]);
}
else
{
inputUrl = new URL(args[0]);
certFile = args[1];
}
SSLSocket sslSocket = null;
PrintWriter outWriter = null;
BufferedReader inReader = null;
try
{
SSLSocketFactory sslSocketFactory = getSSLSocketFactory(certFile);
sslSocket = (SSLSocket) sslSocketFactory.createSocket(inputUrl.getHost(), inputUrl.getPort() == -1 ? inputUrl.getDefaultPort() : inputUrl.getPort());
String[] enabledProtocols = sslSocket.getEnabledProtocols();
System.out.println("Enabled Protocols: ");
for(String enabledProtocol : enabledProtocols) System.out.println("\t" + enabledProtocol);
String[] supportedProtocols = sslSocket.getSupportedProtocols();
System.out.println("Supported Protocols: ");
for(String supportedProtocol : supportedProtocols) System.out.println("\t" + supportedProtocol + ", ");
sslSocket.setEnabledProtocols(useProtocols);
/*
* Before any data transmission, the SSL socket needs to do an SSL handshake.
* We manually initiate the handshake so that we can see/catch any SSLExceptions.
* The handshake would automatically be initiated by writing & flushing data but
* then the PrintWriter would catch all IOExceptions (including SSLExceptions),
* set an internal error flag, and then return without rethrowing the exception.
*
* This means any error messages are lost, which causes problems here because
* the only way to tell there was an error is to call PrintWriter.checkError().
*/
sslSocket.startHandshake();
outWriter = sendRequest(sslSocket, inputUrl);
readResponse(sslSocket);
closeAll(sslSocket, outWriter, inReader);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
closeAll(sslSocket, outWriter, inReader);
}
}
private static PrintWriter sendRequest(SSLSocket sslSocket, URL inputUrl) throws IOException
{
PrintWriter outWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream())));
outWriter.println("GET " + inputUrl.getPath() + " HTTP/1.1");
outWriter.println("Host: " + inputUrl.getHost());
outWriter.println("Connection: Close");
outWriter.println();
outWriter.flush();
if(outWriter.checkError()) // Check for any PrintWriter errors
System.out.println("SSLSocketClient: PrintWriter error");
return outWriter;
}
private static void readResponse(SSLSocket sslSocket) throws IOException
{
BufferedReader inReader = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
String inputLine;
while((inputLine = inReader.readLine()) != null)
System.out.println(inputLine);
}
// Terminate all streams
private static void closeAll(SSLSocket sslSocket, PrintWriter outWriter, BufferedReader inReader) throws IOException
{
if(sslSocket != null) sslSocket.close();
if(outWriter != null) outWriter.close();
if(inReader != null) inReader.close();
}
// Create an SSLSocketFactory based on the certificate if it is available, otherwise use the JVM default certs
public static SSLSocketFactory getSSLSocketFactory(String certFile)
throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException
{
if (certFile == null) return (SSLSocketFactory) SSLSocketFactory.getDefault();
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(new File(certFile)));
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("server", certificate);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
return sslContext.getSocketFactory();
}
}
There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.
For functions with return types, there is Func<> and for functions without return types there is Action<>.
Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).
So you can declare your Diff function to take a Func:
public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:
double result = Diff(myValue, Function);
You can even write the function in-line with lambda syntax:
double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
Try this one also...
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p>Click the button to join two arrays.</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var hege = [{_x000D_
1: "Cecilie",_x000D_
2: "Lone"_x000D_
}];_x000D_
var stale = [{_x000D_
1: "Emil",_x000D_
2: "Tobias"_x000D_
}];_x000D_
var hege = hege.concat(stale);_x000D_
document.getElementById("demo1").innerHTML = hege;_x000D_
document.getElementById("demo").innerHTML = stale;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You can use the --system-site-packages
and then "overinstall" the specific stuff for your virtualenv. That way, everything you install into your virtualenv will be taken from there, otherwise it will be taken from your system.
Adding my solution - it will return a callback whether it is from the camera or from the galley alongside the intent:
public class ImagePickerManager extends BaseAdapter {
private List<ResolveInfo> mApplications;
private TreeSet<Integer> mImageCaptureIntents;
private TreeSet<Integer> mImagePickerIntents;
private Context mContext;
private final ImagePickerManagerListener listener;
private static enum intentType {
choosePhoto,
takePhoto,
unknown;
public int getIntValue() {
switch (this) {
case choosePhoto:
return 0;
case takePhoto:
return 1;
case unknown:
return 2;
}
return 0;
}
}
public interface ImagePickerManagerListener {
void onChooseImage(Intent intent);
void onCaptureImage(Intent intent);
}
public ImagePickerManager(Context context,ImagePickerManagerListener listenr) {
this.mContext = context;
this.listener = listenr;
mImageCaptureIntents = new TreeSet<>();
mImagePickerIntents = new TreeSet<>();
//Picking photo intent
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
mApplications = mContext.getPackageManager().queryIntentActivities(intent, 0);
int index = 0;
for (int i = 0; i < mApplications.size(); i++) {
mImagePickerIntents.add(index);
index++;
}
//Capture photo intent
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> resolveInfoList = mContext.getPackageManager().queryIntentActivities(intent, 0);
mApplications.addAll(resolveInfoList);
for (int i = 0; i < mApplications.size(); i++) {
mImageCaptureIntents.add(index);
index++;
}
}
public static void openChooseAndCaptureImageDialog(final Context context, final ImagePickerManagerListener listener) {
Log.d("openChooseAndCaptureImageDialog", "enter");
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
final ImagePickerManager imagePickerManager = new ImagePickerManager(context,listener);
builder.setTitle(context.getString(R.string.image_picker_dialog_box_title));
builder.setAdapter(imagePickerManager, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialoginterface, int i) {
ResolveInfo resolveInfo = (ResolveInfo) imagePickerManager.getItem(i);
Intent pickerIntent = imagePickerManager.getIntentForPackage(context,resolveInfo,i);
switch (imagePickerManager.getIntentType(i)){
case choosePhoto:
listener.onChooseImage(pickerIntent);
break;
case takePhoto:
listener.onCaptureImage(pickerIntent);
break;
case unknown:
break;
}
}
});
builder.setCancelable(true);
builder.setInverseBackgroundForced(true);
AlertDialog dialog = builder.create();
dialog.show();
}
private intentType getIntentType(int index) {
if (mImageCaptureIntents.contains(index)) {
return intentType.takePhoto;
} else if(mImagePickerIntents.contains(index)) {
return intentType.choosePhoto;
}
return intentType.unknown;
}
private Intent getIntentForPackage(Context context, ResolveInfo info,int index) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(info.activityInfo.packageName);
ComponentName chosenName = new ComponentName(
info.activityInfo.packageName,
info.activityInfo.name);
intent.setComponent(chosenName);
intent.setFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
if (mImageCaptureIntents.contains(index)) {
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
} else if(mImagePickerIntents.contains(index)) {
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
}
return intent;
}
@Override
public int getCount() {
return mApplications.size();
}
@Override
public Object getItem(int position) {
return mApplications.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ResolveInfo item = mApplications.get(position);
if (convertView == null) {
TextView applicationTextView = new TextView(mContext);
LayoutParams param = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
applicationTextView.setLayoutParams(param);
final int horizontalPadding = (int) FVRGeneralUtils.convertDpToPx(mContext, 15);
final int verticalPadding = (int) FVRGeneralUtils.convertDpToPx(mContext, 5);
applicationTextView.setPadding(horizontalPadding,verticalPadding, horizontalPadding, verticalPadding);
applicationTextView.setGravity(android.view.Gravity.CENTER_VERTICAL);
Resources.Theme th = mContext.getTheme();
TypedValue tv = new TypedValue();
if (th.resolveAttribute(android.R.attr.textAppearanceMedium, tv, true)) {
applicationTextView.setTextAppearance(mContext, tv.resourceId);
}
applicationTextView.setMinHeight((int) FVRGeneralUtils.convertDpToPx(mContext, 25));
applicationTextView.setCompoundDrawablePadding((int) FVRGeneralUtils.convertDpToPx(mContext, 7));
convertView = applicationTextView;
}
TextView textView = (TextView) convertView;
textView.setText(item.loadLabel(mContext.getPackageManager()));
textView.setCompoundDrawablesWithIntrinsicBounds(item.loadIcon(mContext.getPackageManager()), null, null, null);
return textView;
} }
An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.
I guess the poster assumes a certain level of knowledge about the language.
I wrote a little script based on Florian's answer that uses nano (my favorite editor):
#!/bin/sh
if [ "$#" -ne 3 ]; then
echo "Usage: $0 hugeFilePath startLine endLine" >&2
exit 1
fi
sed -n -e $2','$3'p' -e $3'q' $1 > hfnano_temporary_file
nano hfnano_temporary_file
(head -n `expr $2 - 1` $1; cat hfnano_temporary_file; sed -e '1,'$3'd' $1) > hfnano_temporary_file2
cat hfnano_temporary_file2 > $1
rm hfnano_temporary_file hfnano_temporary_file2
Use it like this:
sh hfnano yourHugeFile 3 8
In that example, nano will open up lines 3 through 8, you can edit them, and when you save and quit, those lines in the hugefile will automatically be overwritten with your saved lines.
Yes, it’s frustrating—sometimes type
and other programs
print gibberish, and sometimes they do not.
First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.
But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.
When programs use standard C-library I/O functions like printf
, the
program’s output encoding must match the console’s output encoding, or
you will get gibberish. chcp
shows and sets the current codepage. All
output using standard C-library I/O functions is treated as if it is in the
codepage displayed by chcp
.
Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:
A program can get the console’s current codepage using chcp
or
GetConsoleOutputCP
, and configure itself to output in that encoding, or
You or a program can set the console’s current codepage using chcp
or
SetConsoleOutputCP
to match the default output encoding of the program.
However, programs that use Win32 APIs can write UTF-16LE strings directly
to the console with
WriteConsoleW
.
This is the only way to get correct output without setting codepages. And
even when using that function, if a string is not in the UTF-16LE encoding
to begin with, a Win32 program must pass the correct codepage to
MultiByteToWideChar
.
Also, WriteConsoleW
will not work if the program’s output is redirected;
more fiddling is needed in that case.
type
works some of the time because it checks the start of each file for
a UTF-16LE Byte Order Mark
(BOM), i.e. the bytes 0xFF 0xFE
.
If it finds such a
mark, it displays the Unicode characters in the file using WriteConsoleW
regardless of the current codepage. But when type
ing any file without a
UTF-16LE BOM, or for using non-ASCII characters with any command
that doesn’t call WriteConsoleW
—you will need to set the
console codepage and program output encoding to match each other.
How can we find this out?
Here’s a test file containing Unicode characters:
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
Here’s a Java program to print out the test file in a bunch of different
Unicode encodings. It could be in any programming language; it only prints
ASCII characters or encoded bytes to stdout
.
import java.io.*;
public class Foo {
private static final String BOM = "\ufeff";
private static final String TEST_STRING
= "ASCII abcde xyz\n"
+ "German äöü ÄÖÜ ß\n"
+ "Polish aezznl\n"
+ "Russian ??????? ???\n"
+ "CJK ??\n";
public static void main(String[] args)
throws Exception
{
String[] encodings = new String[] {
"UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };
for (String encoding: encodings) {
System.out.println("== " + encoding);
for (boolean writeBom: new Boolean[] {false, true}) {
System.out.println(writeBom ? "= bom" : "= no bom");
String output = (writeBom ? BOM : "") + TEST_STRING;
byte[] bytes = output.getBytes(encoding);
System.out.write(bytes);
FileOutputStream out = new FileOutputStream("uc-test-"
+ encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
out.write(bytes);
out.close();
}
}
}
}
The output in the default codepage? Total garbage!
Z:\andrew\projects\sx\1259084>chcp
Active code page: 850
Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
= bom
´++ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
== UTF-16LE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
= bom
¦A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
== UTF-16BE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
== UTF-32LE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
== UTF-32BE
= no bom
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
= bom
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
However, what if we type
the files that got saved? They contain the exact
same bytes that were printed to the console.
Z:\andrew\projects\sx\1259084>type *.txt
uc-test-UTF-16BE-bom.txt
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
uc-test-UTF-16BE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?????z?|?D?B
R u s s i a n ?0?1?2?3?4?5?6 ?M?N?O
C J K O`Y}
uc-test-UTF-16LE-bom.txt
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
uc-test-UTF-16LE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
uc-test-UTF-32BE-bom.txt
¦ A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
uc-test-UTF-32BE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? ?z ?| ?D ?B
R u s s i a n ?0 ?1 ?2 ?3 ?4 ?5 ?6 ?M ?N
?O
C J K O` Y}
uc-test-UTF-32LE-bom.txt
A S C I I a b c d e x y z
G e r m a n ä ö ü Ä Ö Ü ß
P o l i s h a e z z n l
R u s s i a n ? ? ? ? ? ? ? ? ? ?
C J K ? ?
uc-test-UTF-32LE-nobom.txt
A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ?? ?? z? |? D? B?
R u s s i a n 0? 1? 2? 3? 4? 5? 6? M? N
? O?
C J K `O }Y
uc-test-UTF-8-bom.txt
´++ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
uc-test-UTF-8-nobom.txt
ASCII abcde xyz
German +ñ+Â++ +ä+û+£ +ƒ
Polish -à-Ö+¦+++ä+é
Russian ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK õ¢áÕÑ¢
The only thing that works is UTF-16LE file, with a BOM, printed to the
console via type
.
If we use anything other than type
to print the file, we get garbage:
Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
¦A S C I I a b c d e x y z
G e r m a n õ ÷ ³ - Í _ ¯
P o l i s h ????z?|?D?B?
R u s s i a n 0?1?2?3?4?5?6? M?N?O?
C J K `O}Y
1 file(s) copied.
From the fact that copy CON
does not display Unicode correctly, we can
conclude that the type
command has logic to detect a UTF-16LE BOM at the
start of the file, and use special Windows APIs to print it.
We can see this by opening cmd.exe
in a debugger when it goes to type
out a file:
After type
opens a file, it checks for a BOM of 0xFEFF
—i.e., the bytes
0xFF 0xFE
in little-endian—and if there is such a BOM, type
sets an
internal fOutputUnicode
flag. This flag is checked later to decide
whether to call WriteConsoleW
.
But that’s the only way to get type
to output Unicode, and only for files
that have BOMs and are in UTF-16LE. For all other files, and for programs
that don’t have special code to handle console output, your files will be
interpreted according to the current codepage, and will likely show up as
gibberish.
You can emulate how type
outputs Unicode to the console in your own programs like so:
#include <stdio.h>
#define UNICODE
#include <windows.h>
static LPCSTR lpcsTest =
"ASCII abcde xyz\n"
"German äöü ÄÖÜ ß\n"
"Polish aezznl\n"
"Russian ??????? ???\n"
"CJK ??\n";
int main() {
int n;
wchar_t buf[1024];
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
n = MultiByteToWideChar(CP_UTF8, 0,
lpcsTest, strlen(lpcsTest),
buf, sizeof(buf));
WriteConsole(hConsole, buf, n, &n, NULL);
return 0;
}
This program works for printing Unicode on the Windows console using the default codepage.
For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:
Z:\andrew\projects\sx\1259084>chcp 65001
Active code page: 65001
Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
? ???
CJK ??
??
?
?
= bom
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
?? ???
CJK ??
??
?
?
== UTF-16LE
= no bom
A S C I I a b c d e x y z
…
However, a C program that sets a Unicode UTF-8 codepage:
#include <stdio.h>
#include <windows.h>
int main() {
int c, n;
UINT oldCodePage;
char buf[1024];
oldCodePage = GetConsoleOutputCP();
if (!SetConsoleOutputCP(65001)) {
printf("error\n");
}
freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
fwrite(buf, sizeof(buf[0]), n, stdout);
SetConsoleOutputCP(oldCodePage);
return 0;
}
does have correct output:
Z:\andrew\projects\sx\1259084>.\test
ASCII abcde xyz
German äöü ÄÖÜ ß
Polish aezznl
Russian ??????? ???
CJK ??
The moral of the story?
type
can print UTF-16LE files with a BOM regardless of your current codepageWriteConsoleW
.chcp
, and will probably still get weird output.To answer your questions in a easy way:
a) String.length();
b) String.charAt(/* String index */);
Following two steps worked perfectly fine for me:
Comment out the bind address from the file /etc/mysql/my.cnf
:
#bind-address = 127.0.0.1
Run following query in phpMyAdmin:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'; FLUSH PRIVILEGES;
You can use sed
:
sed -i 's/abc/XYZ/gi' /tmp/file.txt
You can use find
and sed
if you don't know your filename:
find ./ -type f -exec sed -i 's/abc/XYZ/gi' {} \;
Find and replace in all Python files:
find ./ -iname "*.py" -type f -exec sed -i 's/abc/XYZ/gi' {} \;
Best approach of removing duplicates from a list is using set() function, available in python, again converting that set into list
In [2]: some_list = ['a','a','v','v','v','c','c','d']
In [3]: list(set(some_list))
Out[3]: ['a', 'c', 'd', 'v']
It is possible to have 2 groovy-xxx-all.jar files by excample in lib directory. which makes that an app is not running
Another basic example:
NOT working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
};
img.src = reader.result;
Working:
var img = new Image;
img.onload = function() {
this.myGlobalFunction(img);
}.bind(this);
img.src = reader.result;
So basically: just add .bind(this) to your function
You can't compare arrays directly like this
array1==array2
You should compare them char-by-char; for this you can use a function and return a boolean (True:1, False:0) value. Then you can use it in the test condition of the while loop.
Try this:
#include <stdio.h>
int checker(char input[],char check[]);
int main()
{
char input[40];
char check[40];
int i=0;
printf("Hello!\nPlease enter a word or character:\n");
scanf("%s",input);
printf("I will now repeat this until you type it back to me.\n");
scanf("%s",check);
while (!checker(input,check))
{
printf("%s\n", input);
scanf("%s",check);
}
printf("Good bye!");
return 0;
}
int checker(char input[],char check[])
{
int i,result=1;
for(i=0; input[i]!='\0' || check[i]!='\0'; i++) {
if(input[i] != check[i]) {
result=0;
break;
}
}
return result;
}
You can get this if the client specifies "https" but the server is only running "http". So, the server isn't expecting to make a secure connection.
I would say that the basic difference is this:
Grids are used as computing/storage platform.
We start talking about cloud computing when it offers services. I would almost say that cloud computing is higher-level grid. Now I know these are not definitions, but maybe it will make it more clear.
As far as application domains go, grids require users (developers mostly) to actually create services from low-level functions that grid offers. Cloud will offer complete blocks of functionality that you can use in your application.
Example (you want to create physical simulation of ball dropping from certain height): Grid: Study how to compute physics on a computer, create appropriate code, optimize it for certain hardware, think about paralellization, set inputs send application to grid and wait for answer
Cloud: Set diameter of a ball, material from pre-set types, height from which the ball is dropping, etc and ask for results
I would say that if you created OS for grid, you would actually create cloud OS.
for further investigation: print out the mssql error message:
$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message());
It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:
$myServer = "10.85.80.229:1443";
or
$myServer = "10.85.80.229,1443";
Another approach to count number of list elements:
var num = $("#menu").find("li").length;_x000D_
if (num > 1) {_x000D_
console.log(num);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul id="menu">_x000D_
<li>Element 1</li>_x000D_
<li>Element 2</li>_x000D_
<li>Element 3</li>_x000D_
</ul>
_x000D_
You have to specify the format (fmt
) of you data in savetxt
, in this case as a string (%s
):
num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s")
The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.
This should do it for you:
new_list = list(set(old_list))
set
will automatically remove duplicates. list
will cast it back to a list.
I have written a shell script to install/uninstall java on centos. You can get it done by just run the shell. The core of this shell is :
1.download the jdk rpm(RedHat Package Manager) package.
2.install java using rpm.
You can see more detail here: https://github.com/daikaixian/WaterShell/tree/master/program_installer
Hope it works for you.
Try this code in Swift or Objective-C
Swift
self.tabBarController.selectedIndex = 1
Objective-C
[self.tabBarController setSelectedIndex:1];
You're probably trying to convert to a UNIX-like timestamp, which are in UTC:
yourDateTime.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
).TotalMilliseconds
This also avoids summertime issues, since UTC doesn't have those.
Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).
@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
.
@implementation NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
.
@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
.
@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
Just a few lines of example code to show the difference between numpy.array and numpy.ndarray
Warm up step: Construct a list
a = [1,2,3]
Check the type
print(type(a))
You will get
<class 'list'>
Construct an array (from a list) using np.array
a = np.array(a)
Or, you can skip the warm up step, directly have
a = np.array([1,2,3])
Check the type
print(type(a))
You will get
<class 'numpy.ndarray'>
which tells you the type of the numpy array is numpy.ndarray
You can also check the type by
isinstance(a, (np.ndarray))
and you will get
True
Either of the following two lines will give you an error message
np.ndarray(a) # should be np.array(a)
isinstance(a, (np.array)) # should be isinstance(a, (np.ndarray))
I had the same error:
fatal error LNK1104: cannot open file 'GTest.lib;'
This was caused by the ;
at the end. If you have multiple libraries, they should be separated by empty space (spacebar), no comma or semi-colons!
So don't use ;
or any anything else when listing libraries in Project properties >> Configuration Properties >> Linker >> Input
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
I used zsxwing's answer successfully to solve the following problem:
I have source that I build on multiple hosts (on a Raspberry Pi Linux board, on a VMware Linux virtual machine, etc.)
I have a Bash script that creates temporary directories based on the hostname of the machine like this:
# Get hostname to use as part of directory names
HOST_NAME=`uname -n`
# Create a temporary directory for cmake files so they don't
# end up all mixed up with the source.
TMP_DIR="cmake.tmp.$HOSTNAME"
if [ ! -e $TMP_DIR ] ; then
echo "Creating directory for cmake tmp files : $TMP_DIR"
mkdir $TMP_DIR
else
echo "Reusing cmake tmp dir : $TMP_DIR"
fi
# Create makefiles with CMake
#
# Note: switch to the temporary dir and build parent
# which is a way of making cmake tmp files stay
# out of the way.
#
# Note 2: to clean up cmake files, it is OK to
# "rm -rf" the temporary directories
echo
echo Creating Makefiles with cmake ...
cd $TMP_DIR
cmake ..
# Run makefile (in temporary directory)
echo
echo Starting build ...
make
Wrapping the existing formula in IFERROR will not achieve:
the average of cells that contain non-zero, non-blank values.
I suggest trying:
=if(ArrayFormula(isnumber(K23:M23)),AVERAGEIF(K23:M23,"<>0"),"")
You should find you answer here.
Thanks @Will and @Matt for this elegant solution.
jQuery('#path .to .your a').each(function(){
var $t = jQuery(this);
$t.after($t.text());
$t.remove();
});
This code capitalize words after dot:
function capitalizeAfterPeriod(input) {
var text = '';
var str = $(input).val();
text = convert(str.toLowerCase().split('. ')).join('. ');
var textoFormatado = convert(text.split('.')).join('.');
$(input).val(textoFormatado);
}
function convert(str) {
for(var i = 0; i < str.length; i++){
str[i] = str[i].split('');
if (str[i][0] !== undefined) {
str[i][0] = str[i][0].toUpperCase();
}
str[i] = str[i].join('');
}
return str;
}
As mentioned in previous posts already, OPTIONS
requests are there for a reason. If you have an issue with large response times from your server (e.g. overseas connection) you can also have your browser cache the preflight requests.
Have your server reply with the Access-Control-Max-Age
header and for requests that go to the same endpoint the preflight request will have been cached and not occur anymore.
Issue the following command,the way to run specified logrotate:
logrotate -vf /etc/logrotate.d/custom
Options:
-v :show the process
-f :forcing run
custom :user-defined log setting
eg: mongodb-log
# mongodb-log rotate
/data/var/log/mongodb/mongod.log {
daily
dateext
rotate 30
copytruncate
missingok
}
Great answers are:
My note here comes from what Donald Knuth once said (sorry can't find reference) that there is a construct where while-else is indistinguishable from if-else, namely (in Python):
x = 2
while x > 3:
print("foo")
break
else:
print("boo")
has the same flow (excluding low level differences) as:
x = 2
if x > 3:
print("foo")
else:
print("boo")
The point is that if-else can be considered as syntactic sugar for while-else which has implicit break
at the end of its if
block. The opposite implication, that while
loop is extension to if
, is more common (it's just repeated/looped conditional check), because if
is often taught before while
. However that isn't true because that would mean else
block in while-else would be executed each time when condition is false.
To ease your understanding think of it that way:
Without
break
,return
, etc., loop ends only when condition is no longer true and in such caseelse
block will also execute once. In case of Pythonfor
you must consider C-stylefor
loops (with conditions) or translate them towhile
.
Another note:
Premature
break
,return
, etc. inside loop makes impossible for condition to become false because execution jumped out of the loop while condition was true and it would never come back to check it again.
//
syntaxregex.test(string)
, not string.test(regex)
So
jQuery(function () {
$(".mail").keyup(function () {
var VAL = this.value;
var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
if (email.test(VAL)) {
alert('Great, you entered an E-Mail-address');
}
});
});
You need to update your virtualbox sw. On new version, there is VBoxDarwinAdditions.pkg included in a additions iso image, in older versions is missing.
One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:
SELECT a.ID,
a.AText,
(SELECT Count(ID)
FROM table1 b WHERE b.ID <= a.ID
AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;
using List Comprehension:
>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]
>>>
which roughly translates to using a for loop:
>>> newL = []
>>> for x in L:
... newL+=[x+1]
...
>>> newL
[2, 2, 2, 2, 2]
or using map:
>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]
>>>
list
First a very important point, from which everything will follow (I hope).
In ordinary Python, list
is not special in any way (except having cute syntax for constructing, which is mostly a historical accident). Once a list [3,2,6]
is made, it is for all intents and purposes just an ordinary Python object, like a number 3
, set {3,7}
, or a function lambda x: x+5
.
(Yes, it supports changing its elements, and it supports iteration, and many other things, but that's just what a type is: it supports some operations, while not supporting some others. int supports raising to a power, but that doesn't make it very special - it's just what an int is. lambda supports calling, but that doesn't make it very special - that's what lambda is for, after all:).
and
and
is not an operator (you can call it "operator", but you can call "for" an operator too:). Operators in Python are (implemented through) methods called on objects of some type, usually written as part of that type. There is no way for a method to hold an evaluation of some of its operands, but and
can (and must) do that.
The consequence of that is that and
cannot be overloaded, just like for
cannot be overloaded. It is completely general, and communicates through a specified protocol. What you can do is customize your part of the protocol, but that doesn't mean you can alter the behavior of and
completely. The protocol is:
Imagine Python interpreting "a and b" (this doesn't happen literally this way, but it helps understanding). When it comes to "and", it looks at the object it has just evaluated (a), and asks it: are you true? (NOT: are you True
?) If you are an author of a's class, you can customize this answer. If a
answers "no", and
(skips b completely, it is not evaluated at all, and) says: a
is my result (NOT: False is my result).
If a
doesn't answer, and
asks it: what is your length? (Again, you can customize this as an author of a
's class). If a
answers 0, and
does the same as above - considers it false (NOT False), skips b, and gives a
as result.
If a
answers something other than 0 to the second question ("what is your length"), or it doesn't answer at all, or it answers "yes" to the first one ("are you true"), and
evaluates b, and says: b
is my result. Note that it does NOT ask b
any questions.
The other way to say all of this is that a and b
is almost the same as b if a else a
, except a is evaluated only once.
Now sit for a few minutes with a pen and paper, and convince yourself that when {a,b} is a subset of {True,False}, it works exactly as you would expect of Boolean operators. But I hope I have convinced you it is much more general, and as you'll see, much more useful this way.
Now I hope you understand your example 1. and
doesn't care if mylist1 is a number, list, lambda or an object of a class Argmhbl. It just cares about mylist1's answer to the questions of the protocol. And of course, mylist1 answers 5 to the question about length, so and returns mylist2. And that's it. It has nothing to do with elements of mylist1 and mylist2 - they don't enter the picture anywhere.
&
on list
On the other hand, &
is an operator like any other, like +
for example. It can be defined for a type by defining a special method on that class. int
defines it as bitwise "and", and bool defines it as logical "and", but that's just one option: for example, sets and some other objects like dict keys views define it as a set intersection. list
just doesn't define it, probably because Guido didn't think of any obvious way of defining it.
On the other leg:-D, numpy arrays are special, or at least they are trying to be. Of course, numpy.array is just a class, it cannot override and
in any way, so it does the next best thing: when asked "are you true", numpy.array raises a ValueError, effectively saying "please rephrase the question, my view of truth doesn't fit into your model". (Note that the ValueError message doesn't speak about and
- because numpy.array doesn't know who is asking it the question; it just speaks about truth.)
For &
, it's completely different story. numpy.array can define it as it wishes, and it defines &
consistently with other operators: pointwise. So you finally get what you want.
HTH,
Just important to point that the URL object handle both validation and connection. Then, only protocols for which a handler has been provided in sun.net.www.protocol are authorized (file, ftp, gopher, http, https, jar, mailto, netdoc) are valid ones. For instance, try to make a new URL with the ldap protocol:
new URL("ldap://myhost:389")
You will get a java.net.MalformedURLException: unknown protocol: ldap
.
You need to implement your own handler and register it through URL.setURLStreamHandlerFactory()
. Quite overkill if you just want to validate the URL syntax, a regexp seems to be a simpler solution.
If your button is default "button" make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.
if you use js do like this
<form method="POST">
<button name="data" type="button" id="btnData" onclick="getData()">Click</button>
</form>
**If you use jquery use like this**
<form method="POST">
<button name="data" type="button" id="btnData">Click</button>
</form>
$('#btnData').click(function(e){
e.preventDefault();
// Code goes here
getData(); // your onclick function call here
});
You don't need to use the asterisk to accept a list.
Simply give the argument a name in the definition, and pass in a list like
def takes_list(a_list):
for item in a_list:
print item
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
<script src="test.js?random=<?php echo uniqid(); ?>"></script>
EDIT: Or you could use the file modification time so that it's cached on the client.
<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>
I've found the solution. I've recently upgraded my machine to Windows 2008 Server 64-bit. The SqlServer.Replication namespace was written for 32-bit platforms. All I needed to do to get it running again was to set the Target Platform in the Project Build Properties to X86.
This worked perfectly for me without css. I think css would put some icing on the cake though.
<form>
<label for="First Name" >First Name:</label>
<input type="text" name="username" size="15" maxlength="30" />
<label for="Last Name" >Last Name:</label>
<input type="text" name="username" size="15" maxlength="30" />
</form>
Here is my answer,
In row.model.ts
export interface Row {
otherProperty : type;
checked : bool;
otherProperty : type;
...
}
In .html
<tr class="even" *ngFor="let item of rows">
<input [checked]="item.checked" type="checkbox">
</tr>
In .ts
rows : Row[] = [];
update the rows in component.ts
The usernames are shown in the dba_users's username
column, there is a script you can run called:
alter user username identified by password
You can get more information here - https://community.oracle.com/thread/632617?tstart=0
The best option would be to set a class style in CSS like .showMenu
and .hideMenu
with the various styles inside. Then you can do something like
$("#user_button").addClass("showMenu");
Try this:
<?php $htmlString= 'testing'; ?>
<html>
<body>
<script type="text/javascript">
// notice the quotes around the ?php tag
var htmlString="<?php echo $htmlString; ?>";
alert(htmlString);
</script>
</body>
</html>
When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.
Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing'
to $htmlString
. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.
public class IntergerParser {
public static void main(String[] args){
String number = "+123123";
System.out.println(parseInt(number));
}
private static int parseInt(String number){
char[] numChar = number.toCharArray();
int intValue = 0;
int decimal = 1;
for(int index = numChar.length ; index > 0 ; index --){
if(index == 1 ){
if(numChar[index - 1] == '-'){
return intValue * -1;
} else if(numChar[index - 1] == '+'){
return intValue;
}
}
intValue = intValue + (((int)numChar[index-1] - 48) * (decimal));
System.out.println((int)numChar[index-1] - 48+ " " + (decimal));
decimal = decimal * 10;
}
return intValue;
}
Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at Adding SOAP headers when sending requests:
The portable way of doing this is that you create a
SOAPHandler
and mess with SAAJ, but the RI provides a better way of doing this.When you create a proxy or dispatch object, they implement
BindingProvider
interface. When you use the JAX-WS RI, you can downcast toWSBindingProvider
which defines a few more methods provided only by the JAX-WS RI.This interface lets you set an arbitrary number of Header object, each representing a SOAP header. You can implement it on your own if you want, but most likely you'd use one of the factory methods defined on
Headers
class to create one.import com.sun.xml.ws.developer.WSBindingProvider; HelloPort port = helloService.getHelloPort(); // or something like that... WSBindingProvider bp = (WSBindingProvider)port; bp.setOutboundHeader( // simple string value as a header, like <simpleHeader>stringValue</simpleHeader> Headers.create(new QName("simpleHeader"),"stringValue"), // create a header from JAXB object Headers.create(jaxbContext,myJaxbObject) );
Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.
Update: It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post Implementing the WS-Security UsernameToken Profile for Metro-based web services (jump to step 4). Using NetBeans for this step might ease things a lot.
Just in case someone is interest only in what kind of process created the shared moeries, call
ls -l /dev/shm
It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.
None of the above worked for me. But what actually worked was deleting all *.snap files from my workspace. This also preserves almost all settings including imported projects. Make sure to back up the workspace before trying it though!!!
When I use SourceTree to do the stuff, it will spit out this message.
The message that I encountered:
git -c diff.mnemonicprefix=false -c core.quotepath=false -c credential.helper=sourcetree submodule update --init --recursive
No submodule mapping found in .gitmodules for path 'SampleProject/SampleProject'
Completed with errors, see above
My scenario is I misapplied the project directory the contains .git folder.
SourceTree regarded this folder as git submodule, but actually not.
My solution is use command line to remove it.
$ git rm -r SampleProject --cached
$ git commit -m "clean up folders"
remove the garbage in git and keep it clean.
That’s a typo. You’ve accidently set user.mail
with no e. Fix it by setting user.email
in the global configuration with
git config --global user.email "[email protected]"
There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html
This has happened to me several times migrating from Apache 2.2.
What I have found is that there is an Order,Deny that I missed with VIM's Search feature somehow that is the default main Vhost, line 379. Hope this helps someone. I commented out the Order Deny,Allow and Deny from All and it worked!
A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.
I saw a presentation on mongodb yesterday. I can definitely say that setup was "simple", as simple as unpacking it and firing it up. Done.
I believe that both mongodb and cassandra will run on virtually any regular linux hardware so you should not find to much barrier in that area.
I think in this case, at the end of the day, it will come down to which do you personally feel more comfortable with and which has a toolset that you prefer. As far as the presentation on mongodb, the presenter indicated that the toolset for mongodb was pretty light and that there werent many (they said any really) tools similar to whats available for MySQL. This was of course their experience so YMMV. One thing that I did like about mongodb was that there seemed to be lots of language support for it (Python, and .NET being the two that I primarily use).
The list of sites using mongodb is pretty impressive, and I know that twitter just switched to using cassandra.
printf
accepts a variable number of arguments. Those can only have Plain Old Data (POD) types. Code that passes anything other than POD to printf
only compiles because the compiler assumes you got your format right. %s
means that the respective argument is supposed to be a pointer to a char
. In your case it is an std::string
not const char*
. printf
does not know it because the argument type goes lost and is supposed to be restored from the format parameter. When turning that std::string
argument into const char*
the resulting pointer will point to some irrelevant region of memory instead of your desired C string. For that reason your code prints out gibberish.
While printf
is an excellent choice for printing out formatted text, (especially if you intend to have padding), it can be dangerous if you haven't enabled compiler warnings. Always enable warnings because then mistakes like this are easily avoidable. There is no reason to use the clumsy std::cout
mechanism if the printf
family can do the same task in a much faster and prettier way. Just make sure you have enabled all warnings (-Wall -Wextra
) and you will be good. In case you use your own custom printf
implementation you should declare it with the __attribute__
mechanism that enables the compiler to check the format string against the parameters provided.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
**In Eclipse Ide
for generating both setters and getters -> alt+shift+s+r then Alt A then click on ok;
for generating only getters ->alt+shift+s+r then press g then click on ok button;
for generating only setters ->alt+shift+s+r then press l then click on ok button;**
Add the following to your conf file
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
for complete this script , the function for draw circle ,
function drawCircle(coordon)
{
var coord = coordon.split(',');
var c = document.getElementById("myCanvas");
var hdc = c.getContext("2d");
hdc.beginPath();
hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
hdc.stroke();
}
The two alternative you gave are semantically identical, but using make([]int, 0)
will result in an internal call to runtime.makeslice (Go 1.14).
You also have the option to leave it with a nil
value:
var myslice []int
As written in the Golang.org blog:
a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.
A nil
slice will however json.Marshal()
into "null"
whereas an empty slice will marshal into "[]"
, as pointed out by @farwayer.
None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.
I faced the same problem. This unix command is not able to find the main class. This is because the runtime and compile time JDK versions are different. Make the jar through eclipse after changing the java compiler version. The following link helped me.
Try running the jar created after this step and then execute it
Get cursor on top, where white header with file name, then press Alt. To set top menu by default always visible. You needed in top menu selected: FILE -> Config... -> autoHideMenuBar: true (change it to autoHideMenuBar: false) Save it.
Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();
export namespace Singleton {
export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";
SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason
I found out the hard way that if your listbox items are assigned via a data source
List<String> workTables = hhsdbutils.GetWorkTableNames();
listBoxWork.DataSource = workTables;
...you have to unbind that before doing the removal:
listBoxWork.DataSource = null;
for (int i = listBoxWork.Items.Count - 1; i >= 0; --i)
{
if (listBoxWork.Items[i].ToString().Contains(listboxVal))
{
listBoxWork.Items.RemoveAt(i);
}
}
Without the "listBoxWork.DataSource = null;
" line, I was getting, "Value does not fall within the expected range"
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
Do you really need that plugin? You can just animate the scrollTop
property:
$("#nav ul li a[href^='#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});
It is not possible to declare global variables in SQL Server. Sql server has a concept of global variables, but they are system defined and can not be extended.
obviously you can do all kinds of tricks with the SQL you are sending - SqlCOmmand has such a variable replacement mechanism for example - BEFORE you send it to SqlServer, but that is about it.
Use blur event to call your function when element loses focus :
$('#filter').blur(function() {
$('#options').hide();
});
An update to Adam's answer considering tryp's answer too. Don't have to instantiate a String in the loop.
public static URI appendUri(String uri, Map<String, String> parameters) throws URISyntaxException {
URI oldUri = new URI(uri);
StringBuilder queries = new StringBuilder();
for(Map.Entry<String, String> query: parameters.entrySet()) {
queries.append( "&" + query.getKey()+"="+query.getValue());
}
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = queries.substring(1);
} else {
newQuery += queries.toString();
}
URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
return newUri;
}
If you're using Python 3.5+, you can use jsons
to serialize and deserialize to plain old Python objects:
import jsons
response = request.POST
# You'll need your class attributes to match your dict keys, so in your case do:
response['id'] = response.pop('user_id')
# Then you can load that dict into your class:
user = jsons.load(response, FbApiUser)
user.save()
You could also make FbApiUser
inherit from jsons.JsonSerializable
for more elegance:
user = FbApiUser.from_json(response)
These examples will work if your class consists of Python default types, like strings, integers, lists, datetimes, etc. The jsons
lib will require type hints for custom types though.
root@APPLICATIOSERVER:/var/www/html# php connectiontest.php 61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#
Post declaring the proxy settings in the php script file issue has been fixed.
$proxy = '10.172.123.1:80'; curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port
public function updtitle()
{
$data = array(
'table_name' => 'your_table_name_to_update', // pass the real table name
'id' => $this->input->post('id'),
'title' => $this->input->post('title')
);
$this->load->model('Updmodel'); // load the model first
if($this->Updmodel->upddata($data)) // call the method from the model
{
// update successful
}
else
{
// update not successful
}
}
public function upddata($data) {
extract($data);
$this->db->where('emp_no', $id);
$this->db->update($table_name, array('title' => $title));
return true;
}
The active record query is similar to
"update $table_name set title='$title' where emp_no=$id"
powershell ".\MyScript.ps1" > test.log
I had the with a newly created F# project. The solution was to uncheck "Use standard resource names" in the project properties -> Application -> Resources / Specify how application resources will be managed. If you do not see the checkbox then update your Visual Studio! I have 15.6.7 installed. In 15.3.2 this checkbox is not there.
Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
If you invoke with
header('HTTP/1.0 403 Forbidden', true, 403);
the normal behavior of HTTP 403 as configured with Apache or any other server would follow.
Use System.currentTimeMillis() or System.nanoTime() if you want even more precise reading. Usually, milliseconds is precise enough if you need to output the value to the user. Moreover, System.nanoTime()
may return negative values, thus it may be possible that, if you're using that method, the return value is not correct.
A general and wide use would be to use milliseconds :
long start = System.currentTimeMillis();
...
long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
Note that nanoseconds are usually used to calculate very short and precise program executions, such as unit testing and benchmarking. Thus, for overall program execution, milliseconds are preferable.
use this function for copy to clipboard
public void copyToClipboard(String copyText) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(copyText);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("Your OTP", copyText);
clipboard.setPrimaryClip(clip);
}
Toast toast = Toast.makeText(getApplicationContext(),
"Your OTP is copied", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 50, 50);
toast.show();
//displayAlert("Your OTP is copied");
}
Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)
The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.
If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.
The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)
If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)
After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.
Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."
Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.
Thanks, and I hope this helps others who run into this issue!
Use GSON for converting POJO to JSONObject. Refer here.
For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.
// Instead Of
var index = arr.indexOf(200)
// Use
var index = arr.includes(200);
Please Note: Includes function is a simple instance method on the array and helps to easily find if an item is in the array(including NaN unlike indexOf)
my recommendation is
hikari > druid > UCP > c3p0 > DBCP
It's based on what I have tested - 20190202, in my local test environment(4GB mac/mysql in docker/pool minSize=1, maxSize=8), hikari can serve 1024 threads x 1024 times to get connections, average time for each thread to finish is 1 or 2 million seconds, while c3p0 can only serve 256 threads x 1024 times and average time for each thread is already 21 million seconds. (512 threads failed).
Try the fat-jar extension. It will include all external jars inside the jar.
If you aren’t using Auto Layout, have you tried setting the child view’s autoresize mask? Try this:
myChildeView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
Also, you may need to call
myParentView.autoresizesSubviews = YES;
to get the parent view to resize its subviews automatically when its frame changes.
If you’re still seeing the child view drawing outside of the parent view’s frame, there’s a good chance that the parent view is not clipping its contents. To fix that, call
myParentView.clipsToBounds = YES;
I know what you're trying to do, but why not simply do this:
$('div').addClass('hover');
The class is already defined in your CSS...
As for you original question, this has been asked before and it is not possible unfortunately. e.g. http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover
However, your desired functionality may be possible if your Stylesheet is defined in Javascript. see: http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/
Hope this helps!
If you add an AssemblyInfo class to your project and amend the AssemblyVersion
attribute to end with an asterisk, for example:
[assembly: AssemblyVersion("2.10.*")]
Visual studio will increment the final number for you according to these rules (thanks galets, I had that completely wrong!)
To reference this version in code, so you can display it to the user, you use reflection
. For example,
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
DateTime buildDate = new DateTime(2000, 1, 1)
.AddDays(version.Build).AddSeconds(version.Revision * 2);
string displayableVersion = $"{version} ({buildDate})";
It's also worth noting that if both AssemblyVersion
and AssemblyFileVersion
are specified, you won't see this on your .exe.
Setting only the 4th number to be *
can be bad, as the version won't always increment.
The 3rd number is the number of days since the year 2000, and the 4th number is the number of seconds since midnight (divided by 2) [IT IS NOT RANDOM]. So if you built the solution late in a day one day, and early in a day the next day, the later build would have an earlier version number. I recommend always using X.Y.*
instead of X.Y.Z.*
because your version number will ALWAYS increase this way.
(this thread begun in 2009)
The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation.
See this SO answer which explains how to remove determinism (https://stackoverflow.com/a/58101474/1555612)
None of the existing answers quite offers a simple solution that returns "the number of rows that are just duplicates and should be cut out". This is a one-size-fits-all solution that does:
# generate a table of those culprit rows which are duplicated:
dups = df.groupby(df.columns.tolist()).size().reset_index().rename(columns={0:'count'})
# sum the final col of that table, and subtract the number of culprits:
dups['count'].sum() - dups.shape[0]
For python 3, the default encoding would be "utf-8". Following steps are suggested in the base documentation:https://docs.python.org/2/library/csv.html#csv-examples in case of any problem
Create a function
def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')
Then use the function inside the reader, for e.g.
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data))
If the other answers don't work you can check if something else is using the port with netstat:
netstat -ano | findstr <your port number>
If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:
netsh interface ipv4 show excludedportrange protocol=tcp
just use this..................
public string GetIP()
{
string externalIP = "";
externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
return externalIP;
}
I also came across the same issue. I was trying to build the project with a clean install
goal. I simply changed it to clean package -o
in the run configuration. Then I re-built the project and it worked for me.
Add this code to onCreate
of your activity, it will print the hash under the KeyHash tag in your logCat
try {
PackageInfo info = getPackageManager().getPackageInfo(
getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
}
catch (NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}
You can add multiple hashkeys for your account, so if you been running in debug don't forget to run this again in release mode.
I have the same issue with the ".index()" method on lists. I have no issue with the fact that it throws an exception but I strongly disagree with the fact that it's a non-descriptive ValueError. I could understand if it would've been an IndexError, though.
I can see why returning "-1" would be an issue too because it's a valid index in Python. But realistically, I never expect a ".index()" method to return a negative number.
Here goes a one liner (ok, it's a rather long line ...), goes through the list exactly once and returns "None" if the item isn't found. It would be trivial to rewrite it to return -1, should you so desire.
indexOf = lambda list, thing: \
reduce(lambda acc, (idx, elem): \
idx if (acc is None) and elem == thing else acc, list, None)
How to use:
>>> indexOf([1,2,3], 4)
>>>
>>> indexOf([1,2,3], 1)
0
>>>
The standard procedures are:
int ? index = null;
public int Index
{
get
{
if (index.HasValue) // Check for value
return index.Value; //Return value if index is not "null"
else return 777; // If value is "null" return 777 or any other value
}
set { index = value; }
}
The concise version:
String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);
Add a try/catch block for a ParseException to ensure the format is a valid date.
In most versions of the JDK the two versions will be the same:
String s = new String("silly");
String s = "No longer silly";
Because strings are immutable the compiler maintains a list of string constants and if you try to make a new one will first check to see if the string is already defined. If it is then a reference to the existing immutable string is returned.
To clarify - when you say "String s = " you are defining a new variable which takes up space on the stack - then whether you say "No longer silly" or new String("silly") exactly the same thing happens - a new constant string is compiled into your application and the reference points to that.
I dont see the distinction here. However for your own class, which is not immutable, this behaviour is irrelevant and you must call your constructor.
UPDATE: I was wrong! Based on a down vote and comment attached I tested this and realise that my understanding is wrong - new String("Silly") does indeed create a new string rather than reuse the existing one. I am unclear why this would be (what is the benefit?) but code speaks louder than words!
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
How to Enable USB Debugging for LG Optimus (LGD415). Android version 4.4.2 (KitKat)
Go to this website and download the drivers to your phone:
http://www.lg.com/us/support/mobile-support
For example, mine would be:
http://www.lg.com/us/support-mobile/lg-LGD415RD. Then click on “Software Update & Drivers”
On your phone, you need to enable USB debugging. To do so,
Go to “Settings”.
Go to “About Phone”
Go to “Software Information”
Tap “Build number” five times.
A pop-up will appear saying “You are now a developer”. Your’re not done yet.
Go back to your phone’s home page by pushing the home button.
Go to “Settings”.
Go to “Developer options”
Click the “USB debugging- Turn on debug mode when USB is connected”. A blue checkmark will appear.
(EDIT: If USB Debugging is greyed out, unplug your phone. USB Debugging should no longer be greyed out. If it is not greyed out, check the box and plug your phone into your PC.)
Unplug your phone from your PC. Then plug it back in. On the pop-up, make sure you set it to “Media Sync (MTP)”.
Now your phone will show up on an option when you want to run your app in Eclipse.
(Look for dialog box on phone and agree to allow debugging connection with your computer.)
(Also, go to Control Panel | Device Manager and make sure there are TWO entries for your phone, similar to those expanded below.)
showbookimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/**
Here REQUEST_IMAGE is the unique integer value you can pass it any integer
**/
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
}
);
then u can now give the image a file name as follows and then convert it into bitmap and later on to file
private void createImageFile(Bitmap bitmap) throws IOException {
// Create an image file name
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
FileOutputStream stream = new FileOutputStream(image);
stream.write(bytes.toByteArray());
stream.close();
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
fileUri = image.getAbsolutePath();
Picasso.with(getActivity()).load(image).into(showbookimage);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == TAKE_PICTURE && resultCode== Activity.RESULT_OK && intent != null){
// get bundle
Bundle extras = intent.getExtras();
// get
bitMap = (Bitmap) extras.get("data");
// showbookimage.setImageBitmap(bitMap);
try {
createImageFile(bitMap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
use picasso for images to display rather fast
The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:
$.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
$('#orderDetails').html(data);
}, 'script')
Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:
<% @restaurant.orders.each do |order| %>
<!-- you should add more class and id attr to help control the DOM -->
<tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id %>);">
<td class="order_id"><%= order.id %></td>
<td class="customer_id"><%= order.customer_id %></td>
<td class="status"><%= order.status %></td>
</tr>
<% end %>
js:
function orderModal(order_id){
var tr = $('#order_' + order_id);
// get the current info in html table
var customer_id = tr.find('.customer_id');
var status = tr.find('.status');
// U should work on lines here:
var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
$('#orderDetails').html(info_to_insert);
$('#orderModal').modal({
keyboard: true,
backdrop: "static"
});
};
That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.
abarnert
's answer is very good and pythonic. Another completely different route (not in python) is to let bash do this for you:
$ python myscript.py > myoutput.txt
This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to file for more.
If you updated the android SDK, the licenses may have changed. Depending on how you did the update you may or may not have been prompted to accept the changes, or maybe it just doesn't save the fact that you did accept them in a way flutter can understand.
To resolve, try running
flutter doctor --android-licenses
This should prompt you to accept licenses (it may ask you first, in case just type y
and press enter - although it should tell you that).
If you still have problems after doing that, it might be worth either opening a new bug in the Flutter Github repository, or adding a comment on an existing issue like this one as it may be what you're seeing.
String.prototype.startsWith = function(needle)
{
return this.indexOf(needle) === 0;
};
Case insensitive:
var re = new RegExp("^(http|https)://", "i");
var str = "My String";
var match = re.test(str);
Here is great solution with dotts at the end with full words
function text_cut($text, $length = 200, $dots = true) {
$text = trim(preg_replace('#[\s\n\r\t]{2,}#', ' ', $text));
$text_temp = $text;
while (substr($text, $length, 1) != " ") { $length++; if ($length > strlen($text)) { break; } }
$text = substr($text, 0, $length);
return $text . ( ( $dots == true && $text != '' && strlen($text_temp) > $length ) ? '...' : '');
}
Input: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Output: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...
This is a more idiomatic alternative to the artificial state variable solutions:
$("#button_id").one('click', DoSomething);
function DoSomething() {
// do something.
$("#button_id").one('click', DoSomething);
}
One will only execute once (until attached again). More info here: http://docs.jquery.com/Events/one
C and C++ take a very abstract view of I/O, and there is no standard way of doing what you want. There are standard ways to get characters from the standard input stream, if there are any to get, and nothing else is defined by either language. Any answer will therefore have to be platform-specific, perhaps depending not only on the operating system but also the software framework.
There's some reasonable guesses here, but there's no way to answer your question without knowing what your target environment is.
To complete @GauravKachhadiya's answer :
IndexIgnore *.jpg
means "hide only .jpg extension files from indexing.
IndexIgnore directive uses wildcard expression to match against directories and files.
a star character , it matches any charactes in a string ,eg : foo or foo.extension, in the following example, we are going to turn off the directory listing, no files or dirs will appear in the index :
IndexIgnore *
Or if you want to hide spacific files , in the directory listing, then we can use
IndexIgnore *.php
*.php => matches a string that starts with any char and ends with .php
The example above hides all files that end with .php
It will work in IE7. But here you need to fixed the size
less than the number of option
and not use overflow-y:scroll
. In your example you have 2 option
but you set size=10
, which will not work.
Suppose your select has 10 option
, then fixed size=9
.
Here, in your code reference you used height:100px
with size:2
. I remove the height
css, because its not necessary and change the size:5
and it works fine.
Here is your modified code from jsfiddle:
<select size="5" style="width:100px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
this will generate a larger select box than size:2
create.In case of small size
the select box will not display the scrollbar,you have to check with appropriate size
quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2
and size
greater than 2
(e.g: 3,5).
Here is your desired result. I think this will help you:
CSS
.wrapper{
border: 1px dashed red;
height: 150px;
overflow-x: hidden;
overflow-y: scroll;
width: 150px;
}
.wrapper .selection{
width:150px;
border:1px solid #ccc
}
HTML
<div class="wrapper">
<select size="15" class="selection">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</div>
(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)
You need to enclose your code within this wrapper:
if _%1_==_payload_ goto :payload
:getadmin
echo %~nx0: elevating self
set vbs=%temp%\getadmin.vbs
echo Set UAC = CreateObject^("Shell.Application"^) >> "%vbs%"
echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
goto :eof
:payload
echo %~nx0: running payload with parameters:
echo %*
echo ---------------------------------------------------
cd /d %2
shift
shift
rem put your code here
rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof
This makes batch file run itself as elevated user. It adds two parameters to the privileged code:
word payload
, to indicate this is payload call, i.e. already elevated. Otherwise
it would just open new processes over and over.
directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)
Note: Unfortunately, for some reason shift
does not work for %*
, so if you need
to pass actual arguments on, you will have to resort to the ugly notation I used
in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9
), which also brings in the limit of
maximum of 9 arguments
If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels()
and ax.set_yticklabels()
:
import matplotlib.pyplot as plt
# Create Figure and Axes instances
fig,ax = plt.subplots(1)
# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')
# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])
plt.show()
If you have an access to php.ini, set expose_php = Off
.
You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:
$ /path/to/the/script.py > output.txt
This will overwrite the file. You can use >>
to append to it.
If you want errors to be logged in the file as well, use &>>
or &>
.
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
--allow-empty-message -m ''
(and -m ""
) fail in Git 2.29.2 on PowerShell:
error: switch `m' requires a value
(oddly enough, with a backtick on one side and a single quote on the other)
The following works consistently in Linux, PowerShell, and Command Prompt:
git commit --allow-empty-message --no-edit
The --no-edit
bit does the trick, as it prevents the editor from launching.
I find this form more explicit and a bit less hacky than forcing an empty message with -m ''
.
For result find: Click Here
Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.
You can do this by displaying a div (if you want to do it in a modal manner you could use blockUI - or one of the many other modal dialog plugins out there) prior to the request then just waiting until the call back succeeds as a quick example you can you $.getJSON as follows (you might want to use .ajax if you want to add proper error handling)
$("#ajaxLoader").show(); //Or whatever you want to do
$.getJSON("/AJson/Call/ThatTakes/Ages", function(result) {
//Process your response
$("#ajaxLoader").hide();
});
If you do this several times in your app and want to centralise the behaviour for all ajax calls you can make use of the global AJAX events:-
$("#ajaxLoader").ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
Using blockUI is similar for example with mark up like:-
<a href="/Path/ToYourJson/Action" id="jsonLink">Get JSON</a>
<div id="resultContainer" style="display:none">
And the answer is:-
<p id="result"></p>
</div>
<div id="ajaxLoader" style="display:none">
<h2>Please wait</h2>
<p>I'm getting my AJAX on!</p>
</div>
And using jQuery:-
$(function() {
$("#jsonLink").click(function(e) {
$.post(this.href, function(result) {
$("#resultContainer").fadeIn();
$("#result").text(result.Answer);
}, "json");
return false;
});
$("#ajaxLoader").ajaxStart(function() {
$.blockUI({ message: $("#ajaxLoader") });
})
.ajaxStop(function() {
$.unblockUI();
});
});
#generate matrix
matrix=[]
m=input('enter number of rows, m = ')
n=input('enter number of columns, n = ')
for i in range(m):
matrix.append([])
for j in range(n):
elem=input('enter element: ')
matrix[i].append(elem)
#print matrix
for i in range(m):
for j in range(n):
print matrix[i][j],
print '\n'
#generate transpose
transpose=[]
for j in range(n):
transpose.append([])
for i in range (m):
ent=matrix[i][j]
transpose[j].append(ent)
#print transpose
for i in range (n):
for j in range (m):
print transpose[i][j],
print '\n'
The better pattern is to create a standalone BroadcastReceiver
. This insures that your app can respond to the broadcast, whether or not the Service
is running. In fact, using this pattern may remove the need for a constant-running Service
altogether.
Register the BroadcastReceiver
in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent
(Bundle
) to the Service
, and respond to it in onStartCommand()
.
Eg:
public class FooReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}
I get this problem in Eclipse sometimes when importing an Android project that does not have a .classpath file. The one that Eclipse creates is not exactly the same one that Android expects. But, the Android .classpath files are usually all relative, so I just copy a correct .classpath file from another project over the incorrect .classpath. I've created a video that shows how I do this: https://www.youtube.com/watch?v=IVIhgeahS1Ynto
First, you really need to keep in mind that it's never impossible to reverse-engineer something. Everything is hackable. A smart developer using a smart IDE can already get far enough.
Well, you can find here a list. ProGuard is pretty good. I've used it myself, but only to "minify" Java code.
I've put this answer on a similar question that was marked as a duplicate of this question. The answer has helped a decent amount of people so I thought I'd add it here too in just in case.
This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).
Your html will look pretty similar to the normal radio button:
<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second
In your controller you'll have declared the mValue
that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope
variable associated with the group to the desired input's value:
$scope.mValue="second"
This makes the "second" radio button selected on loading the page.
I had this problem on ReactJS history push, turned out i was trying to open //link
(with double slashes)
I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl
to my mat-form-field
.
<form [formGroup]="questionsForm">
<ng-container *ngFor="let question of questions">
<mat-form-field [formControlName]="question.id" ngDefaultControl>
<mat-label>{{question.questionContent}}</mat-label>
<textarea matInput rows="3" required></textarea>
</mat-form-field>
</ng-container>
<button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
</form>
In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such
sendFeedbackAsAgent():void {
if (this.questionsForm.valid) {
console.log(this.questionsForm.value)
}
}
If you want to make sure that every implementation of the interface contains specific field, you simply need to add to your interface the getter for that field:
interface IMyMessage(){
@NonNull String getReceiver();
}
Receiver
object has to be passed to the class in some way (either by constructor or by setter)I have been using one machine to push code to two different GitHub accounts with different username. Assuming you already set up one account and want to add a new one:
ssh-keygen -t rsa -C "[email protected]"
id_rsa
. Give it a different name, e.g. id_rsa_another
Settings -> SSH and GPG keys -> New SSH key -> Give a label and paste the key -> Add SSH key
ssh-add ~/.ssh/id_rsa_another
touch ~/.ssh/config
and edit the file by providing configurations to your accounts:#first account
Host github.com-first
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa
#another account
Host github.com-another
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_another
Now you should be able to push from different accounts depending on what key you add to the ssh agent, i.e. to use your first account, do
ssh-add ~/.ssh/id_rsa
.
You might also want to change your user email:
git config --global user.email "[email protected]"
or clean out ssh keys in case of permission error when pusing code to one of the accounts:
ssh-add -D
I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:
function isMobileDevice(){
$aMobileUA = array(
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
//Return true if Mobile User Agent is detected
foreach($aMobileUA as $sMobileKey => $sMobileOS){
if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
return true;
}
}
//Otherwise return false..
return false;
}
Swift is statically typed so the performSelector:
methods are to fall by the wayside.
Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.
EDIT: the relevant performSelector:
is also notably missing from the Swift version of the NSRunLoop
documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject
I'd argue it's pretty clear what Apple is thinking here.
Just say :
git commit --amend -m "New commit message"
and then
git push --force
What had caused this error on my side was the following line
include_once dirname(__FILE__) . './Config.php';
I managed to realize it was the culprit when i added the lines:
//error_reporting(E_ALL | E_DEPRECATED | E_STRICT);
//ini_set('display_errors', 1);
to all my php files.
To solve the path issue
i canged the offending line to:
include_once dirname(__FILE__) . '/Config.php';