Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become
WHERE ... LIKE '%aa[%]bb%'
If you need proof:
create table test (field nvarchar(100))
go
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
go
select * from test where field like 'abcdef[%]hijklm'
go
Try the following:
LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/python
Replace /usr/local/lib
with the folder where you have installed libpython2.7.so.1.0
if it is not in /usr/local/lib
.
If this works and you want to make the changes permanent, you have two options:
Add export LD_LIBRARY_PATH=/usr/local/lib
to your .profile
in your home directory (this works only if you are using a shell which loads this file when a new shell instance is started). This setting will affect your user only.
Add /usr/local/lib
to /etc/ld.so.conf
and run ldconfig
. This is a system-wide setting of course.
EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.
The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.
The value of EOF is -1 because it has to be different from any return value from getchar
that is an actual character. So getchar
returns any character value as an unsigned char, converted to int, which will therefore be non-negative.
If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar()
will return EOF
, and hence getchar() != EOF
will be false, and the loop will terminate.
[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.
Works that way as well, a bit more tidy.
getQuery()
just returns the underlying builder, which already contains the table reference.
$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
->select('browser', $browser_total_raw)
->groupBy('browser')
->pluck('total','browser');
Use keypress
event on usersSearch
textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.
$('document').ready(function(){
$('#searchButton').click(function(){
var search = $('#usersSearch').val();
$.post('../searchusers.php',{search: search},function(response){
$('#userSearchResultsTable').html(response);
});
})
$('#usersSearch').keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#searchButton').click();//Trigger search button click event
}
});
});
To connect to mongodb
with mongoose
, you can use :
mongoose.connect('mongodb://localhost/users_test');
or
mongoose.connect('localhost/users_test');
or
mongoose.connect('localhost','users_test');
But not mongoose.connect('mongodb:localhost/users_test');
, it doesnt match the right hostname (mongodb
instead of localhost
)
This is another way of solving this problem.
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
I'd suggest creating a directory junction named C:\Android
pointing to the actual C:\Program Files (x86)\Android\android-sdk-windows\
:
MKLINK /J C:\Android "C:\Program Files (x86)\Android\android-sdk-windows\"
and then setting the newly created junction as SDK Location for your Eclipse ADT Plugin (Eclipse menu\ Window\ Preference\ Android). This might help for a number of tools/ plugin too that have problems with spaces in paths.
i did this:
$("#myModal").modal({}).draggable();
and it make my very standard/basic modal draggable.
not sure how/why it worked, but it did.
If 'config/config.json' file is used then add 'logging': false to the config.json in this case under development configuration section.
// file config/config.json
{
{
"development": {
"username": "username",
"password": "password",
"database": "db_name",
"host": "127.0.0.1",
"dialect": "mysql",
"logging": false
},
"test": {
...
}
function currentUrl() {
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
return $protocol . '://' . $host . $script . '?' . $params;
}
Then add your value with something like;
echo currentUrl().'&value=myVal';
if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b
Try float(a)/b
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
Check the XML. It is not a valid xml.
Prolog is the first line with xml version info. It ok not to include it in your xml.
This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.
e.g.
In my environment, I just added the two files to class path. And is work fine.
slf4j-jdk14-1.7.25.jar
slf4j-api-1.7.25.jar
There is virtually no difference.
My .zip file was formatted correctly (I think) but it wasn't working. Even unchecking "Group items by category" didn't work
To install it I did so:
At this point Eclipse read the plugin correctly, I went ahead, accepted the conditions and then asked me to restart the IDE.
<form target="_parent" ... />
Using Kevin Vella's idea, I tried using the above on the form element made by PayPal's button generator. Worked for me so that Paypal does not open in a new browser window/tab.
Update
Here's an example:
Generating a button as of today (01-19-2021), PayPal automatically includes target="_top"
on the form
element, but if that doesn't work for your context, try a different target
value. I suggest _parent
-- at least that worked when I was using this PayPal button.
See Form Target Values for more info.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_parent">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHostedGuest">
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
In Kotlin you can add Textview as follows.
val textView = TextView(activity).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
setMargins(0, 20, 0, 0)
setPadding(10, 10, 0, 10)
}
text = "SOME TEXT"
setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimary))
setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark))
textSize = 16.0f
typeface = Typeface.defaultFromStyle(Typeface.BOLD)
}
linearLayoutContainer.addView(textView)
PHP's DateTime
object is pretty flexible.
Since the user asked for more than one timezone option, then you can make it generic.
Generic Function
function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
$date = new DateTime($date,new DateTimeZone($timezone));
$date->setTimezone( new DateTimeZone($timezone_to) );
return $date->format($format);
}
Usage:
echo convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');
Output:
2011-04-21 09:14:00
The percent sign is escaped using a percent sign:
System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);
The complete syntax can be accessed in java docs. This particular information is in the section Conversions
of the first link.
The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. %
is not a valid character.
In your current code, you save the GState
of the current context, configure it to draw a shadow .. and the restore it to what it was before you configured it to draw a shadow. Then, finally, you invoke the superclass's implementation of drawRect
: .
Any drawing that should be affected by the shadow setting needs to happen after
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
but before
CGContextRestoreGState(currentContext);
So if you want the superclass's drawRect:
to be 'wrapped' in a shadow, then how about if you rearrange your code like this?
- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
[super drawRect: rect];
CGContextRestoreGState(currentContext);
}
Here's how i am calling my modal
<a data-toggle="modal" data-id="190" data-target="#modal-popup">Open</a>
Here's how i am obtaining value in the modal
$('#modal-popup').on('show.bs.modal', function(e) {
console.log($(e.relatedTarget).data('id')); // 190 will be printed
});
It is basically a comment. As we know, a number of people working on the same project must have knowledge about the code changes. We are making some notes in the program about the parameters.
I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:
$var = new YourClass();
$var->method();
You can also use the new way to do the same since PHP 5.4:
(new YourClass)->method();
I hope it helps you!
Use Map<Integer, List<String>>
:
Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();
map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...
To add a new key/value pair in this map:
public void add(Integer key, String newValue) {
List<String> currentValue = map.get(key);
if (currentValue == null) {
currentValue = new ArrayList<String>();
map.put(key, currentValue);
}
currentValue.add(newValue);
}
Please remember to "make it work first before you make it work fast".
Very few percent of any program are usually relevant for its speed.
You can always kick out or simplify an assert
if it ever proves to
be a performance problem -- and most of them never will.
Be pragmatic:
Assume you have a method that processes a non-empty list of tuples and the program logic will break if those tuples are not immutable. You should write:
def mymethod(listOfTuples):
assert(all(type(tp)==tuple for tp in listOfTuples))
This is probably fine if your lists tend to be ten entries long, but it can become a problem if they have a million entries. But rather than discarding this valuable check entirely you could simply downgrade it to
def mymethod(listOfTuples):
assert(type(listOfTuples[0])==tuple) # in fact _all_ must be tuples!
which is cheap but will likely catch most of the actual program errors anyway.
I'll be honest here. . .everything above may or may not be true, but it all seems WAY too complicated, or doesn't address knowing what tab is being used server side.
Sometimes we need to apply Occam's razor.
Here's the Occam's approach: (no, I'm not Occam, he died in 1347)
1) assign a browser unique id to your page on load. . . if and only if the window doesn't have an id yet (so use a prefix and a detection)
2) on every page you have (use a global file or something) simply put code in place to detect the focus event and/or mouseover event. (I'll use jquery for this part, for ease of code writing)
3) in your focus (and/or mouseover) function, set a cookie with the window.name in it
4) read that cookie value from your server side when you need to read/write tab specific data.
Client side:
//Events
$(window).ready(function() {generateWindowID()});
$(window).focus(function() {setAppId()});
$(window).mouseover(function() {setAppId()});
function generateWindowID()
{
//first see if the name is already set, if not, set it.
if (se_appframe().name.indexOf("SEAppId") == -1){
"window.name = 'SEAppId' + (new Date()).getTime()
}
setAppId()
}
function setAppId()
{
//generate the cookie
strCookie = 'seAppId=' + se_appframe().name + ';';
strCookie += ' path=/';
if (window.location.protocol.toLowerCase() == 'https:'){
strCookie += ' secure;';
}
document.cookie = strCookie;
}
server side (C# - for example purposes)
//variable name
string varname = "";
HttpCookie aCookie = Request.Cookies["seAppId"];
if(aCookie != null) {
varname = Request.Cookies["seAppId"].Value + "_";
}
varname += "_mySessionVariable";
//write session data
Session[varname] = "ABC123";
//readsession data
String myVariable = Session[varname];
Done.
I actually found it better just testing for string length since many times the field is not null, just empty
<xsl:when test="string-length(field-you-want-to-test)<1">
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
above is excerpted from the Spring doc website https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html.
So, it seemed to be invoked when Spring container has started, if you want to do something at that time.
It just has one method to set the context, so you will get the context and do something to sth now already in context I think.
https://appetize.io/demo?device=iphone8&scale=75&orientation=portrait&osVersion=13.3 60 seconds is enought for test. Isn't need to register account to.
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
From my experience ten minutes ago this situation can happen where there are more than one category but with a lot of NAs. Taking the Kaggle Houseprice Dataset as example, if you loaded data and run a simple regression,
train.df = read.csv('train.csv')
lm1 = lm(SalePrice ~ ., data = train.df)
you will get same error. I also tried testing the number of levels of each factor, but none of them says it has less than 2 levels.
cols = colnames(train.df)
for (col in cols){
if(is.factor(train.df[[col]])){
cat(col, ' has ', length(levels(train.df[[col]])), '\n')
}
}
So after a long time I used summary(train.df)
to see details of each col, and removed some, and it finally worked:
train.df = subset(train.df, select=-c(Id, PoolQC,Fence, MiscFeature, Alley, Utilities))
lm1 = lm(SalePrice ~ ., data = train.df)
and removing any one of them the regression fails to run again with same error (which I have tested myself).
And above attributes generally have 1400+ NAs and 10 useful values, so you might want to remove these garbage attributes, even they have 3 or 4 levels. I guess a function counting how many NAs in each column will help.
FYI here is a function to convert a permission string with 9 characters (e.g. 'rwsr-x-wt') to a mask that can be used with os.chmod()
.
def perm2mask(p):
assert len(p) == 9, 'Bad permission length'
assert all(p[k] in 'rw-' for k in [0,1,3,4,6,7]), 'Bad permission format (read-write)'
assert all(p[k] in 'xs-' for k in [2,5]), 'Bad permission format (execute)'
assert p[8] in 'xt-', 'Bad permission format (execute other)'
m = 0
if p[0] == 'r': m |= stat.S_IRUSR
if p[1] == 'w': m |= stat.S_IWUSR
if p[2] == 'x': m |= stat.S_IXUSR
if p[2] == 's': m |= stat.S_IXUSR | stat.S_ISUID
if p[3] == 'r': m |= stat.S_IRGRP
if p[4] == 'w': m |= stat.S_IWGRP
if p[5] == 'x': m |= stat.S_IXGRP
if p[5] == 's': m |= stat.S_IXGRP | stat.S_ISGID
if p[6] == 'r': m |= stat.S_IROTH
if p[7] == 'w': m |= stat.S_IWOTH
if p[8] == 'x': m |= stat.S_IXOTH
if p[8] == 't': m |= stat.S_IXOTH | stat.S_ISVTX
return m
Note that setting SUID/SGID/SVTX bits will automatically set the corresponding execute bit. Without this, the resulting permission would be invalid (ST
characters).
In ImageMagick, you can do "supersampling". You specify a large density and then resize down as much as desired for the final output size. For example with your image:
convert -density 600 test.pdf -background white -flatten -resize 25% test.png
Download the image to view at full resolution for comparison..
I do not recommend saving to JPG if you are expecting to do further processing.
If you want the output to be the same size as the input, then resize to the inverse of the ratio of your density to 72. For example, -density 288 and -resize 25%. 288=4*72 and 25%=1/4
The larger the density the better the resulting quality, but it will take longer to process.
in some versions the code below might not work
mydict = dict(zip(df.id, df.value))
so make it explicit
id_=df.id.values
value=df.value.values
mydict=dict(zip(id_,value))
Note i used id_ because the word id is reserved word
Go to your Jenkins server's front page, click on REST API at the bottom of the page:
Create Job
To create a new job, post config.xml
to this URL with query parameter name=JOBNAME
. You need to send a Content-Type: application/xml
header. You'll get 200
status code if the creation is successful, or 4xx/5xx
code if it fails. config.xml
is the format Jenkins uses to store the project in the file system, so you can see examples of them in the Jenkins home directory, or by retrieving the XML configuration of existing jobs from /job/JOBNAME/config.xml
.
Use the CREATE TABLE SELECT syntax.
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
The OP's problem is the error. Deleting state isn't the only solution - or even a good one. The problem is docker run
isn't re-entrant, and docker start
is impotent w/o run
. So we have to combine them.
For example to run Postgres w/o destroying previous state, try this:
docker start postgres || docker run -d -p 5432:5432 --name postgres -e POSTGRES_PASSWORD=password postgres:13-alpine
Try using a div tag and block for span!
<div>
<span style="padding-right:3px; padding-top: 3px; display:block;">
<img class="manImg" src="images/ico_mandatory.gif"></img>
</span>
</div>
In case you encounter an error like this
mysqldump: 1044 Access denied when using LOCK TABLES
A quick workaround is to pass the –-single-transaction
option to mysqldump
.
So your command will be like this.
mysqldump --single-transaction -u user -p DBNAME > backup.sql
if you want to get the week number with the year use: "%Y-W%V"
:
e.g yearAndweeks <- strftime(dates, format = "%Y-W%V")
so
> strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%Y-W%V")
becomes:
[1] "2014-W11" "2014-W12" "2014-W12" "2014-W01
"
I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).
It sounds like you might need to create and query linked database servers in SQL Server
At the moment you've created a query that's going between different databases using a 3 part name mydatabase.dbo.mytable
but you need to go up a level and use a 4 part name myserver.mydatabase.dbo.mytable
, see this post on four part naming for more info
edit
The four part naming for your existing query would be as shown below (which I suspect you may have already tried?), but this assumes you can "get to" the remote database with the four part name, you might need to edit your host file / register the server or otherwise identify where to find database.windows.net
.
INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
([InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks])
SELECT [InvoiceNumber]
,[TotalAmount]
,[IsActive]
,[CreatedBy]
,[UpdatedBy]
,[CreatedDate]
,[UpdatedDate]
,[Remarks] FROM [BC1-PC].[testdabse].[dbo].[invoice]
If you can't access the remote server then see if you can create a linked database server:
EXEC sp_addlinkedserver [database.windows.net];
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR
[database.windows.net].basecampdev.dbo.invoice;
GO
Then you can just query against MyEmployee
without needing the full four part name
try this one ,
n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
a=raw_input()
if(a.isdigit()):
l1.insert(i,float(a)) #statement1
else:
l1.insert(i,a) #statement2
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.
Edited on 1/2/15
C# 6 :
With C# 6 you can initialize auto-properties directly (finally!), there are now other answers in the thread that describe that.
C# 5 and below:
Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway...
public class DefaultValuesTest
{
public DefaultValuesTest()
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
{
DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
if (myAttribute != null)
{
property.SetValue(this, myAttribute.Value);
}
}
}
public void DoTest()
{
var db = DefaultValueBool;
var ds = DefaultValueString;
var di = DefaultValueInt;
}
[System.ComponentModel.DefaultValue(true)]
public bool DefaultValueBool { get; set; }
[System.ComponentModel.DefaultValue("Good")]
public string DefaultValueString { get; set; }
[System.ComponentModel.DefaultValue(27)]
public int DefaultValueInt { get; set; }
}
Unfortunately, if you're trying to debug something at the very start of a Windows Service operation, "attaching" to the running process won't work. I tried using Debugger.Break() within the OnStart procecdure, but with a 64-bit, Visual Studio 2010 compiled application, the break command just throws an error like this:
System error 1067 has occurred.
At that point, you need to set up an "Image File Execution" option in your registry for your executable. It takes five minutes to set up, and it works very well. Here's a Microsoft article where the details are:
In my case this mistake was in unstable gradle version. Just use a stable version of gradle (not alpha, not even beta). And it was fixed for me
First you have to check if FileZilla is running on xampp control panel Than such error can occur You have to stop the FileZilla service from Xampp control panel
I would opt for AutoMapper, an open source and free mapping library which allows to map one type into another, based on conventions (i.e. map public properties with the same names and same/derived/convertible types, along with many other smart ones). Very easy to use, will let you achieve something like this:
Model model = Mapper.Map<Model>(dto);
Not sure about your specific requirements, but AutoMapper also supports custom value resolvers, which should help you writing a single, generic implementation of your particular mapper.
If you want to inspect html, css or maybe you need js console in your mobile browser . You can use excelent tool eruda Using it you have the same Developer Tools on your mobile browser like in your desctop device. Dont forget to upvote :) Here is a link https://github.com/liriliri/eruda
You can use round function
round("10.221",2);
Will return 10.22
I had this problem today, and all one-liners here failed to me because the files contained spaces in the names.
This is what I came up with that worked:
grep -ril <WORD1> | sed 's/.*/"&"/' | xargs grep -il <WORD2>
If you do not care about the data in management database; i.e. users
, vhosts
, messages
etc., and neither about other queues
, then you can reset
via commandline by running the following commands in order:
WARNING: In addition to the queues, this will also remove any
users
andvhosts
, you have configured on your RabbitMQ server; and will delete any persistentmessages
rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app
The rabbitmq documentation says that the reset
command:
Returns a RabbitMQ node to its virgin state.
Removes the node from any cluster it belongs to, removes all data from the management database, such as configured users and vhosts, and deletes all persistent messages.
So, be careful using it.
You could use predefined utility type Record<Keys, Type>
:
const obj: Record<string, string> = {
property: "value",
};
It allows to specify keys for your object literal:
type Keys = "prop1" | "prop2"
const obj: Record<Keys, string> = {
prop1: "Hello",
prop2: "Aloha",
something: "anything" // TS Error: Type '{ prop1: string; prop2: string; something: string; }' is not assignable to type 'Record<Keys, string>'.
// Object literal may only specify known properties, and 'something' does not exist in type 'Record<Keys, string>'.
};
And a type for the property value:
type Keys = "prop1" | "prop2"
type Value = "Hello" | "Aloha"
const obj1: Record<Keys, Value> = {
prop1: "Hello",
prop2: "Hey", // TS Error: Type '"Hey"' is not assignable to type 'Value'.
};
Had a similar problem to yours. What we had to do is use the document.domain solution found here:
Ways to circumvent the same-origin policy
We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:
Since 1.10 release, you can now add multiple tags at once on build:
docker build -t name1:tag1 -t name1:tag2 -t name2 .
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
const
public const string MyStr;
is a compile time constant (you can use it as the default parameter for a method parameter for example), and it will not be obfuscated if you use such technology
static readonly
public static readonly string MyStr;
is runtime constant. It means that it is evaluated when the application is launched and not before. This is why it can't be used as the default parameter for a method (compilation error) for example. The value stored in it can be obfuscated.
Your second bit of code starts the first bit of code as a subprocess with piped input and output. It then closes its input and tries to read its output.
The first bit of code tries to read from standard input, but the process that started it closed its standard input, so it immediately reaches an end-of-file, which Python turns into an exception.
As already mentioned, compiling the app in x64 gives you far more available memory.
But in the case one must build an app in x86, there is a way to raise the memory limit from 1,2GB to 4GB (which is the actual limit for 32 bit processes):
In the VC/bin folder of the Visual Studio installation directory, there must be an editbin.exe
file. So in my default installation I find it under
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\editbin.exe
In order to make the program work, maybe you must execute vcvars32.bat
in the same directory first. Then a
editbin /LARGEADDRESSAWARE <your compiled exe file>
is enough to let your program use 4GB RAM. <your compiled exe file>
is the exe, which VS generated while compiling your project.
If you want to automate this behavior every time you compile your project, use the following Post-Build event for the executed project:
if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
call "$(DevEnvDir)..\tools\vsvars32.bat"
editbin /largeaddressaware "$(TargetPath)"
)
Sidenote: The same can be done with the devenv.exe
to let Visual Studio also use 4GB RAM instead of 1.2GB (but first backup the old devenv.exe
).
Below code is using com.google.gson.JsonArray
.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
Simply put, the transient java keyword protect fields from the been Serialize as their non-transient fields counter parts.
In this code snippet our abstract class BaseJob implement Serializable interface, we extends from BaseJob but we need not serialize the remote and local data sources; serialize only organizationName and isSynced fields.
public abstract class BaseJob implements Serializable{
public void ShouldRetryRun(){}
}
public class SyncOrganizationJob extends BaseJob {
public String organizationName;
public Boolean isSynced
@Inject transient RemoteDataSource remoteDataSource;
@Inject transient LocalDaoSource localDataSource;
public SyncOrganizationJob(String organizationName) {
super(new
Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());
this.organizationName = organizationName;
this.isSynced=isSynced;
}
}
a proper solution with streams and error handling is below:
const fs = require('fs')
const stream = require('stream')
app.get('/report/:chart_id/:user_id',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
})
with Node older then 10 you will need to use pump instead of pipeline.
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
This can easily be done by using the Linq extension method Union. For example:
var mergedList = list1.Union(list2).ToList();
This will return a List in which the two lists are merged and doubles are removed. If you don't specify a comparer in the Union extension method like in my example, it will use the default Equals and GetHashCode methods in your Person class. If you for example want to compare persons by comparing their Name property, you must override these methods to perform the comparison yourself. Check the following code sample to accomplish that. You must add this code to your Person class.
/// <summary>
/// Checks if the provided object is equal to the current Person
/// </summary>
/// <param name="obj">Object to compare to the current Person</param>
/// <returns>True if equal, false if not</returns>
public override bool Equals(object obj)
{
// Try to cast the object to compare to to be a Person
var person = obj as Person;
return Equals(person);
}
/// <summary>
/// Returns an identifier for this instance
/// </summary>
public override int GetHashCode()
{
return Name.GetHashCode();
}
/// <summary>
/// Checks if the provided Person is equal to the current Person
/// </summary>
/// <param name="personToCompareTo">Person to compare to the current person</param>
/// <returns>True if equal, false if not</returns>
public bool Equals(Person personToCompareTo)
{
// Check if person is being compared to a non person. In that case always return false.
if (personToCompareTo == null) return false;
// If the person to compare to does not have a Name assigned yet, we can't define if it's the same. Return false.
if (string.IsNullOrEmpty(personToCompareTo.Name) return false;
// Check if both person objects contain the same Name. In that case they're assumed equal.
return Name.Equals(personToCompareTo.Name);
}
If you don't want to set the default Equals method of your Person class to always use the Name to compare two objects, you can also write a comparer class which uses the IEqualityComparer interface. You can then provide this comparer as the second parameter in the Linq extension Union method. More information on how to write such a comparer method can be found on http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx
If set is sufficient, ConcurrentSkipListSet might be used. (Its implementation is based on ConcurrentSkipListMap which implements a skip list.)
The expected average time cost is log(n) for the contains, add, and remove operations; the size method is not a constant-time operation.
If you are using rails or at less activesupport you got String#remove and String#remove! method
def remove!(*patterns)
patterns.each do |pattern|
gsub! pattern, ""
end
self
end
source: http://api.rubyonrails.org/classes/String.html#method-i-remove
Just wanted to add an important piece of information that I believe was left out perhaps with the assumption that the ones seeking answers might already know. This problem happens a lot and I too found myself stuck when I tried to implement the viewAlert
method for the buttons of the UIAlertView
message. To do this you need to 1st add the delegate class which may look something like this:
@interface YourViewController : UIViewController <UIAlertViewDelegate>
Also you can find a very helpful tutorial here!
Hope this helps.
By using below method you can convert java.math.BigDecimal to String.
BigDecimal bigDecimal = new BigDecimal("10.0001");
String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
System.out.println("bigDecimal value in String: "+bigDecimalString);
Output:
bigDecimal value in String: 10.0001
If you're using jQuery versions 1.4.3+:
$('selector').click(false);
If not:
$('selector').click(function(){return false;});
I use this script in my extension "Grab Any Media" and work fine ( like youtube case )
var oldHref = document.location.href;
window.onload = function() {
var
bodyList = document.querySelector("body")
,observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (oldHref != document.location.href) {
oldHref = document.location.href;
/* Changed ! your code here */
}
});
});
var config = {
childList: true,
subtree: true
};
observer.observe(bodyList, config);
};
if (!$_GET) echo "empty";
why do you need such a checking?
lol
you guys too direct-minded.
don't take as offense but sometimes not-minded at all
$_GET is very special variable, not like others.
it is supposed to be always set. no need to treat it as other variables.
when $_GET is not set and it's expected - it is emergency case and that's what "Undefined variable" notice invented for
Use <packages xmlns="urn:packages">
in the place of <packages>
You can have multiple CSS declarations for the same properties by separating them with commas:
.abc, .xyz {
margin-left: 20px;
}
You need to specify which column of the datarow you want to pull data from.
Try the following:
StringBuilder output = new StringBuilder();
foreach (DataRow rows in results.Tables[0].Rows)
{
foreach (DataColumn col in results.Tables[0].Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
Giving access to the IIS AppPool\YourAppPoolName user may be not enough with IIS default configurations.
In my case, I still had the error HTTP Error 401.3 - Unauthorized after adding the AppPool user and it was fixed only after adding permissions to the IUSR user.
This is necessary because, by default, Anonymous access is done using the IUSR. You can set another specific user, the Application Pool or continue using the IUSR, but don't forget to set the appropriate permissions.
Credits to this answer: HTTP Error 401.3 - Unauthorized
Old question, but the :before pseudo element works well here.
<style>
li:before {
content: "";
display: inline-block;
height: 1rem; // or px or em or whatever
width: .5rem; // or whatever space you want
}
</style>
It works really well and doesn't require many extra rules or html.
<ul>
<li>Some content</li>
<li>Some other content</li>
</ul>
Cheers!
There are multiple settings for adjusting the legend size. The two I find most useful are:
legend(..., labelspacing=0.2)
will reduce the spacing between entries to 2 points. The default on my install is about 0.5.legend(..., prop={'size':8})
. The default on my install is about 14 points.In addition, the legend documentation lists a number of other padding and spacing parameters including: borderpad
, handlelength
, handletextpad
, borderaxespad
, and columnspacing
. These all follow the same form as labelspacing and area also in multiples of fontsize.
These values can also be set as the defaults for all figures using the matplotlibrc file.
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 am assuming that you need the JDK itself. If so you can accomplish this with:
sudo add-apt-repository ppa:sun-java-community-team/sun-java6
sudo apt-get update
sudo apt-get install sun-java6-jdk
You don't really need to go around editing sources or anything along those lines.
This cannot be done reliably, since it's up to the browser to decide what to do with an URL it's been asked to retrieve.
You can suggest to the browser that it should offer to "save to disk" right away by sending a Content-disposition header:
header("Content-disposition: attachment");
I'm not sure how well this is supported by various browsers. The alternative is to send a Content-type of application/octet-stream, but that is a hack (you're basically telling the browser "I'm not telling you what kind of file this is" and depending on the fact that most browsers will then offer a download dialog) and allegedly causes problems with Internet Explorer.
Read more about this in the Web Authoring FAQ.
Edit You've already switched to a PHP file to deliver the data - which is necessary to set the Content-disposition header (unless there are some arcane Apache settings that can also do this). Now all that's left to do is for that PHP file to read the contents of the CSV file and print them - the filename=example.csv
in the header only suggests to the client browser what name to use for the file, it does not actually fetch the data from the file on the server.
Working code from my sources:
HTML WORLD
<select name="select_from" disabled>...</select>
JS WORLD
var from = jQuery('select[name=select_from]');
//add disabled
from.attr('disabled', 'disabled');
//remove it
from.removeAttr("disabled");
Try this:
System.Windows.Forms.MessageBox.Show("Here's a message!");
I was able to do this using TortoiseSVN directly from Windows explorer:
Right click on file to ignore->TortiseSVN
->Delete and add to ignore list
I had to close then re-open the project in Eclipse, job done :)
Hope this will assist anyone having the same error while importing CSV data into related tables. In my case the parent table was OK, but I got the error while importing data to the child table containing the foreign key. After temporarily removing the foregn key constraint on the child table, I managed to import the data and was suprised to find some of the values in the FK column having values of 0 (obviously this had been causing the error since the parent table did not have such values in its PK column). The cause was that, the data in my CSV column preceeding the FK column contained commas (which I was using as a field delimeter). Changing the delimeter for my CSV file solved the problem.
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
there is configuration in the following way:
Preferences -> keys -> Navigation shortcuts
the 3rd option: shortcut to choose a split pane is "no shortcut" by default, we can choose one
cheers
Extension attributes are added by Exchange. According to this Technet article something like this should work:
Set-Mailbox -Identity "anyUser" -ExtensionCustomAttribute4 @{Remove="myString"}
Brad's method worked for me. If you use it you might want to make it a little safer.
id scrollView = [yourWebView.subviews objectAtIndex:0]; if( [scrollView respondsToSelector:@selector(setAllowsRubberBanding:)] ) { [scrollView performSelector:@selector(setAllowsRubberBanding:) withObject:NO]; }
If apple changes something then the bounce will come back - but at least your app won't crash.
The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
function stringToUint(string) {
var string = btoa(unescape(encodeURIComponent(string))),
charList = string.split(''),
uintArray = [];
for (var i = 0; i < charList.length; i++) {
uintArray.push(charList[i].charCodeAt(0));
}
return new Uint8Array(uintArray);
}
function uintToString(uintArray) {
var encodedString = String.fromCharCode.apply(null, uintArray),
decodedString = decodeURIComponent(escape(atob(encodedString)));
return decodedString;
}
I have done, with some help from the internet, these little functions, they should solve your problems! Here is the working JSFiddle.
EDIT:
Since the source of the Uint8Array is external and you can't use atob
you just need to remove it(working fiddle):
function uintToString(uintArray) {
var encodedString = String.fromCharCode.apply(null, uintArray),
decodedString = decodeURIComponent(escape(encodedString));
return decodedString;
}
Warning: escape and unescape is removed from web standards. See this.
"
is on the official list of valid HTML 4 entities, but '
is not.
From C.16. The Named Character Reference ':
The named character reference
'
(the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use'
instead of'
to work as expected in HTML 4 user agents.
This query should identify columns that are potential problems...
SELECT *
FROM [source].INFORMATION_SCHEMA.COLUMNS src
INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst
ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH
Android studio 2.1.2 (or possibly earlier) will let you pick from a color wheel:
I got this by adding the following to my layout:
android:background="#FFFFFF"
Then I clicked on the FFFFFF color and clicked on the lightbulb that appeared.
I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.
Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.
You can try
Session::put('variable_Name', "Your Data Save Successfully !");
Session::get('variable_Name');
Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate
is a date input field in template.
import {formatDate} from '@angular/common';
this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));
I find that running
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
and
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/bin/virtualenv-3.4
in the command line on Ubuntu forces mkvirtualenv to use python3 and virtualenv-3.4. One still has to do
mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment
to create the environment. This is assuming that you have python3 in /usr/bin/python3 and virtualenv-3.4 in /usr/local/bin/virtualenv-3.4.
I'm not sure about best practice, but here is how I do it:
/*
* Object Constructor
*/
var foo = function(x) {
this.x = x;
};
/*
* Object Protoype
*/
foo.prototype = {
/*
* f is the name that is going to be used to call the various overloaded versions
*/
f: function() {
/*
* Save 'this' in order to use it inside the overloaded functions
* because there 'this' has a different meaning.
*/
var that = this;
/*
* Define three overloaded functions
*/
var f1 = function(arg1) {
console.log("f1 called with " + arg1);
return arg1 + that.x;
}
var f2 = function(arg1, arg2) {
console.log("f2 called with " + arg1 + " and " + arg2);
return arg1 + arg2 + that.x;
}
var f3 = function(arg1) {
console.log("f3 called with [" + arg1[0] + ", " + arg1[1] + "]");
return arg1[0] + arg1[1];
}
/*
* Use the arguments array-like object to decide which function to execute when calling f(...)
*/
if (arguments.length === 1 && !Array.isArray(arguments[0])) {
return f1(arguments[0]);
} else if (arguments.length === 2) {
return f2(arguments[0], arguments[1]);
} else if (arguments.length === 1 && Array.isArray(arguments[0])) {
return f3(arguments[0]);
}
}
}
/*
* Instantiate an object
*/
var obj = new foo("z");
/*
* Call the overloaded functions using f(...)
*/
console.log(obj.f("x")); // executes f1, returns "xz"
console.log(obj.f("x", "y")); // executes f2, returns "xyz"
console.log(obj.f(["x", "y"])); // executes f3, returns "xy"
In Prolog (specifically, SWI-Prolog)
:- use_module(library(tabling)).
% path(+Graph,?Source,?Target,?Path)
:- table path/4.
path(_,N,N,[N]).
path(G,S,T,[S|Path]) :-
dif(S,T),
member(S-I, G), % directed graph
path(G,I,T,Path).
test:
paths :- Graph =
[ 1- 2 % node 1 and 2 are connected
, 2- 3
, 2- 5
, 4- 2
, 5-11
,11-12
, 6- 7
, 5- 6
, 3- 6
, 6- 8
, 8-10
, 8- 9
],
findall(Path, path(Graph,1,7,Path), Paths),
maplist(writeln, Paths).
?- paths.
[1,2,3,6,7]
[1,2,5,6,7]
true.
Cygwin mount
now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab
, then restart your shell:
c:/Users /home none bind 0 0
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
If your csv file contains extra data, columns can be deleted from the DataFrame after import.
import pandas as pd
from StringIO import StringIO
csv = r"""dummy,date,loc,x
bar,20090101,a,1
bar,20090102,a,3
bar,20090103,a,5
bar,20090101,b,1
bar,20090102,b,3
bar,20090103,b,5"""
df = pd.read_csv(StringIO(csv),
index_col=["date", "loc"],
usecols=["dummy", "date", "loc", "x"],
parse_dates=["date"],
header=0,
names=["dummy", "date", "loc", "x"])
del df['dummy']
Which gives us:
x
date loc
2009-01-01 a 1
2009-01-02 a 3
2009-01-03 a 5
2009-01-01 b 1
2009-01-02 b 3
2009-01-03 b 5
On the other hand, it:
At the cost of:
So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid.
For more info, see the official Microsoft documentation.
In order to resolve this problem for android projects. follow the below mentioned steps new->android project->create project from existing source and in this you can give your code location. Now, it will import all the specified project code and will work fine
I had the same problem while installing ionic@beta
.
I tried the following items and they didn't help me.
npm cache clean
%temp%\npm-*
I solved the problem by installing node-v5.10.1-x64.msi (Previous version was node-v5.9.0-x64.msi) and run an npm cache clean
before installing ionic@beta
It worked!
I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));
string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));
With the contents of the script being:
$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable
Protected Member
Protected Member of a class in only available in the contained class (in which it has been declared) and in the derived class within the assembly and also outside the assembly.
Means if a class that resides outside the assembly can use the protected member of the other assembly by inherited that class only.
We can exposed the Protected member outside the assembly by inherited that class and use it in the derived class only.
Note: Protected members are not accessible using the object in the derived class.
Internal Member
Internal Member of a class is available or access within the assembly either creating object or in a derived class or you can say it is accessible across all the classes within the assembly.
Note: Internal members not accessible outside the assembly either using object creating or in a derived class.
Protected Internal
Protected Internal access modifier is combination Protected or Internal.
Protected Internal Member can be available within the entire assembly in which it declared either creating object or by inherited that class. And can be accessible outside the assembly in a derived class only.
Note: Protected Internal member works as Internal within the same assembly and works as Protected for outside the assembly.
Depends what you mean by "post data". You can use the HTML target=""
attribute on a <form />
tag, so it could be as simple as:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!">
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
If that's not it, or you're after something more complex, please edit your question to include more detail.
There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.
I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.
default.asp
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<form action="do_stuff.asp" method="post" target="my_frame">
<input type="text" name="someText" value="Some Text">
<input type="submit">
</form>
<iframe name="my_frame" src="do_stuff.asp">
</iframe>
</body>
</html>
do_stuff.asp
<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<% if (Request.Form.Count) { %>
You typed: <%=Request.Form("someText").Item%>
<% } else { %>
(not submitted)
<% } %>
</body>
</html>
I would be very interested to hear of any browser that doesn't run these examples correctly.
To compile you could just initiate a shell call to the csc compiler. You may have a headache trying to keep your paths and switches straight but it certainly can be done.
EDIT: Or better yet, use the CodeDOM as Noldorin suggested...
Take care to reset target, otherwise all other calls like Response.Redirect
will open in a new tab, which might be not what you want.
<asp:LinkButton OnClientClick="openInNewTab();" .../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
No, sorry. User-defined functions in SQL Server are really limited, because of a requirement that they be deterministic. No way round it, as far as I know.
Have you tried debugging the SQL code with Visual Studio?
If you can get it to run in a browser then something as simple as this would work
var webRequest = WebRequest.Create(@"http://webservi.se/year/getCurrentYear");
using (var response = webRequest.GetResponse())
{
using (var rd = new StreamReader(response.GetResponseStream()))
{
var soapResult = rd.ReadToEnd();
}
}
for "THIS IS" not to be bold -
add <span></span>
around the text
<h1>><span>THIS IS</span> A HEADLINE</h1>
and in style
h1 span{font-weight:normal}
Client send some messages need be compressed, server (kafka) decompress the string meesage
Below is my sample:
compress:
public static String compress(String str, String inEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(inEncoding));
gzip.close();
return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
decompress:
public static String decompress(String str, String outEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
String decode = URLDecoder.decode(str, "UTF-8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(decode.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString(outEncoding);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
If you get UnsupportedOperationException
from using one of ther answer above and your List
is created from Arrays.asList()
, it is because you can't edit such List
.
To fix, wrap the Arrays.asList()
inside new LinkedList<String>()
:
List<String> list = new LinkedList<String>(Arrays.asList(split));
Source is from this answer.
Tip : To make Auto size work , the call to sheet.autoSizeColumn(columnNumber)
should be made after populating the data into the excel.
Calling the method before populating the data, will have no effect.
Continuing from this answer: https://stackoverflow.com/a/15285514/1865860, I forked the nice github repo from @daniel-smith and made some improvements:
setItems
methoditems_list
setItems
methodslistItem
touch feedbackDon't just enable the first occurrence of display_errors
in the php.ini file. Make sure you scroll down to the "real" setting and change it from Off
to On
.
The thing is that if you settle with changing (i.e. uncomment + add = On
) by the very first occurrence of display_errors
your changes will be overwritten somewhere on line 480 where it's set to Off
again.
You can also try find() method. It determines if string str occurs in string, or in a substring of string.
str1 = "please help me out so that I could solve this"
str2 = "please help me out"
if (str1.find(str2)>=0):
print("True")
else:
print ("False")
Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream
is similar to the usage of iostream
, so it is not a burden to learn.
Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.
The basic member functions of stringstream class are
str()
, which returns the contents of its buffer in string type.
str(string)
, which set the contents of the buffer to the string argument.
Here is an example of how to use string streams.
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
The result is dec: 15 hex: f
.
istringstream
is of more or less the same usage.
To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.
FYI, the inheritance relationships between the classes are:
val viewTreeObserver: ViewTreeObserver = videoView.viewTreeObserver;
if (viewTreeObserver.isAlive) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
//Remove Listener
videoView.viewTreeObserver.removeOnGlobalLayoutListener(this);
//View Dimentions
viewWidth = videoView.width;
viewHeight = videoView.height;
//View Location
val point = IntArray(2)
videoView.post {
videoView.getLocationOnScreen(point) // or getLocationInWindow(point)
viewPositionX = point[0]
viewPositionY = point[1]
}
}
});
}
'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.
1) Use GDB scripts from http://clith.com/gdb_stl_utils/ These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.
2) Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.
3) Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. Note that if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). So compile with -fkeep-inline-functions
this maybe help someone else, in my case the problem with the missing favicon.
If you're really talking about the static text
<title>Foo & Bar</title>
stored in some file on the hard disk and served directly by a server, then yes: it probably doesn't need to be escaped.
However, since there is very little HTML content nowadays that's completely static, I'll add the following disclaimer that assumes that the HTML content is generated from some other source (database content, user input, web service call result, legacy API result, ...):
If you don't escape a simple &
, then chances are you also don't escape a &
or a
or <b>
or <script src="http://attacker.com/evil.js">
or any other invalid text. That would mean that you are at best displaying your content wrongly and more likely are suspectible to XSS attacks.
In other words: when you're already checking and escaping the other more problematic cases, then there's almost no reason to leave the not-totally-broken-but-still-somewhat-fishy standalone-& unescaped.
Hammer time!
I have used Hammer JS and it work with gesture. Read details from here: https://hammerjs.github.io/
Good thing that it is much more light weight and fast then jQuery mobile. You can test it on their website as well.
You need to load a package (like magrittr
or dplyr
) that defines the function first, then it should work.
install.packages("magrittr") # package installations are only needed the first time you use it
install.packages("dplyr") # alternative installation of the %>%
library(magrittr) # needs to be run every time you start R and want to use %>%
library(dplyr) # alternatively, this also loads %>%
The pipe operator %>%
was introduced to "decrease development time and to improve readability and maintainability of code."
But everybody has to decide for himself if it really fits his workflow and makes things easier.
For more information on magrittr
, click here.
Not using the pipe %>%
, this code would return the same as your code:
words <- colnames(as.matrix(dtm))
words <- words[nchar(words) < 20]
words
EDIT: (I am extending my answer due to a very useful comment that was made by @Molx)
Despite being from
magrittr
, the pipe operator is more commonly used with the packagedplyr
(which requires and loadsmagrittr
), so whenever you see someone using%>%
make sure you shouldn't loaddplyr
instead.
The color for your buttons comes from the btn-x classes (e.g., btn-primary, btn-success), so if you want to manually change the colors by writing your own custom css rules, you'll need to change:
/*This is modifying the btn-primary colors but you could create your own .btn-something class as well*/
.btn-primary {
color: #fff;
background-color: #0495c9;
border-color: #357ebd; /*set the color you want here*/
}
.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
color: #fff;
background-color: #00b3db;
border-color: #285e8e; /*set the color you want here*/
}
To extract only the filename from the path, you can do the following:
varFileName = Mid(fDialog.SelectedItems(1), InStrRev(fDialog.SelectedItems(1), "\") + 1, Len(fDialog.SelectedItems(1)))
It seems that the struct
datatype is commonly used in SOAP:
var_dump($client->__getTypes());
array(52) {
[0] =>
string(43) "struct Bank {\n string Code;\n string Name;\n}"
}
This is not a native PHP datatype!
It seems that the properties of the struct
type referred to in SOAP can be accessed as a simple PHP stdClass
object:
$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;
Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");
I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.
Yep, a late answer from me, but I think it may help to understand what's happening under the hood in case anyone wants to code some other Collector
-logic.
I tried to solve the problem by coding a more native and straight forward approach. I think it's as direct as possible:
public class LambdaUtilities {
/**
* In contrast to {@link Collectors#toMap(Function, Function)} the result map
* may have null values.
*/
public static <T, K, U, M extends Map<K, U>> Collector<T, M, M> toMapWithNullValues(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
return toMapWithNullValues(keyMapper, valueMapper, HashMap::new);
}
/**
* In contrast to {@link Collectors#toMap(Function, Function, BinaryOperator, Supplier)}
* the result map may have null values.
*/
public static <T, K, U, M extends Map<K, U>> Collector<T, M, M> toMapWithNullValues(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, Supplier<Map<K, U>> supplier) {
return new Collector<T, M, M>() {
@Override
public Supplier<M> supplier() {
return () -> {
@SuppressWarnings("unchecked")
M map = (M) supplier.get();
return map;
};
}
@Override
public BiConsumer<M, T> accumulator() {
return (map, element) -> {
K key = keyMapper.apply(element);
if (map.containsKey(key)) {
throw new IllegalStateException("Duplicate key " + key);
}
map.put(key, valueMapper.apply(element));
};
}
@Override
public BinaryOperator<M> combiner() {
return (left, right) -> {
int total = left.size() + right.size();
left.putAll(right);
if (left.size() < total) {
throw new IllegalStateException("Duplicate key(s)");
}
return left;
};
}
@Override
public Function<M, M> finisher() {
return Function.identity();
}
@Override
public Set<Collector.Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
}
};
}
}
And the tests using JUnit and assertj:
@Test
public void testToMapWithNullValues() throws Exception {
Map<Integer, Integer> result = Stream.of(1, 2, 3)
.collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null));
assertThat(result)
.isExactlyInstanceOf(HashMap.class)
.hasSize(3)
.containsEntry(1, 1)
.containsEntry(2, null)
.containsEntry(3, 3);
}
@Test
public void testToMapWithNullValuesWithSupplier() throws Exception {
Map<Integer, Integer> result = Stream.of(1, 2, 3)
.collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null, LinkedHashMap::new));
assertThat(result)
.isExactlyInstanceOf(LinkedHashMap.class)
.hasSize(3)
.containsEntry(1, 1)
.containsEntry(2, null)
.containsEntry(3, 3);
}
@Test
public void testToMapWithNullValuesDuplicate() throws Exception {
assertThatThrownBy(() -> Stream.of(1, 2, 3, 1)
.collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null)))
.isExactlyInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate key 1");
}
@Test
public void testToMapWithNullValuesParallel() throws Exception {
Map<Integer, Integer> result = Stream.of(1, 2, 3)
.parallel() // this causes .combiner() to be called
.collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null));
assertThat(result)
.isExactlyInstanceOf(HashMap.class)
.hasSize(3)
.containsEntry(1, 1)
.containsEntry(2, null)
.containsEntry(3, 3);
}
@Test
public void testToMapWithNullValuesParallelWithDuplicates() throws Exception {
assertThatThrownBy(() -> Stream.of(1, 2, 3, 1, 2, 3)
.parallel() // this causes .combiner() to be called
.collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null)))
.isExactlyInstanceOf(IllegalStateException.class)
.hasCauseExactlyInstanceOf(IllegalStateException.class)
.hasStackTraceContaining("Duplicate key");
}
And how do you use it? Well, just use it instead of toMap()
like the tests show. This makes the calling code look as clean as possible.
EDIT:
implemented Holger's idea below, added a test method
A very simple approach which works great cross browser is this:
http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page
html,_x000D_
body {_x000D_
margin:0;_x000D_
padding:0;_x000D_
height:100%;_x000D_
}_x000D_
#container {_x000D_
min-height:100%;_x000D_
position:relative;_x000D_
}_x000D_
#header {_x000D_
background:#ff0;_x000D_
padding:10px;_x000D_
}_x000D_
#body {_x000D_
padding:10px;_x000D_
padding-bottom:60px; /* Height of the footer */_x000D_
}_x000D_
#footer {_x000D_
position:absolute;_x000D_
bottom:0;_x000D_
width:100%;_x000D_
height:60px; /* Height of the footer */_x000D_
background:#6cf;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="header">header</div>_x000D_
<div id="body">body</div>_x000D_
<div id="footer">footer</div>_x000D_
</div>
_x000D_
With numpy 1.3 or svn you can do this
In [1]: a = arange(10000.).reshape(100,100)
In [3]: isnan(a.max())
Out[3]: False
In [4]: a[50,50] = nan
In [5]: isnan(a.max())
Out[5]: True
In [6]: timeit isnan(a.max())
10000 loops, best of 3: 66.3 µs per loop
The treatment of nans in comparisons was not consistent in earlier versions.
You need to name the entity that holds the association to User. For example,
... INNER JOIN ug.user u ...
That's the "path" the error message is complaining about -- path from UserGroup to User entity.
Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.
For Firefox you can apply the CSS declaration "-moz-user-select" to "none". Check out their documentation, user-select.
It's a "preview" of the future "user-select" as they say, so maybe Opera or WebKit-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).
Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.
Use Return to break the loop.
angular.forEach([0,1,2], function(count){
if(count == 1) {
return;
}
});
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
You need astype
:
df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)
For converting to categorical
:
df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')
Another solution is Categorical
:
df['zipcode'] = pd.Categorical(df.zipcode)
Sample with data:
import pandas as pd
df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
print (df.dtypes)
bathrooms float64
bedrooms int64
floors float64
sqft_living int64
sqft_lot int64
zipcode int64
dtype: object
df['zipcode'] = df.zipcode.astype('category')
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
print (df.dtypes)
bathrooms float64
bedrooms int64
floors float64
sqft_living int64
sqft_lot int64
zipcode category
dtype: object
As Fermin said, a variable in the global scope should be accessible to all scripts loaded after it is declared. You could also use a property of window
or (in the global scope) this
to get the same effect.
// first.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
... in another file ...
// second.js
alert (colorCodes.back); // alerts `#fff`
... in your html file ...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
If your script is inside head tag in html file, try to put it inside body tag. CreateElement while script is inside head tag will give you a null warning
<head>
<title></title>
</head>
<body>
<h1>Game</h1>
<script type="text/javascript" src="script.js"></script>
</body>
scope.$watch returns a function that you can call and that will unregister the watch.
Something like:
var unbindWatch = $scope.$watch("myvariable", function() {
//...
});
setTimeout(function() {
unbindWatch();
}, 1000);
Oh, I just found that command on PostgreSQL forum:
SELECT * FROM pg_stat_activity;
I had some difficulty using the solutions already suggested for my specific use case, but figured it out eventually. I don't think my specific case is worthy of a new question, so I am posting my solution here for reference. (This is very closely related to the question and provides a solution for anyone else with a similar case to mine).
The code I ended up with looks like this:
public class HideableControl<T>: Control where T: class
{
private string _propertyName;
private PropertyInfo _propertyInfo;
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_propertyInfo = typeof(T).GetProperty(value);
}
}
protected override bool GetIsVisible(IRenderContext context)
{
if (_propertyInfo == null)
return false;
var model = context.Get<T>();
if (model == null)
return false;
return (bool)_propertyInfo.GetValue(model, null);
}
protected void SetIsVisibleProperty(Expression<Func<T, bool>> propertyLambda)
{
var expression = propertyLambda.Body as MemberExpression;
if (expression == null)
throw new ArgumentException("You must pass a lambda of the form: 'vm => vm.Property'");
PropertyName = expression.Member.Name;
}
}
public interface ICompanyViewModel
{
string CompanyName { get; }
bool IsVisible { get; }
}
public class CompanyControl: HideableControl<ICompanyViewModel>
{
public CompanyControl()
{
SetIsVisibleProperty(vm => vm.IsVisible);
}
}
The important part for me is that in the CompanyControl
class the compiler will only allow me to choose a boolean property of ICompanyViewModel
which makes it easier for other developers to get it right.
The main difference between my solution and the accepted answer is that my class is generic and I only want to match properties from the generic type that are boolean.
I got a solution that plays nice with bodyParser, using the verify
callback in bodyParser. In this code, I am using it to get a sha1 of the content and also getting the raw body.
app.use(bodyParser.json({
verify: function(req, res, buf, encoding) {
// sha1 content
var hash = crypto.createHash('sha1');
hash.update(buf);
req.hasha = hash.digest('hex');
console.log("hash", req.hasha);
// get rawBody
req.rawBody = buf.toString();
console.log("rawBody", req.rawBody);
}
}));
I am new in Node.js and express.js (started yesterday, literally!) so I'd like to hear comments on this solution.
Limiting output to two lines of text is possible with CSS, if you set the line-height
and height
of the element, and set overflow:hidden;
:
#someDiv {
line-height: 1.5em;
height: 3em; /* height is 2x line-height, so two lines will display */
overflow: hidden; /* prevents extra lines from being visible */
}
Alternatively, you can use the CSS text-overflow
and white-space
properties to add ellipses, but this only appears to work for a single line.
#someDiv {
line-height: 1.5em;
height: 3em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 100%;
}
And a demo:
Achieving both multiple lines of text and ellipses appears to be the realm of javascript.
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA <> 'x' AND columbB <> 'y'";
I'd suggest using the diamond operator (<>) in favor of != as the first one is valid SQL and the second one is a MySQL addition.
This is by far the most general and performant solution; surprised it hasn't been posted yet.
import numpy as np
def unique_count(a):
unique, inverse = np.unique(a, return_inverse=True)
count = np.zeros(len(unique), np.int)
np.add.at(count, inverse, 1)
return np.vstack(( unique, count)).T
print unique_count(np.random.randint(-10,10,100))
Unlike the currently accepted answer, it works on any datatype that is sortable (not just positive ints), and it has optimal performance; the only significant expense is in the sorting done by np.unique.
You can include any layout file in other layout file as-
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="30dp" >
<include
android:id="@+id/frnd_img_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="@layout/include_imagefile"/>
<include
android:id="@+id/frnd_video_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="@layout/include_video_lay" />
<ImageView
android:id="@+id/downloadbtn"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerInParent="true"
android:src="@drawable/plus"/>
</RelativeLayout>
here the layout files in include tag are other .xml layout files in the same res folder.
The combined answer for writing to a file can be;
MemoryStream ms = new MemoryStream();
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
I have had the same error recently. I have checked the folder Log of my Server instance.
x:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Log\
and I have found this errors in logs
Starting up database 'master'.
Error: 17204, Severity: 16, State: 1.
FCB::Open failed: Could not open file
x:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\master.mdf for file number 1. OS error: 5(Access is denied.).
Error: 5120, Severity: 16, State: 101.
Unable to open the physical file "E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\master.mdf". Operating system error 5: "5(Access is denied.)".
Error: 17204, Severity: 16, State: 1. FCB::Open failed: Could not open file E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mastlog.ldf for file number 2. OS error: 5(Access is denied.).
Error: 5120, Severity: 16, State: 101. Unable to open the physical file "E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mastlog.ldf". Operating system error 5: "5(Access is denied.)".
SQL Server shutdown has been initiated
So for me it was an easy fix. I just added proper access rights to this files to the sql server service account. I hope it will help
You can try this:
private boolean isConnectedToWifi(){
ConnectivityManager cm = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null){
NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
return nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
}
return false;
}
Add this code structure to your page code
<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=1900; $year<=date('Y'); $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>
It works perfectly and can be reverse engineered
<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=date('Y'); $year>=1900; $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>
With this you are good to go.
As c-smile mentioned: Just need to remove the apostrophes in the url()
:
<div style="background-image: url(http://i54.tinypic.com/4zuxif.jpg)"></div>
You need to use:
table{
width:100%;
table-layout: fixed;
overflow-wrap: break-word;
}
Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If
I think the problem may be that you are not finding your element because of the "#" in your call to get it:
window.parent.document.getElementById('#target');
You only need the # if you are using jquery. Here it should be:
window.parent.document.getElementById('target');
just do this
@Override
public void onBackPressed() {
super.onBackPressed();
}
This happens because of the way the windows paths interact. Your 32-bit JRE is listed BEFORE your 64-bit version. Since javaw.exe is named the same for both 32 and 64 bit versions, it tries the first one it finds. Change the order in your Path Environmental variables, so the 64-bit version higher on the list than the 32-bit, and it will work correctly.
As others mentioned before me....getting Python to work with MySQL on a Mac is a ?@#$@&%^!! nightmare.
Installed Django framework on Mac OS 10.7.5 initially from the original Django website and when the MySQLdb didn't work, and after many hours googling and trying solutions from SO, I have installed the Django stack from BitNami http://bitnami.com/stack/django
Still, got the issues mentioned above and then some more...
What helped me eventually is what Josh recommends on his blog: http://joshbranchaud.com/blog/2013/02/10/Errors-While-Setting-Up-Django.html
Now Python 2.7 is finally connected to MySQL 5.5
I think, that in this case using PYTHONPATH is a better thing, mostly because it doesn't introduce (questionable) unneccessary code.
After all, if you think of it, your user doesn't need that sys.path
thing, because your package will get installed into site-packages, because you will be using a packaging system.
If the user chooses to run from a "local copy", as you call it, then I've observed, that the usual practice is to state, that the package needs to be added to PYTHONPATH manually, if used outside the site-packages.
It depends on the language and the exact use. For instance, in C# 1 it made no difference. In C# 2, if the local variable is captured by an anonymous method (or lambda expression in C# 3) it can make a very signficant difference.
Example:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
List<Action> actions = new List<Action>();
int outer;
for (int i=0; i < 10; i++)
{
outer = i;
int inner = i;
actions.Add(() => Console.WriteLine("Inner={0}, Outer={1}", inner, outer));
}
foreach (Action action in actions)
{
action();
}
}
}
Output:
Inner=0, Outer=9
Inner=1, Outer=9
Inner=2, Outer=9
Inner=3, Outer=9
Inner=4, Outer=9
Inner=5, Outer=9
Inner=6, Outer=9
Inner=7, Outer=9
Inner=8, Outer=9
Inner=9, Outer=9
The difference is that all of the actions capture the same outer
variable, but each has its own separate inner
variable.
Want to format it automatically when you save the file???
then Goto Window > Preferences > Java > Editor > Save Actions
and configure your save actions.
Along with saving, you can format, Organize imports,add modifier ‘final’ where possible etc
Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.
import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;
//...
assertThat(result, is(new int[] {56, 100, 2000}));
Failure Trace output:
java.lang.AssertionError:
Expected: is [<56>, <100>, <2000>]
but: was [<55>, <100>, <2000>]
libs and Assets folder in Android Studio:
Create libs folder inside app folder and Asset folder inside main in the project directory by exploring project directory.
Now come back to Android Studio and switch the combo box from Android to Project. enjoy...
This maybe a bit off topic.
I was looking for a way to write this kind of information to the Docker log of my PHP-FPM container and came up with the snippet below. I'm sure this can be used by Docker PHP-FPM users.
fwrite(fopen('php://stdout', 'w'), var_export($object, true));
You can also set DirectoryIndex in apache's httpd.conf file.
CentOS keeps this file in /etc/httpd/conf/httpd.conf
Debian: /etc/apache2/apache2.conf
Open the file in your text editor and find the line starting with DirectoryIndex
To load landing.html as a default (but index.html if that's not found) change this line to read:
DirectoryIndex landing.html index.html
There is more into it aside from using a software. If you could create a bulk emailer program that sends intermittently. Say if you will send 5,000 recipients, create a loop that would send 38 lists per sending then pause for 10 seconds. I have an actual experience sending 500 manually per days for the past weeks and so far i have good results.
Another consideration are the content of your email. Nowadays it is a standard that you need to put your physical office address and the "unsubscribe" opt-out. These are factors that majority of recipient emails servers are checking. If you don't have these they will classify you as spammer.
Mailchimp is my best recommendation to use if you want a paid service provider in sending to your email subscriber NOT sending unsolicited or cold email marketing.
Hope it helps.
Yes, it is called Inline CSS, Here you styling the div
using some height, width, and background.
Here the example:
<div style="width:50px;height:50px;background color:red">
You can achieve same using Internal or External CSS
2.Internal CSS:
<head>
<style>
div {
height:50px;
width:50px;
background-color:red;
foreground-color:white;
}
</style>
</head>
<body>
<div></div>
</body>
3.External CSS:
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div></div>
</body>
style.css /external css file/
div {
height:50px;
width:50px;
background-color:red;
}
The problem is that you define it inside the class, which
a) means the second argument is implicit (this
) and
b) it will not do what you want it do, namely extend std::ostream
.
You have to define it as a free function:
class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
Just add -d32 to VM arguments in the "Edit launch configuration properties".
This generally means that the owning Hibernate session has already closed. You can do one of the following to fix it:
HibernateTemplate.initialize(object name)
lazy=false
in your hbm files.When you write 'array[index]' in C it translates it to machine instructions.
The translation is goes something like:
The result addresses something which may, or may not, be part of the array. In exchange for the blazing speed of machine instructions you lose the safety net of the computer checking things for you. If you're meticulous and careful it's not a problem. If you're sloppy or make a mistake you get burnt. Sometimes it might generate an invalid instruction that causes an exception, sometimes not.
I agree with Kevin and others, using a plugin for this is pointless.
window.scrollTo(0, $("#element").offset().top);
The Application.Volatile
doesn't work for recalculating a formula with my own function inside. I use the following function:
Application.CalculateFull
Try the code below to prevent the default behaviour scrolling back to the top of the page
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
For more information on event.preventDefault() have a look here at the official documentation.
NSLog(@"%s %d %s %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__);
Outputs file name, line number, and function name:
/proj/cocoa/cdcli/cdcli.m 121 managedObjectContext managedObjectContext
__FUNCTION__
in C++ shows mangled name __PRETTY_FUNCTION__
shows nice function name, in cocoa they look the same.
I'm not sure what is the proper way of disabling NSLog, I did:
#define NSLog
And no logging output showed up, however I don't know if this has any side effects.
If you're using Visual Studio you could also do "#pragma once" at the top of the headerfile to achieve the same thing as the "#ifndef ..."-wrapping. Some other compilers probably support it as well .. .. However, don't do this :D Stick with the #ifndef-wrapping to achieve cross-compiler compatibility. I just wanted to let you know that you could also do #pragma once, since you'll probably meet this statement quite a bit when reading other peoples code.
Good luck with it
Its very easy to implement . For that you need to create a one xml file(selector file) and put it in drawable folder in res. After that set xml file in button's background in your layout file.
<?xml version="1.0" encoding="UTF-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/your_hover_image" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/your_hover_image" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/your_hover_image"/>
<item android:drawable="@drawable/your_simple_image" />
</selector>
Now set the above file in button's background.
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/grey_text"
android:background="@drawable/button_background_selector"/>
JDO is dead
JDO is not dead actually so please check your facts. JDO 2.2 was released in Oct 2008 JDO 2.3 is under development.
This is developed openly, under Apache. More releases than JPA has had, and its ORM specification is still in advance of even the JPA2 proposed features
One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.
I am just going to show as a static example which you can accommodate in your real world.
On each of your <tr>
's add a data attribute for id
(i.e. data-id
) with the corresponding id value and specify a data-target
, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal
to make this a trigger for modal.
<tr data-toggle="modal" data-id="1" data-target="#orderModal">
<td>1</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="2" data-target="#orderModal">
<td>2</td>
<td>24234234</td>
<td>A</td>
</tr>
<tr data-toggle="modal" data-id="3" data-target="#orderModal">
<td>3</td>
<td>24234234</td>
<td>A</td>
</tr>
And now in the javascript just set up the modal just once and event listen to its events so you can do your work.
$(function(){
$('#orderModal').modal({
keyboard: true,
backdrop: "static",
show:false,
}).on('show', function(){ //subscribe to show method
var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
//make your ajax call populate items or what even you need
$(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow + '</b>'))
});
});
Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.
Alternative ways here:
The next version of dplyr will support an improved version of select that also incorporates renaming:
> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
disp2
Mazda RX4 160
Mazda RX4 Wag 160
Datsun 710 108
Hornet 4 Drive 258
Hornet Sportabout 360
Valiant 225
> changes( mtcars, mtcars2 )
Changed variables:
old new
disp 0x105500400
disp2 0x105500400
Changed attributes:
old new
names 0x106d2cf50 0x106d28a98
|| is the logical OR operator. It sounds like you basically know what that is. It's used in conditional statements such as if, while, etc.
condition1 || condition2
Evaluates to true if either condition1 OR condition2 is true.
| is the bitwise OR operator. It's used to operate on two numbers. You look at each bit of each number individually and, if one of the bits is 1 in at least one of the numbers, then the resulting bit will be 1 also. Here are a few examples:
A = 01010101
B = 10101010
A | B = 11111111
A = 00000001
B = 00010000
A | B = 00010001
A = 10001011
B = 00101100
A | B = 10101111
Hopefully that makes sense.
So to answer the last two questions, I wouldn't say there are any caveats besides "know the difference between the two operators." They're not interchangeable because they do two completely different things.
I'm using this to only enable a button if a listview item is selected (ie not null):
<Style TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=lvMyList, Path=SelectedItem}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
Ok, I will give a small example on how to do what you ask
public class ClassB extends Activity
{
ClassA A1 = new ClassA(this); // for activity context
ClassA A2 = new ClassA(getApplicationContext()); // for application context.
}
You might want to try int.TryParse(string, out int)
in the KeyPress(object, KeyPressEventArgs)
event to check for numeric values. For the other problem you could use regular expressions instead.
Some installations of Apache are fubar (think Oracle's packaging of it, OHS) and do not understand the -V flag, nor can be invoked directly without running into missing library errors.
Easiest way is to use the strings
command (part of binutils
) on the httpd binary and grep for a string that might resemble a version. For example, assuming your httpd
binary is under directory /foo/bar
:
$ strings /foo/bar/httpd | grep 2.2
GLIBC_2.2.5
Oracle-HTTP-Server/2.2.22 (Unix)
Success_Accepted_202
202 Accepted
Most binaries (not all) contain their version (at least their major version) as static strings. This is my go-to way to get versions (or to corroborate what a binary's help message matches what reality on the ground truly is.)
I use Wireshark in most cases, but I have found Fiddler to be less of a hassle when dealing with encrypted data.
Just in case if you're feeding this path to the Git itself, use :/
# this adds the whole working tree from any directory in the repo
git add :/
# and is equal to
git add $(git rev-parse --show-toplevel)
@Tim's answer only does half the work -- that gets it into a datetime.datetime object.
To get it into the string format you require, you use datetime.strftime:
print(datetime.strftime('%b %d,%Y'))
Although it is a bit strange, but the notifyDataSetChanged
does not really work without setting new values to adapter. So, you should do:
array = getNewItems();
((MyAdapter) mAdapter).setValues(array); // pass the new list to adapter !!!
mAdapter.notifyDataSetChanged();
This has worked for me.
In my case i had some problem with opacity transition so this one fix it:
#dropdown {
transition:.6s opacity;
}
#dropdown.ns {
opacity:0;
transition:.6s all;
}
#dropdown.fade {
opacity:1;
}
Mouse Enter
$('#dropdown').removeClass('ns').addClass('fade');
Mouse Leave
$('#dropdown').addClass('ns').removeClass('fade');
Scaffold(
appBar: AppBar(
title: Text('BMI CALCULATOR'),
),
body: Container(
height: 200,
width: 170,
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(
0xFF1D1E33,
),
borderRadius: BorderRadius.circular(5),
),
),
);