I think rake must be preinstalled if you want work with bundler. Try to install rake via 'gem install' and then run 'bundle install' again:
gem install rake && bundle install
If you are using rvm ( http://rvm.io ) rake is installed by default...
Try installing NodeJS and try again.
https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager
I also had this issue, where trying to run in production without precompiling it would still throw not-precompiled errors. I had to change which line was commented application.rb:
# If you precompile assets before deploying to production, use this line
# Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
Bundler.require(:default, :assets, Rails.env)
I had this same error but only on my staging server not my production environment. nodejs was already installed on both environments.
By typing:
which node
I found out that the node command was located in: /usr/bin/node on production but: /usr/local/bin/node in staging.
After creating a symlink on staging i.e. :
sudo ln -s /usr/local/bin/node /usr/bin/node
the application then worked in staging.
No muss no fuss.
As far as I know, display: inline-block
is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.
Most of these answers circulate around removing a file from the "staging area" pre-commit, but I often find myself looking here after I've already committed and I want to remove some sensitive information from the commit I just made.
An easy to remember trick for all of you git commit --amend
folks out there like me is that you can:
git add .
to add the deletion to the "staging area"git commit --amend
to remove the file from the previous commit.You will notice in the commit message that the unwanted file is now missing. Hooray! (Commit SHA
will have changed, so be careful if you already pushed your changes to the remote.)
I have encountered the same problem and in my case it was happening as a result of this problem:
I had the controllers defined in a separate module (called 'myApp.controllers') and injected to the main app module (called 'myApp') like this:
angular.module('myApp', ['myApp.controllers'])
A colleague pushed another controller module in a separate file but with the exact same name as mine (i.e. 'myApp.controllers' ) which caused this error. I think because Angular got confused between those controller modules. However the error message was not very helpful in discovering what is going wrong.
Simple JAVA code to calculate cosine similarity
/**
* Method to calculate cosine similarity of vectors
* 1 - exactly similar (angle between them is 0)
* 0 - orthogonal vectors (angle between them is 90)
* @param vector1 - vector in the form [a1, a2, a3, ..... an]
* @param vector2 - vector in the form [b1, b2, b3, ..... bn]
* @return - the cosine similarity of vectors (ranges from 0 to 1)
*/
private double cosineSimilarity(List<Double> vector1, List<Double> vector2) {
double dotProduct = 0.0;
double normA = 0.0;
double normB = 0.0;
for (int i = 0; i < vector1.size(); i++) {
dotProduct += vector1.get(i) * vector2.get(i);
normA += Math.pow(vector1.get(i), 2);
normB += Math.pow(vector2.get(i), 2);
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
You’ll want to do:
UIImage(data: data)
In Swift, they’ve replaced most Objective C factory methods with regular constructors.
See:
Updated 2018
For the original question based on Bootstrap 3, the solution was to use push-pull.
In Bootstrap 4 it's now possible to change the order, even when the columns are full-width stacked vertically, thanks to Bootstrap 4 flexbox. OFC, the push pull method will still work, but now there are other ways to change column order in Bootstrap 4, making it possible to re-order full-width columns.
Method 1 - Use flex-column-reverse
for xs
screens:
<div class="row flex-column-reverse flex-md-row">
<div class="col-md-3">
sidebar
</div>
<div class="col-md-9">
main
</div>
</div>
Method 2 - Use order-first
for xs
screens:
<div class="row">
<div class="col-md-3">
sidebar
</div>
<div class="col-md-9 order-first order-md-last">
main
</div>
</div>
Bootstrap 4(alpha 6): http://www.codeply.com/go/bBMOsvtJhD
Bootstrap 4.1: https://www.codeply.com/go/e0v77yGtcr
Original 3.x Answer
For the original question based on Bootstrap 3, the solution was to use push-pull for the larger widths, and then the columns will show is their natural order on smaller (xs) widths. (A-B reverse to B-A).
<div class="container">
<div class="row">
<div class="col-md-9 col-md-push-3">
main
</div>
<div class="col-md-3 col-md-pull-9">
sidebar
</div>
</div>
</div>
Bootstrap 3: http://www.codeply.com/go/wgzJXs3gel
@emre stated, "You cannot change the order of columns in smaller screens but you can do that in large screens". However, this should be clarified to state: "You cannot change the order of full-width "stacked" columns.." in Bootstrap 3.
Lets start with 3. That wouldnt work. public getMyProperty()
has no return typ.
And number 1 and 2 are actually same things. 2 is what number 1 becomes after compilation.
So 1 and 2 are same things. with two you can have some validation or caching in your model.
other than that they become same.
Your JRE_HOME does not need to point to the "bin" directory. Just set it to C:\Program Files\Java\jre1.8.0_25
Edit:
It actually just occurred to me that in Xcode 7b4, UI testing now has
expectationForPredicate:evaluatedWithObject:handler:
Original:
Another way is to spin the run loop for a set amount of time. Really only useful if you know how much (estimated) time you'll need to wait for
Obj-C:
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow: <<time to wait in seconds>>]]
Swift:
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: <<time to wait in seconds>>))
This is not super useful if you need to test some conditions in order to continue your test. To run conditional checks, use a while
loop.
Just use the modulus
loop through the list and run the following on each item
if(num % 2 == 0)
{
//is even
}
else
{
//is odd
}
Alternatively if you want to know if all are even you can do something like this:
bool allAreEven = lst.All(x => x % 2 == 0);
I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:
there are cases when object construction is a task complex enough to justify its extraction to another class.
That class is in fact a Builder, rather than a Factory.
In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.
Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.
This also eliminates the issues related to return-by-value.
Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.
Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.
If you are after the "perfect" factory implementation, well, good luck.
build
and listener
objects are presenting during system groovy execution. You can do this:
def myVar = build.getEnvironment(listener).get('myVar')
If you are encountering the error/warning when you're running a program that uses log4j, the solution is to add a log4j.properties that can be seen by the class loader. Normally it's in the "src" folder of your Java project: Add the following contents to the file
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
I had it when I did so :
function foo() (...) export default foo
correctly:
export default () =>(...);
or
const foo = ...
export default foo
Another example if you are using Titanium Alloy:
collection.fetch({
data: {
where : JSON.stringify({
page: 1
})
}
});
I believe the only way is to get a list from the iterator then get the element you want from that list.
l = list(myfunct())
l[4]
You could use animation like this:
-webkit-animation: spin 1s infinite linear;
@-webkit-keyframes spin {
0% {-webkit-transform: rotate(0deg)}
100% {-webkit-transform: rotate(360deg)}
}
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
You haven't created a user db
. If its just a fresh install, the default user is postgres
and the password should be blank. After you access it, you can create the users you need.
I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):
aptitude install debian-archive-keyring
In case it is some other keyring you need, check out
apt-cache search keyring | grep debian
My squeeze system shows all these:
debian-archive-keyring - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring - GnuPG archive keys of the Debian Edu archive
debian-keyring - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring - GnuPG archive keys for the emdebian repository
Here is a slightly different approach to read-only properties, which perhaps should be called write-once properties since they do have to get initialized, don't they? For the paranoid among us who worry about being able to modify properties by accessing the object's dictionary directly, I've introduced "extreme" name mangling:
from uuid import uuid4
class ReadOnlyProperty:
def __init__(self, name):
self.name = name
self.dict_name = uuid4().hex
self.initialized = False
def __get__(self, instance, cls):
if instance is None:
return self
else:
return instance.__dict__[self.dict_name]
def __set__(self, instance, value):
if self.initialized:
raise AttributeError("Attempt to modify read-only property '%s'." % self.name)
instance.__dict__[self.dict_name] = value
self.initialized = True
class Point:
x = ReadOnlyProperty('x')
y = ReadOnlyProperty('y')
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
try:
p = Point(2, 3)
print(p.x, p.y)
p.x = 9
except Exception as e:
print(e)
int myInt = (int)Math.Ceiling(myDouble);
UPDATE Warning, this answer is extremely out of date now that OData V4 is available.
I wrote a post on the subject a while ago here.
As Franci said, OData is based on Atom Pub. However, they have layered some functionality on top and unfortunately have ignored some of the REST constraints in the process.
The querying capability of an OData service requires you to construct URIs based on information that is not available, or linked to in the response. It is what REST people call out-of-band information and introduces hidden coupling between the client and server.
The other coupling that is introduced is through the use of EDMX metadata to define the properties contained in the entry content. This metadata can be discovered at a fixed endpoint called $metadata. Again, the client needs to know this in advance, it cannot be discovered.
Unfortunately, Microsoft did not see fit to create media types to describe these key pieces of data, so any OData client has to make a bunch of assumptions about the service that it is talking to and the data it is receiving.
Try using:
if(NewType* v = dynamic_cast<NewType*>(old)) {
// old was safely casted to NewType
v->doSomething();
}
This requires your compiler to have rtti support enabled.
EDIT: I've had some good comments on this answer!
Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.
Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).
As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.
if(old->getType() == BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.
Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:
// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
Step 1 :
Create ts : app/_helpers/must-match.validator.ts
import { FormGroup } from '@angular/forms';
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
Step 2 :
Use in your component.ts
import { MustMatch } from '../_helpers/must-match.validator';
ngOnInit() {
this.loginForm = this.formbuilder.group({
Password: ['', [Validators.required, Validators.minLength(6)]],
ConfirmPassword: ['', [Validators.required]],
}, {
validator: MustMatch('Password', 'ConfirmPassword')
});
}
Step 3 :
Use In View/Html
<input type="password" formControlName="Password" class="form-control" autofocus>
<div *ngIf="loginForm.controls['Password'].invalid && (loginForm.controls['Password'].dirty || loginForm.controls['Password'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['Password'].errors.required">Password Required. </div>
<div *ngIf="loginForm.controls['Password'].errors.minlength">Password must be at least 6 characters</div>
</div>
<input type="password" formControlName="ConfirmPassword" class="form-control" >
<div *ngIf="loginForm.controls['ConfirmPassword'].invalid && (loginForm.controls['ConfirmPassword'].dirty || loginForm.controls['ConfirmPassword'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.required">ConfirmPassword Required. </div>
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.mustMatch">Your password and confirmation password do not match.</div>
</div>
Please try running
brew install docker
This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.
If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:
brew install --cask docker
open /Applications/Docker.app
You can use JavaScripts Fetch API (available in your browser) to make network requests.
If using node, you will need to install the node-fetch package.
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
I would be inclined to include the year in the output. One way:
select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1
Another way (more standard SQL):
select extract(year from date_created) as yr, extract(month from date_created) as mon,
sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;
Remember the order by, since you presumably want these in order, and there is no guarantee about the order that rows are returned in after a group by.
Try this way ->
Firstly create a class TimeTask that run your task, it looks like:
public class CustomTask extends TimerTask {
public CustomTask(){
//Constructor
}
public void run() {
try {
// Your task process
} catch (Exception ex) {
System.out.println("error running thread " + ex.getMessage());
}
}
}
then in main class you instantiate the task and run it periodically started by a specified date:
public void runTask() {
Calendar calendar = Calendar.getInstance();
calendar.set(
Calendar.DAY_OF_WEEK,
Calendar.MONDAY
);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timer time = new Timer(); // Instantiate Timer Object
// Start running the task on Monday at 15:40:00, period is set to 8 hours
// if you want to run the task immediately, set the 2nd parameter to 0
time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}
This problem drives me crazy as well but I know what the cause of it is. The problem is that eclipse is not smart enough to create a folder with the same name of your project within your workspace folder if it is custom.
The way to solve this is to make sure all of your projects are in a folder with the name that matches your Project Name, otherwise it will dump all of your project files straight into the directory. The reason why you end up seeing that error is because it thinks you are putting a project inside another project (probably reads the project config file).
I noticed this is especially a problem when not using the default workspace path. The way I solve this problem is to just add the Project Name to the end of location. So let's say you are putting a project named "HelloWorld" into /Users/name/Documents/projects/android/, you would want to manually add "HelloWorld" to the end of it, like this: /Users/name/Documents/projects/android/HelloWorld. This would ensure that the project is put in it's own folder called "HelloWorld" and not inside some other project. Be sure that if there are any projects not within folders into a folder of the same name as the project to solve the errors.
Press Shift twice and a Search Everywhere dialog will appear.
check $xml->entry[$i] exists and is an object before trying to get a property of it
if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
$source = $xml->entry[$i]->source;
$s[$source] += 1;
}
or $source might not be a legal array offset but an array, object, resource or possibly null
In Flutter
Update version:1.0.0+1 in pubspec.yaml.
The default version number of the app is 1.0.0. To update it, navigate to the pubspec.yaml
file and update the following line:
version: 1.0.0+1
+1 (the number after the +) represents the versionCode such as 1, 2, 3, etc.
So increase it one by one, like this
version: 1.0.1+2
The version number is three numbers separated by dots, such as 1.0.0 in the example above, followed by an optional build number such as 1 in the example above, separated by a +.
Both the version and the build number may be overridden in Flutter’s build by specifying --build-name and --build-number, respectively.
In Android, build-name is used as versionName while build-number used as versionCode. For more information, see Version your app
After updating the version number in the pubspec file
, run flutter pub
get from the top of the project, or use the Pub get button in your IDE. This updates the versionName
and versionCode
in the local.properties
file, which are later updated in the build.gradle
file when you rebuild the Flutter app.
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.
Thanks , but i found an alternative solution using ffmpeg:
def save():
os.system("ffmpeg -r 1 -i img%01d.png -vcodec mpeg4 -y movie.mp4")
But thank you for your help :)
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
LastRow = ActiveSheet.UsedRange.Rows.Count
If you're only getting these to manually pass into df.set_index()
, that's unnecessary. Just directly do df.set_index['your_col_name', drop=False]
, already.
It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.
If you don't mind using a 3rd party library, SequenceM
from cyclops-streams (and LazyFutureStream
from simple-react) both a have single & singleOptional operators.
singleOptional()
throws an exception if there are 0
or more than 1
elements in the Stream
, otherwise it returns the single value.
String result = SequenceM.of("x")
.single();
SequenceM.of().single(); // NoSuchElementException
SequenceM.of(1, 2, 3).single(); // NoSuchElementException
String result = LazyFutureStream.fromStream(Stream.of("x"))
.single();
singleOptional()
returns Optional.empty()
if there are no values or more than one value in the Stream
.
Optional<String> result = SequenceM.fromStream(Stream.of("x"))
.singleOptional();
//Optional["x"]
Optional<String> result = SequenceM.of().singleOptional();
// Optional.empty
Optional<String> result = SequenceM.of(1, 2, 3).singleOptional();
// Optional.empty
Disclosure - I am the author of both libraries.
First of all, it will 100% work........
onResume()
method.onResume()
find the view which is focusing again and again by findViewById()
.onResume()
set requestFocus()
to this view.onResume()
set clearFocus
to this view.focusable
true and focusableInTuch
true.onResume()
find the above top view by findViewById
onResume()
set requestFocus()
to this view at the last.I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="ie7.css" />
<![endif]-->
Since id is an attribute don't create an id element, just do this:
myPara.setAttribute("id", "id_you_like");
Use:
/category[@name='Sport' and author/text()[1]='James Small']
or use:
/category[@name='Sport' and author[starts-with(.,'James Small')]]
It is a good rule to try to avoid using the //
pseudo-operator whenever possible, because its evaluation can typically be very slow.
Also:
./somename
is equivalent to:
somename
so it is recommended to use the latter.
You should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least two spaces).
Here is a code sample with your three keywords working fine:
Here is the file ts.txt
:
*** test cases ***
mytest
${color} = set variable Red
Run Keyword If '${color}' == 'Red' log to console \nexecuted with single condition
Run Keyword If '${color}' == 'Red' or '${color}' == 'Blue' or '${color}' == 'Pink' log to console \nexecuted with multiple or
${color} = set variable Blue
${Size} = set variable Small
${Simple} = set variable Simple
${Design} = set variable Simple
Run Keyword If '${color}' == 'Blue' and '${Size}' == 'Small' and '${Design}' != '${Simple}' log to console \nexecuted with multiple and
${Size} = set variable XL
${Design} = set variable Complicated
Run Keyword Unless '${color}' == 'Black' or '${Size}' == 'Small' or '${Design}' == 'Simple' log to console \nexecuted with unless and multiple or
and here is what I get when I execute it:
$ pybot ts.txt
==============================================================================
Ts
==============================================================================
mytest .
executed with single condition
executed with multiple or
executed with unless and multiple or
mytest | PASS |
------------------------------------------------------------------------------
If you have a code like
int arr[10] = {0, 5, 3, 64};
, and you want to append or add a value to next index, you can simply add it by typing a[5] = 5
.
The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8
to index 9, I can do it by the above concept prior to filling up before indices.
But in python by using list.append()
you can do it by continued indices.
Upgrading from 2.2.x to 3.0.x -- reason post method fails. If you are upgrading CI 3.x, need to keep the index_page in config file. Also check the .htaccess file for mod_rewrite. CI_3.x
$config['index_page'] = ''; // ci 2.x
$config['index_page'] = 'index.php'; // ci 3.x
My .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>
Have a go with these code:
>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")
xs:boolean
is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:
<xs:simpleType name="my:boolean">
<xs:restriction base="xs:string">
<xs:enumeration value="True"/>
<xs:enumeration value="False"/>
</xs:restriction>
</xs:simpleType>
that's why Idon't like NULL values in the database at all.
I hope you are having it for a reason.
if ($_POST['location_id'] === '') {
$location_id = 'NULL';
} else {
$location_id = "'".$_POST['location_id']."'";
}
$notes = mysql_real_escape_string($_POST['notes']);
$ipid = mysql_real_escape_string($_POST['ipid']);
$sql="UPDATE addresses
SET notes='$notes', location_id=$location_id
WHERE ipid = '$ipid'";
echo $sql; //to see different queries this code produces
// and difference between NULL and 'NULL' in the query
int column(0), row(0), index(0);
Note that this form will work with custom types too, especially when their constructors take more than one argument.
You can also simply write
if (dt.Rows.Count == 0)
{
//DataTable does not contain records
}
Is this what you want:
>>> d={'a':1,'b':2,'c':3}
>>> default_val=99
>>> for k in d:
... d[k]=default_val
...
>>> d
{'a': 99, 'b': 99, 'c': 99}
>>>
>>> d={'a':1,'b':2,'c':3}
>>> from collections import defaultdict
>>> d=defaultdict(lambda:99,d)
>>> d
defaultdict(<function <lambda> at 0x03D21630>, {'a': 1, 'c': 3, 'b': 2})
>>> d[3]
99
In the beginning, a compiler was responsible for turning a high-level language (defined as higher level than assembler) into object code (machine instructions), which would then be linked (by a linker) into an executable.
At one point in the evolution of languages, compilers would compile a high-level language into pseudo-code, which would then be interpreted (by an interpreter) to run your program. This eliminated the object code and executables, and allowed these languages to be portable to multiple operating systems and hardware platforms. Pascal (which compiled to P-Code) was one of the first; Java and C# are more recent examples. Eventually the term P-Code was replaced with bytecode, since most of the pseudo-operations are a byte long.
A Just-In-Time (JIT) compiler is a feature of the run-time interpreter, that instead of interpreting bytecode every time a method is invoked, will compile the bytecode into the machine code instructions of the running machine, and then invoke this object code instead. Ideally the efficiency of running object code will overcome the inefficiency of recompiling the program every time it runs.
Navigate to the project root of the local repository and check for existing remotes:
git remote -v
If your repository is using SSH you will see something like:
> origin [email protected]:USERNAME/REPOSITORY.git (fetch)
> origin [email protected]:USERNAME/REPOSITORY.git (push)
And if your repository is using HTTPS you will see something like:
> origin https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin https://github.com/USERNAME/REPOSITORY.git (push)
Changing the URL is done with git remote set-url
. Depending on the output of git remote -v
, you can change the URL in the following manner:
In case of SSH, you can change the URL from REPOSITORY.git
to NEW_REPOSITORY.git
like:
$ git remote set-url origin [email protected]:USERNAME/NEW_REPOSITORY.git
And in case of HTTPS, you can change the URL from REPOSITORY.git
to NEW_REPOSITORY.git
like:
$ git remote set-url origin https://github.com/USERNAME/NEW_REPOSITORY.git
NOTE: If you've changed your GitHub username, you can follow the same process as above to update the change in the username associated with your repository. You would only have to update the USERNAME
in the git remote set-url
command.
I am currently using Rob de la Cruz's reply:
Object.keys(obj)
And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.
if (!Object.keys) {
Object.keys = function(object) {
var keys = [];
for (var o in object) {
if (object.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.
Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.
My problem was the following line (HAML):
%a{"href"=>"#", "ng-click" => "showConfirmDeleteModal()"} Delete
Notice that I have a angular ng-click
and I have an href
tag which will jump to #
which is the same page. I just had to remove the href
tag and I was good to go.
If it doesn't require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START
net stop "DNS Client"
net start "DNS client"
or if you want to get a little more sophisticated, you could try Powershell
You can create a custom link as described here using a small jQuery script
$('.linkPinIt').click(function(){
var url = $(this).attr('href');
var media = $(this).attr('data-image');
var desc = $(this).attr('data-desc');
window.open("//www.pinterest.com/pin/create/button/"+
"?url="+url+
"&media="+media+
"&description="+desc,"_blank","top=0,right=0,width=750,height=320");
return false;
});
this will work for all links with class linkPinIt
which have the image and the description stored in the HTML 5 data attributes data-image
and data-desc
<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F"
data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg"
data-desc="Title for Pinterest Photo" class="linkPinIt">
Pin it!
</a>
see this jfiddle example
You need an event handler which will fire when the button is clicked. Here is a quick way -
var button = new Button();
button.Text = "my button";
this.Controls.Add(button);
button.Click += (sender, args) =>
{
MessageBox.Show("Some stuff");
Close();
};
But it would be better to understand a bit more about buttons, events, etc.
If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:
this.button1.Click += new System.EventHandler(this.button1_Click);
You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:
this.button1.Location = new System.Drawing.Point(128, 214);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
As for closing the Form, it is as easy as putting Close(); within your event handler:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("some text");
Close();
}
Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.
Which is alluded to on the geom_smooth()
page with:
"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".
It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.
If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()
MkdirAll
creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.
The path_test.go is a good illustration on how to use it:
func TestMkdirAll(t *testing.T) {
tmpDir := TempDir()
path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
err := MkdirAll(path, 0777)
if err != nil {
t.Fatalf("MkdirAll %q: %s", path, err)
}
defer RemoveAll(tmpDir + "/_TestMkdirAll_")
...
}
(Make sure to specify a sensible permission value, as mentioned in this answer)
you can use this code
$a = '';
if(!empty($a))
echo 'text';
If you are trying to make more than just one folder on the root of the sdcard,
ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"
then instead of folder.mkdir()
you would use folder.mkdirs()
I've made this mistake in the past & I took forever to figure it out.
A quick and copy/paste you can use for Chrome and Firefox would be: (change the stuff after the # to change the color)
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
-border-radius: 10px;
-moz-box-shadow: 0 0 15px 5px #666;
-webkit-box-shadow: 0 0 15px 05px #666;
Matt Roberts' answer is correct for webkit browsers (safari, chrome, etc), but I thought someone out there might want a quick answer rather than be told to learn to program to make some shadows.
A void* can point to anything (it's a raw pointer without any type info).
You need to escape those but don't just replace it by %2F
manually. You can use URLEncoder
for this.
Eg URLEncoder.encode(url, "UTF-8")
Then you can say
yourUrl = "www.musicExplained/index.cfm/artist/" + URLEncoder.encode(VariableName, "UTF-8")
UPDATE TABLE_NAME SET COLUMN_A = COLUMN_B;
Much easier. At least on Oracle SQL, i don't know if this works on other dialects as well.
new java.util.Timer().schedule(new TimerTask(){
@Override
public void run() {
System.out.println("Executed...");
//your code here
//1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly
}
},1000*5,1000*5);
SevenZipSharp is another solution. Creates 7-zip archives...
The same can be done without DataTrigger
too:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" >
<Setter.Value>
<Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
<Binding.ConverterParameter>
<x:Array Type="SolidColorBrush">
<SolidColorBrush Color="{StaticResource RedColor}"/>
<SolidColorBrush Color="{StaticResource TransparentColor}"/>
</x:Array>
</Binding.ConverterParameter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
Where BooleanToBrushConverter
is the following class:
public class BooleanToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.Transparent;
Brush[] brushes = parameter as Brush[];
if (brushes == null)
return Brushes.Transparent;
bool isTrue;
bool.TryParse(value.ToString(), out isTrue);
if (isTrue)
{
var brush = (SolidColorBrush)brushes[0];
return brush ?? Brushes.Transparent;
}
else
{
var brush = (SolidColorBrush)brushes[1];
return brush ?? Brushes.Transparent;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
This isn't exactly an answer, but some useful/related code I made. When you run it and enter any character in the command line it returns getNumericValue(char)
... which doesn't seem to be the same as the ASCII table so be aware. Anyways, not a direct answer to your question but hopefully helpful:
import java.lang.*;
import java.util.*;
/* charVal.java
*/
//infinite loops. whenever you type in a character gives you value of
//getNumericValue(char)
//
//ctrl+c to exit
public class charVal {
public static void main(String[] args) {
Scanner inPut = new Scanner(System.in);
for(;;){
char c = inPut.next().charAt(0);
System.out.printf("\n %s = %d \n", c, Character.getNumericValue(c));
}
}
}
This is a simple copy, just like you would do with memcpy()
(indeed, some compilers actually produce a call to memcpy()
for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.
Just Try to do like this....
SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();
// Add this code
if(userCache != null)
{
userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null
userListComboBox.DisplayMember = "Key";
userListComboBox.ValueMember = "Value";
}
[[UIDevice currentDevice] uniqueIdentifier]
Returns the Unique ID of your iPhone.
EDIT:
-[UIDevice uniqueIdentifier]
is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.
If you need to create several UUID, just use this method (with ARC):
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string;
}
EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:
NSString *UUID = [[NSUUID UUID] UUIDString];
setForeground
is added in API level 23. Leverage the power of RevealAnimator
in case u need to relay on foreground
property !
<View
android:id="@+id/circular_reveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/primaryMilk_22"
android:elevation="@dimen/margin_20"
android:visibility="invisible" />
With kotlin ext function, it's way osm !
fun View.circularReveal() {
val cx: Int = width / 2
val cy: Int = height / 2
val finalRadius: Int =
width.coerceAtLeast(height)
val anim: Animator = ViewAnimationUtils.createCircularReveal(
this,
cx,
cy,
0f,
finalRadius.toFloat()
)
anim.interpolator = AccelerateDecelerateInterpolator()
anim.duration = 400
isVisible = true
anim.start()
anim.doOnEnd {
isVisible = false
}
}
You can't pass objects using router params, only strings because it needs to be reflected in the URL. It would be probably a better approach to use a shared service to pass data around between routed components anyway.
The old router allows to pass data
but the new (RC.1
) router doesn't yet.
Update
data
was re-introduced in RC.4
How do I pass data in Angular 2 components while using Routing?
you can do this very easy by using following in sudo vi /etc/nginx/sites-available/default
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _ your_domain;
location /health {
access_log off;
return 200 "healthy\n";
}
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}
Seems that EditText apply the hintTextColor only if the text is empty. So simple solution will be like this
Editable text = mEditText.getText();
mEditText.setText(null);
mEditText.setHintTextColor(color);
mEditText.setText(text);
If you have multiple fields, you can extend the EditText and write a method which executes this logic and use that method instead.
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
When TOP
is used with INSERT
, UPDATE
, MERGE
, or DELETE
, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in these statements. If you need to use TOP to insert, delete, or modify rows in a meaningful chronological order, you must use TOP
together with an ORDER BY
clause that is specified in a subselect statement.
TOP
cannot be used in an UPDATE
and DELETE
statements on partitioned views.
TOP
cannot be combined with OFFSET
and FETCH
in the same query expression (in the same query scope). For more information, see http://technet.microsoft.com/en-us/library/ms189463.aspx
First of all, find where the main apache’s config file httpd.conf is located. If you use Debian, it should be here: /etc/apache/httpd.conf
. Using some file editor like Vim or Nano open this file and find the line that looks as follows:
Options Includes Indexes FollowSymLinks MultiViews
then remove word Indexes and save the file. The line should look like this one:
Options Includes FollowSymLinks MultiViews
After it is done, restart apache (e.g. /etc/init.d/apache restart in Debian). That’s it!
Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.
If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)
am startservice <INTENT>
or actually from the OS shell
adb shell am startservice <INTENT>
Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:
In public class Startup
add a property
public IConfigurationRoot Configuration { get; }
And then add a singleton IHttpContextAccessor to DI in ConfigureServices.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
Then in Configure
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
)
{
add the DI Parameter IServiceProvider svp
, so the method looks like:
public void Configure(
IApplicationBuilder app
,IHostingEnvironment env
,ILoggerFactory loggerFactory
,IServiceProvider svp)
{
Next, create a replacement class for System.Web:
namespace System.Web
{
namespace Hosting
{
public static class HostingEnvironment
{
public static bool m_IsHosted;
static HostingEnvironment()
{
m_IsHosted = false;
}
public static bool IsHosted
{
get
{
return m_IsHosted;
}
}
}
}
public static class HttpContext
{
public static IServiceProvider ServiceProvider;
static HttpContext()
{ }
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
// var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
// Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
// context.Response.WriteAsync("Test");
return context;
}
}
} // End Class HttpContext
}
Now in Configure, where you added the IServiceProvider svp
, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)
and set HostingEnvironment.IsHosted to true
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
ServiceProvider = svp;
System.Web.HttpContext.ServiceProvider = svp;
System.Web.Hosting.HostingEnvironment.m_IsHosted = true;
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest
, CookieHttpOnly=false
});
Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start
in global.asax.
I stress again, this only works if you actually added
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.
Perhaps a more maintainable method would be adding this helper class
namespace System.Web
{
public static class HttpContext
{
private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
{
m_httpContextAccessor = httpContextAccessor;
}
public static Microsoft.AspNetCore.Http.HttpContext Current
{
get
{
return m_httpContextAccessor.HttpContext;
}
}
}
}
And then calling HttpContext.Configure in Startup->Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
System.Web.HttpContext.Configure(app.ApplicationServices.
GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
);
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
I found a solution that works for hiding the grid lines in a Line chart.
Set the gridLines
color to be the same as the div's background color.
var options = {
scales: {
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
yAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
}
or use
var options = {
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
}
Java includes a scripting language extension package starting with version 6.
See the Rhino project documentation for embedding a JavaScript interpreter in Java.
[Edit]
Here is a small example of how you can expose Java objects to your interpreted script:
public class JS {
public static void main(String args[]) throws Exception {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings = js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("stdout", System.out);
js.eval("stdout.println(Math.cos(Math.PI));");
// Prints "-1.0" to the standard output stream.
}
}
You could also use Format$(Now(), "Short Date") or whatever date format you want. Be aware, this function will return the Date as a string, so using Date() is a better approach.
Did you know that JavaScript has it's built-in methods and libs to create forms and submit them?
I am seeing a lot of replies here all asking to use a 3rd party library which I think is an overkill.
I would do the following in pure Javascript:
<script>
function launchMyForm()
{
var myForm = document.createElement("FORM");
myForm.setAttribute("id","TestForm");
document.body.appendChild(myForm);
// this will create a new FORM which is mapped to the Java Object of myForm, with an id of TestForm. Equivalent to: <form id="TestForm"></form>
var myInput = document.createElement("INPUT");
myInput.setAttribute("id","MyInput");
myInput.setAttribute("type","text");
myInput.setAttribute("value","Heider");
document.getElementById("TestForm").appendChild(myInput);
// This will create an INPUT equivalent to: <INPUT id="MyInput" type="text" value="Heider" /> and then assign it to be inside the TestForm tags.
}
</script>
This way (A) you don't need to rely on 3rd parties to do the job. (B) It's all built-in to all browsers, (C) faster, (D) it works, feel free to try it out.
I hope this helps. H
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
I believe the top answer successfully redirects non-www to www (ex: mysite.com -> www.mysite.com), but doesn't take into account wildcard subdomains, which results in:
random.mysite.com -> www.random.mysite.com
Here's a solution with/without HTTPS
HTTP
RewriteEngine On
RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://www.mysite.com/$1 [L,R=301]
HTTP/HTTPS
RewriteEngine On
RewriteCond %{HTTPS} =on
RewriteRule ^(.*)$ - [env=protocol:https]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ - [env=protocol:http]
RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
RewriteRule ^(.*)$ %{ENV:protocol}://www.mysite.com/$1 [L,R=301]
*note: I haven't tested https because I don't currently have a cert to test, but if someone can verify or optimize what I have that would be awesome.
Mark Berry's answer worked fine here. I just add to split the previous code:
$.clearFormFields = function(area) {
$(area).find('input[type="text"],input[type="email"],textarea,select').val('');
};
to:
$.clearFormFields = function(area) {
$(area).find('input#name').val('');
$(area).find('input#phone').val("");
$(area).find('input#email').val("");
$(area).find('select#topic').val("");
$(area).find('textarea#description').val("");
};
Another class of reasons why this can happen is due to Postgres version updates.
You can confirm this is a problem by looking at the postgres logs:
tail -n 10000 /usr/local/var/log/postgres.log
and seeing entries like:
DETAIL: The data directory was initialized by PostgreSQL version 12, which is not compatible with this version 13.0.
In this case (assuming you are on Mac and using brew
), just run:
brew postgresql-upgrade-database
(Oddly, it failed on run 1 and worked on run 2, so try it twice before giving up)
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
I am arriving late here. However, I made a simple method that checks for the input type="checkbox"
var formData = new FormData($form.get(0));
var objectData = {};
formData.forEach(function (value, key) {
var updatedValue = value;
if ($('input[name="' + key + '"]').attr("type") === "checkbox" && $('input[name="' + key + '"]').is(":checked")) {
updatedValue = true; // we don't set false due to it is by default on HTML
}
objectData[key] = updatedValue;
});
var jsonData = JSON.stringify(objectData);
I hope this helps somebody else.
<h1>
<a href="http://stackoverflow.com">
Stack Overflow<img src="logo.png" alt="Stack Overflow" />
</a>
</h1>
This was the good option for SEO because SEO gives the H1 tag high priority, inside the h1 tag should be your site name. Using this method if you search the site name in SEO it will show your site logo as well.
you want to hide the site name OR text please use text-indent in negative value. ex
h1 a {
text-indent: -99999px;
}
Using generators, it is quite simple:
signal = ['?Signal value?']
def pniter( iter, signal=signal ):
iA = iB = signal
for iC in iter:
if iB is signal:
iB = iC
continue
else:
yield iA, iB, iC
iA = iB
iB = iC
iC = signal
yield iA, iB, iC
if __name__ == '__main__':
print('test 1:')
for a, b, c in pniter( range( 10 )):
print( a, b, c )
print('\ntest 2:')
for a, b, c in pniter([ 20, 30, 40, 50, 60, 70, 80 ]):
print( a, b, c )
print('\ntest 3:')
cam = { 1: 30, 2: 40, 10: 9, -5: 36 }
for a, b, c in pniter( cam ):
print( a, b, c )
for a, b, c in pniter( cam ):
print( a, a if a is signal else cam[ a ], b, b if b is signal else cam[ b ], c, c if c is signal else cam[ c ])
print('\ntest 4:')
for a, b, c in pniter([ 20, 30, None, 50, 60, 70, 80 ]):
print( a, b, c )
print('\ntest 5:')
for a, b, c in pniter([ 20, 30, None, 50, 60, 70, 80 ], ['sig']):
print( a, b, c )
print('\ntest 6:')
for a, b, c in pniter([ 20, ['?Signal value?'], None, '?Signal value?', 60, 70, 80 ], signal ):
print( a, b, c )
Note that tests that include None and the same value as the signal value still work, because the check for the signal value uses "is" and the signal is a value that Python doesn't intern. Any singleton marker value can be used as a signal, though, which might simplify user code in some circumstances.
Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
You can use this to replace the function if it doesn't exist:
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
</script>
Alternatively, you can cast the row DataItem to a class and then add condition based on the class properties. Here is a sample that I used to convert the row to a class/model named TimetableModel, then in if statement you have access to all class fields/properties:
protected void GridView_TimeTable_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var tt = (TimetableModel)(e.Row.DataItem);
if (tt.Unpublsihed )
e.Row.BackColor = System.Drawing.Color.Red;
else
e.Row.BackColor = System.Drawing.Color.Green;
}
}
}
It isn't always possible to do repetitive things in a simple and elegant way.
Just do what you always do when you have common code that gets replicated across many projects:
Search CPAN, someone may have already the code for you. For this issue I found Scalar::MoreUtils.
If you don't find something you like on CPAN, make a module and put the code in a subroutine:
package My::String::Util;
use strict;
use warnings;
our @ISA = qw( Exporter );
our @EXPORT = ();
our @EXPORT_OK = qw( is_nonempty);
use Carp qw(croak);
sub is_nonempty ($) {
croak "is_nonempty() requires an argument"
unless @_ == 1;
no warnings 'uninitialized';
return( defined $_[0] and length $_[0] != 0 );
}
1;
=head1 BOILERPLATE POD
blah blah blah
=head3 is_nonempty
Returns true if the argument is defined and has non-zero length.
More boilerplate POD.
=cut
Then in your code call it:
use My::String::Util qw( is_nonempty );
if ( is_nonempty $name ) {
# do something with $name
}
Or if you object to prototypes and don't object to the extra parens, skip the prototype in the module, and call it like: is_nonempty($name)
.
There is also str_sub
from the stringr package
x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"
I have adapted the script from Russ Cam (thank you, Russ Cam!) to my own needs: I needed to merge any columns that had the same value, not just empty cells.
This could be useful to someone else... Here is what I have come up with:
jQuery(document).ready(function() {
jQuery('table.tblSimpleAgenda tr').each(function() {
var tr = this;
var counter = 0;
var strLookupText = '';
jQuery('td', tr).each(function(index, value) {
var td = jQuery(this);
if ((td.text() == strLookupText) || (td.text() == "")) {
counter++;
td.prev().attr('colSpan', '' + parseInt(counter + 1,10) + '').css({textAlign : 'center'});
td.remove();
}
else {
counter = 0;
}
// Sets the strLookupText variable to hold the current value. The next time in the loop the system will check the current value against the previous value.
strLookupText = td.text();
});
});
});
If you want to update your project using SVN then first of all:
Go to the path on which your project is stored through command prompt.
Use the command SVN update
That's it.
You need to assign display: block;
property to the wrapping anchor. Otherwise it won't wrap correctly.
<a style="display:block" href="http://justinbieber.com">
<div class="xyz">My div contents</div>
</a>
The better way is to include it in a rake task. Create import.rake file inside /lib/tasks/ and put this code to that file.
desc "Imports a CSV file into an ActiveRecord table"
task :csv_model_import, [:filename, :model] => [:environment] do |task,args|
lines = File.new(args[:filename], "r:ISO-8859-1").readlines
header = lines.shift.strip
keys = header.split(',')
lines.each do |line|
values = line.strip.split(',')
attributes = Hash[keys.zip values]
Module.const_get(args[:model]).create(attributes)
end
end
After that run this command in your terminal rake csv_model_import[file.csv,Name_of_the_Model]
And yet another way to get the same error:
Using 0.0.0.0
as the IP address. That works fine in production, but has started failing on IIS Express for us. Changing that back to localhost in dev, solved our issue.
Just had this error, solved by downloading the Android SDK Command-line Tools (latest)
on Android Studio, under settings > Appearance & Behavior > System Settings > Android SDK > SDK Tools
and re-running flutter doctor --android-licenses
Apple enabled the attribute playsinline
in all browsers on iOS 10, so this works seamlessly:
<video src="file.mp4" playsinline>
Short answer: use iphone-inline-video, it enables inline playback and syncs the audio.
Long answer: You can work around this issue by simulating the playback by skimming the video instead of actually .play()
'ing it.
Yahoo is very easy to use and provides customized data. Use the following page to learn more.
finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv
WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.
Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv
$(document).on("submit","form",function(e){
//e.preventDefault();
$form = $(this);
$i = 0;
$("form input[required],form select[required]").each(function(){
if ($(this).val().trim() == ''){
$(this).css('border-color', 'red');
$i++;
}else{
$(this).css('border-color', '');
}
})
if($i != 0) e.preventDefault();
});
$(document).on("change","input[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
$(document).on("change","select[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
_x000D_
Permanent Fix
pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org
For eg:
pip install <package name> --trusted-host pypi.org --trusted-host files.pythonhosted.org
REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.
Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.
HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.
Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.
The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.
(Updated to cover implications of making the connection SSL-only.)
This also worked for me if you want to use shell environment variables:
ansible-playbook -i "localhost," ldap.yaml --extra-vars="LDAP_HOST={{ lookup('env', 'LDAP_HOST') }} clustername=mycluster env=dev LDAP_USERNAME={{ lookup('env', 'LDAP_USERNAME') }} LDAP_PASSWORD={{ lookup('env', 'LDAP_PASSWORD') }}"
I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)
Why not just stream down the content with the correct content specifier?
That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.
Explaining with Pictures :
The reference in the scope is not exactly the reference in the template. When you data-bind two objects, you need a third one that listen to the first and modify the other.
Here, when you modify the <input>
, you touch the data-ref3. And the classic data-bind mecanism will change data-ref4. So how the other {{data}}
expressions will move ?
Angular maintains a oldValue
and newValue
of every binding. And after every Angular event, the famous $digest()
loop will check the WatchList to see if something changed. These Angular events are ng-click
, ng-change
, $http
completed ... The $digest()
will loop as long as any oldValue
differs from the newValue
.
In the previous picture, it will notice that data-ref1 and data-ref2 has changed.
It's a little like the Egg and Chicken. You never know who starts, but hopefully it works most of the time as expected.
The other point is that you can understand easily the impact deep of a simple binding on the memory and the CPU. Hopefully Desktops are fat enough to handle this. Mobile phones are not that strong.
This C# code is to fetch all items from a dynamodb table using BatchGet or CreateBatchGet
string tablename = "AnyTableName"; //table whose data you want to fetch
var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(
new DynamoDBOperationConfig
{
OverrideTableName = tablename;
});
foreach(string Id in IdList) // in case you are taking string from input
{
Guid objGuid = Guid.Parse(Id); //parsing string to guid
BatchRead.AddKey(objGuid);
}
await BatchRead.ExecuteAsync();
var result = BatchRead.Results;
// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch
To do this, I would strongly consider wrapping a Text
component in a TouchableOpacity
. When a TouchableOpacity
is touched, it fades (becomes less opaque). This gives the user immediate feedback when touching the text and provides for an improved user experience.
You can use the onPress
property on the TouchableOpacity
to make the link happen:
<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
<Text style={{color: 'blue'}}>
Google
</Text>
</TouchableOpacity>
<table border="1" width="183" style='table-layout:fixed'>
<col width="67">
<col width="75">
<col width="41">
<tr>
<td>First Column</td>
<td>Second Column</td>
<td>Third Column</td>
</tr>
<tr>
<td>Row 1</td>
<td>Text</td>
<td align="right">1</td>
</tr>
<tr>
<td>Row 2</td>
<td>Abcdefg</td>
<td align="right">123</td>
</tr>
<tr>
<td>Row 3</td>
<td>Abcdefghijklmnop</td>
<td align="right">123456</td>
</tr>
</table>
I know it's old school, but give that a try, it works.
may also want to add this:
<style>
td {overflow:hidden;}
</style>
Of course, you'd put this in a separate linked stylesheet, and not inline... wouldn't you ;)
If you have a dataset named daily_data
:
daily_data<-daily_data[order(as.Date(daily_data$date, format="%d/%m/%Y")),]
A pattern that I particularly like is to combine nested classes with the factory pattern:
public abstract class BankAccount
{
private BankAccount() {} // prevent third-party subclassing.
private sealed class SavingsAccount : BankAccount { ... }
private sealed class ChequingAccount : BankAccount { ... }
public static BankAccount MakeSavingAccount() { ... }
public static BankAccount MakeChequingAccount() { ... }
}
By nesting the classes like this, I make it impossible for third parties to create their own subclasses. I have complete control over all the code that runs in any bankaccount object. And all my subclasses can share implementation details via the base class.
Helpful trick I thought I'd share on this old thread.
You can see how much memory is being used and adjust things accordingly using the Show memory indicator
setting.
It shows up in the lower right of the window.
In likeness of how I found this question using Google, I wanted to take it one step further.
Lets say I have a string[] states
and a db Entity
of StateCounties
and I just want the states from the list returned and not all of the StateCounties
.
I would write:
db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();
I found this within the sample of CheckBoxList
for nu-get.
Until now, I used the solutions described in the answers of this question. Now, I came up with a little library called Parallel Stream Support for that:
ForkJoinPool pool = new ForkJoinPool(NR_OF_THREADS);
ParallelIntStreamSupport.range(1, 1_000_000, pool)
.filter(PrimesPrint::isPrime)
.collect(toList())
But as @PabloMatiasGomez pointed out in the comments, there are drawbacks regarding the splitting mechanism of parallel streams which depends heavily on the size of the common pool. See Parallel stream from a HashSet doesn't run in parallel .
I am using this solution only to have separate pools for different types of work but I can not set the size of the common pool to 1 even if I don't use it.
I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.
http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011
There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.
Here are few things you can try out
$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert
$a.Results | ConvertFrom-Json
Try this to see if you can filter out the columns that you are getting from the API
$a.Results | ft
or, you can try using this also
$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert
$b.Content | ConvertFrom-Json
Curl Style Headers
$b.Headers
I tested the IRM / IWR with the twitter JSON api.
$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell
Hope this helps.
I used the below solution and it worked for me.
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'filename.csv');_x000D_
} else {_x000D_
var a = document.createElement('a');_x000D_
a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data);_x000D_
a.target = '_blank';_x000D_
a.download = 'filename.csv';_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
}
_x000D_
It is possible to do (in the deployed repository)
git fetch
git checkout origin/master -- path/to/file
The fetch will download all the recent changes, but it will not put it in your current checked out code (working area).
The checkout will update the working tree with the particular file from the downloaded changes (origin/master
).
At least this works for me for those little small typo fixes, where it feels weird to create a branch etc just to change one word in a file.
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
Make an object
$obj = json_decode(json_encode($need_to_json));
Show data from this $obj
$obj->{'needed'};
Thanks to this post, my full css for cross browser happiness is:
<style>
.backgroundpic {
background-image: url('img/home.jpg');
background-size: cover;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='img/home.jpg',
sizingMethod='scale');
}
</style>
It's been so long since I've worked on this piece of code, but I'd like to add for more browser compatibility I've appended this to my CSS for more browser compatibility:
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
http://msdn.microsoft.com/en-us/library/ms173767.aspx
Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.
If you already have Visual Studio installed, the new project types will be installed along with SQL Server.
RFC 2616 describes which status codes to use.
And no, it's not always 200.
I like to do this witch i think is cleaner :
1 - Add the model to namespace:
use App\Employee;
2 - then you can do :
$employees = Employee::get();
or maybe somthing like this:
$employee = Employee::where('name', 'John')->first();
The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date
/ java.util.Calendar
classes.
Joda's DateFormatter
can parse a String to a Joda DateTime
.
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
In your code j is Already json data and j['places'] is list not dict.
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
for each in j['places']:
print each['latitude']
IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.
You want a dict.
For (unsorted) lists in Python, the "in" operation requires O(n) time---not good when you have a large amount of data. A dict, on the other hand, is a hash table, so you can expect O(1) lookup time.
As others have noted, you might choose a set (a special type of dict) instead, if you only have keys rather than key/value pairs.
Related:
I'd use the code in the original question, but if you really wanted to use foreach and have an integer index in C#:
foreach (int i in Enumerable.Range(0, myArray.Length).Reverse())
{
myArray[i] = 42;
}
I think width: -moz-calc(25% - 1em);
is what you are looking for.
And you may want to give this Link a look for any further assistance
You can use JavaScript to do this, with onClick method. This maybe helps CSS3 transition click event
In ASP.NET MVC 3 Preview1 you can import a namespace on all your razor views with this code in Global.asax.cs
Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");
I hope in RTM this gets done through Web.config section.
Insert \u0020 directly in the XML for a blank you would like to preserve.
<string name="spelatonertext3">-4, \u00205, \u0020\u0020-5, \u00206, \u0020-6,</string>
AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)
I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).
Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.
This worked for me
var dateToFormat = "2018-05-16 12:57:13"; //TIMESTAMP
moment(dateToFormat).format("DD/MM/YYYY"); // you get "16/05/2018"
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
this native-base there is solution:
<Button
block
disabled={!learnedWordsByUser.length}
style={{ marginTop: 10 }}
onPress={learnedWordsByUser.length && () => {
onFlipCardsGenerateNewWords(learnedWordsByUser)
onFlipCardsBtnPress()
}}
>
<Text>Let's Review</Text>
</Button>
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
If you run binary on linux machine you could use shell script.
overwrite into a file
./binaryapp > binaryapp.log
append into a file
./binaryapp >> binaryapp.log
overwrite stderr into a file
./binaryapp &> binaryapp.error.log
append stderr into a file
./binaryapp &>> binalyapp.error.log
it can be more dynamic using shell script file.
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
I have same problem but CleanUp eclipse option doesn't work for me.
1) install TortoiseSVN
2) Go to windows explorer and right click on your project directory
3 Choice CleanUp option (by checking break lock option)
It's works.
Hope this helps someone.
In my case, stopping Proxifier fixed it. I added a rule to route any connections from vpnkit.exe
as Direct
and it now works.
const setTimeoutAsync = (cb, delay) =>
new Promise((resolve) => {
setTimeout(() => {
resolve(cb());
}, delay);
});
We can pass custom 'cb fxn' like this one
You could also use:
public static bool IsWhiteSpace(string s)
{
return s.Trim().Length == 0;
}
The below code should apply different CSS classes based on your Model's CanEdit
Property value .
<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>
But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.
@if(Model.CanEdit)
{
<div>Edit/Delete link goes here</div>
}
git checkout checksum # You could use this to peek previous checkpoints
git status # You will see HEAD detached at checksum
git checkout master # This moves HEAD to master branch
Frustratingly the Numpy package published to PyPI won't install on most Windows computers https://github.com/numpy/numpy/issues/5479
Instead:
pip install numpy-1.10.2+mkl-cp35-none-win_amd64.whl
MySQL multiple instances present on Ubuntu.
step 1 : if it's listed as installed, you got it. Else you need to get it.
sudo ps -A | grep mysql
step 2 : remove the one MySQL
sudo apt-get remove mysql
sudo service mysql restart
step 3 : restart lamp
sudo /opt/lampp/lampp restart
global $post;
echo $post->ID;
If you are using post as a model (without dependency injection), you can also do:
$posts = Post::orderBy('id', 'DESC')->get();
I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).
<input type="text" value="<script>alert('test');</script>" />
Produces:
You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value
attribute.
var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";
To indicate a missing file/resource and serve a 404 page, you need not redirect. In the same request you must generate the response with the status code set to 404 and the content of your 404 HTML page as response body. Here is the sample code to demonstrate this in Node.js.
var http = require('http'),
fs = require('fs'),
util = require('util'),
url = require('url');
var server = http.createServer(function(req, res) {
if(url.parse(req.url).pathname == '/') {
res.writeHead(200, {'content-type': 'text/html'});
var rs = fs.createReadStream('index.html');
util.pump(rs, res);
} else {
res.writeHead(404, {'content-type': 'text/html'});
var rs = fs.createReadStream('404.html');
util.pump(rs, res);
}
});
server.listen(8080);
As per latest updates, caskroom packages have moved to homebrew. So try following commands:
brew tap homebrew/cask
brew cask install sublime-text
These 2 terminal commands will be enough for installing sublime.
Use the password input type.
<input type="password" name="password" />
Here is a simple demo http://jsfiddle.net/cPaEN/
You only use the M
for a numeric literal, when you cast it's just:
decimal dtot = (decimal)doubleTotal;
Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal
you may get rounding errors. You may want to convert the numbers to Decimal
before adding them together, or make sure that the numbers aren't floating point numbers in the first place.
You can use datetime.strftime to extract the day, the month, the year...
Example :
from datetime import datetime
d = datetime.today()
# Retrieves the day and the year
print d.strftime("%d-%Y")
Output (for today):
29-2011
If you just want to retrieve the day, you can use day attribute like :
from datetime import datetime
d = datetime.today()
# Retrieves the day
print d.day
Ouput (for today):
29
Maybe you are looking for Vector
. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList
instead.
Update: Although this answer has been accepted a few years ago, note that its approach is now recommended against by the Apache documentation. Use a Redirect
instead. See this answer.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript.
A model, and namely a class, is an actual JS function which is being used to generate new objects.
I want to load JSON data from a URL and bind to the Interface/Model.
Go for a model, otherwise it will still be JSON in your Javascript.
MemoryStream
has .WriteTo(outstream);
and .NET 4.0 has .CopyTo
on normal stream object.
.NET 4.0:
instream.CopyTo(outstream);
I had the same problem and solved with '%' operator:
select 12.54 % 1;
In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.
$('.btn-action').click(function(){
var url = $(this).data("url");
$.ajax({
url: url,
dataType: 'json',
success: function(res) {
// get the ajax response data
var data = res.body;
// update modal content here
// you may want to format data or
// update other modal elements here too
$('.modal-body').text(data);
// show modal
$('#myModal').modal('show');
},
error:function(request, status, error) {
console.log("ajax call went wrong:" + request.responseText);
}
});
});
A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.
You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.
AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.
Bind you Datagrid to an ObservableCollection, and update your collection instead.
Github documentation contains a script that replaces the committer info for all commits in a branch.
Run the following script from terminal after changing the variable values
#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
Push the corrected history to GitHub:
git push --force --tags origin 'refs/heads/*'
OR if you like to push selected references of the branches then use
git push --force --tags origin 'refs/heads/develop'
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
-- Step 1: Create temp table. create table Billing ( TAP_ID char(10), ACCT_NUM char(10));
SELECT * FROM BILLING;
-- Step 2: Create Control file.
load data infile IN_DATA.txt into table Billing fields terminated by ',' (TAP_ID, ACCT_NUM)
-- Step 3: Create input data file. IN_DATA.txt file content: 100,15678966
-- Step 4: Execute command from run: .. client\bin>sqlldr username@db-sis__id/password control='Billing.ctl'
The following solution seems like a good option,
<label ng-repeat="fruit in fruits">
<input
type="checkbox"
ng-model="fruit.checked"
ng-value="true"
> {{fruit.fruitName}}
</label>
And in controller model value fruits
will be like this
$scope.fruits = [
{
"name": "apple",
"checked": true
},
{
"name": "orange"
},
{
"name": "grapes",
"checked": true
}
];
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern
df[0::len(df)-1 if len(df) > 1 else 1]
works even for single row-dataframes.
Example: For the following dataframe this will not create a duplicate:
df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1 else 1]
print df2
a b
0 1 a
whereas this does:
df3 = df.iloc[[0, -1]]
print df3
a b
0 1 a
0 1 a
because the single row is the first AND last row at the same time.
If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.
There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).
In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.
Hope it helps!
You can use HAVING clause for filter calculated in SELECT fields and aliases
Answered here quite elegantly using attached behaviors, my preferred method for almost anything.
myfun(*some_tuple)
does exactly what you request. The *
operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.
Since Doctrine 2.6
it is possible to use count()
method directly from EntityRepository
. For details see the link.
Bitmap
implements Parcelable
, so you could always pass it with the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
If you have start-stop-daemon
start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
%c
is designed for a single character a char, so it print only one element.Passing the char array as a pointer you are passing the address of the first element of the array(that is a single char) and then will be printed :
s
printf("%c\n",*name++);
will print
i
and so on ...
Pointer is not needed for the %s because it can work directly with String of characters.
Two awesome solutions were this, if your extending ListFragment from a fragment, know that mListView.setOnItemClickListener
wont be called before your activity is created, this ensured it is set when activity has been created
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long rowId) {
// Do the onItemClick action
Log.d("ROWSELECT", "" + rowId);
}
});
}
While looking at the source code for ListFragment, I came across this
public class ListFragment extends Fragment {
...........................................
................................................
final private AdapterView.OnItemClickListener mOnClickListener
= new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
onListItemClick((ListView)parent, v, position, id);
}
};
................................................................
................................................................
public void onListItemClick(ListView l, View v, int position, long id) {
}
}
An onItemClickListener
object is attached and it calls onListItemClick()
As such the other similar solution, which works in the exact same way is to override onListItemClick()
@Override
public void onListItemClick(ListView l, View v, int position, long rowId) {
super.onListItemClick(l, v, position, id);
// Do the onItemClick action
Log.d("ROWSELECT", "" + rowId);
}
I'm tuning into what krtek has written. More specifically solution 1:
Assumptions:
Solution:
hg rollback
to undo the last commitThe rollback really undoes the last operation. Its way of working is quite simple: normal operations in HG will only append to files; this includes a commit. Mercurial keeps track of the file lengths of the last transaction and can therefore completely undo one step by truncating the files back to their old lengths.
Use from
to directly convert a previously created Promise to an Observable.
import { from } from 'rxjs';
// getPromise() is called once, the promise is passed to the Observable
const observable$ = from(getPromise());
observable$
will be a hot Observable that effectively replays the Promises value to Subscribers.
It's a hot Observable because the producer (in this case the Promise) is created outside of the Observable. Multiple subscribers will share the same Promise. If the inner Promise has been resolved a new subscriber to the Observable will get its value immediately.
Use defer
with a Promise factory function as input to defer the creation and conversion of a Promise to an Observable.
import { defer } from 'rxjs';
// getPromise() is called every time someone subscribes to the observable$
const observable$ = defer(() => getPromise());
observable$
will be a cold Observable.
It's a cold Observable because the producer (the Promise) is created inside of the Observable. Each subscriber will create a new Promise by calling the given Promise factory function.
This allows you to create an observable$
without creating and thus executing a Promise right away and without sharing this Promise with multiple subscribers.
Each subscriber to observable$
effectively calls from(promiseFactory()).subscribe(subscriber)
. So each subscriber creates and converts its own new Promise to a new Observable and attaches itself to this new Observable.
Most RxJS operators that combine (e.g. merge
, concat
, forkJoin
, combineLatest
...) or transform observables (e.g. switchMap
, mergeMap
, concatMap
, catchError
...) accept promises directly. If you're using one of them anyway you don't have to use from
to wrap a promise first (but to create a cold observable you still might have to use defer
).
// Execute two promises simultaneously
forkJoin(getPromise(1), getPromise(2)).pipe(
switchMap(([v1, v2]) => v1.getPromise(v2)) // map to nested Promise
)
Check the documentation or implementation to see if the operator you're using accepts ObservableInput
or SubscribableOrPromise
.
type ObservableInput<T> = SubscribableOrPromise<T> | ArrayLike<T> | Iterable<T>;
// Note the PromiseLike ----------------------------------------------------v
type SubscribableOrPromise<T> = Subscribable<T> | Subscribable<never> | PromiseLike<T> | InteropObservable<T>;
The difference between from
and defer
in an example: https://stackblitz.com/edit/rxjs-6rb7vf
const getPromise = val => new Promise(resolve => {
console.log('Promise created for', val);
setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000);
});
// the execution of getPromise('FROM') starts here, when you create the promise inside from
const fromPromise$ = from(getPromise('FROM'));
const deferPromise$ = defer(() => getPromise('DEFER'));
fromPromise$.subscribe(console.log);
// the execution of getPromise('DEFER') starts here, when you subscribe to deferPromise$
deferPromise$.subscribe(console.log);
As the other answers state there is no way getting query string parameters using servlet api.
So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)
I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.
Example: username=james&username=smith&password=pwd1,pwd2
will return
password : [pwd1, pwd2]
(length = 2)
username : [james, smith]
(length = 2)
public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
Map<String, String[]> queryParameters = new HashMap<>();
String queryString = request.getQueryString();
if (StringUtils.isNotEmpty(queryString)) {
queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
String[] parameters = queryString.split("&");
for (String parameter : parameters) {
String[] keyValuePair = parameter.split("=");
String[] values = queryParameters.get(keyValuePair[0]);
//length is one if no value is available.
values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
queryParameters.put(keyValuePair[0], values);
}
}
return queryParameters;
}
Just just using Transformers It did not work for me I was getting type cast exception.
sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class))
did notwork because I was getting Array of Object in the return list element not the fixed MYEngityName type of list element.
It worked for me when I make following changes When I have added sqlQuery.addScalar(-)
each selected column and its type and for specific String type column we dont have to map its type. like addScalar("langCode");
And I have join MYEngityName with NextEnity we cant just select *
in the Query it will give array of Object in the return list.
Below code sample :
session = ht.getSessionFactory().openSession();
String sql = new StringBuffer("Select txnId,nft.mId,count,retryReason,langCode FROM MYEngityName nft INNER JOIN NextEntity m on nft.mId = m.id where nft.txnId < ").append(lastTxnId)
.append(StringUtils.isNotBlank(regionalCountryOfService)? " And m.countryOfService in ( "+ regionalCountryOfService +" )" :"")
.append(" order by nft.txnId desc").toString();
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setResultTransformer(Transformers.aliasToBean(MYEngityName.class));
sqlQuery.addScalar("txnId",Hibernate.LONG)
.addScalar("merchantId",Hibernate.INTEGER)
.addScalar("count",Hibernate.BYTE)
.addScalar("retryReason")
.addScalar("langCode");
sqlQuery.setMaxResults(maxLimit);
return sqlQuery.list();
It might help some one. in this way work for me.
I have tried above with above code but not working ,Here is solution to set current date selected in asp.net calendar control
dtpStartDate.SelectedDate = Convert.ToDateTime(DateTime.Now.Date);
dtpStartDate.VisibleDate = Convert.ToDateTime(DateTime.Now.ToString());