You can do that after you added the 'n' column into your df as follows.
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(10, 5))
df['mean'] = df.mean(1)
df
0 1 2 3 4 mean
0 0.929616 0.316376 0.183919 0.204560 0.567725 0.440439
1 0.595545 0.964515 0.653177 0.748907 0.653570 0.723143
2 0.747715 0.961307 0.008388 0.106444 0.298704 0.424512
3 0.656411 0.809813 0.872176 0.964648 0.723685 0.805347
4 0.642475 0.717454 0.467599 0.325585 0.439645 0.518551
5 0.729689 0.994015 0.676874 0.790823 0.170914 0.672463
6 0.026849 0.800370 0.903723 0.024676 0.491747 0.449473
7 0.526255 0.596366 0.051958 0.895090 0.728266 0.559587
8 0.818350 0.500223 0.810189 0.095969 0.218950 0.488736
9 0.258719 0.468106 0.459373 0.709510 0.178053 0.414752
### here you can add below line and it should work
# Don't forget the two (()) 'brackets' around columns names.Otherwise, it'll give you an error.
df = df[list(('mean',0, 1, 2,3,4))]
df
mean 0 1 2 3 4
0 0.440439 0.929616 0.316376 0.183919 0.204560 0.567725
1 0.723143 0.595545 0.964515 0.653177 0.748907 0.653570
2 0.424512 0.747715 0.961307 0.008388 0.106444 0.298704
3 0.805347 0.656411 0.809813 0.872176 0.964648 0.723685
4 0.518551 0.642475 0.717454 0.467599 0.325585 0.439645
5 0.672463 0.729689 0.994015 0.676874 0.790823 0.170914
6 0.449473 0.026849 0.800370 0.903723 0.024676 0.491747
7 0.559587 0.526255 0.596366 0.051958 0.895090 0.728266
8 0.488736 0.818350 0.500223 0.810189 0.095969 0.218950
9 0.414752 0.258719 0.468106 0.459373 0.709510 0.178053
The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable
.
So for that, here is what I did, when I came across the same problem.
string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };
foreach (string ColName in ColumnsToBeDeleted)
{
if (dt.Columns.Contains(ColName))
dt.Columns.Remove(ColName);
}
When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.
TextArea t = new TextArea();
t.setText("insert text when you want a new line add \nThen more text....);
setBounds();
setFont();
add(t);
This is the only way I was able to do it, maybe there is a simpler way but I havent discovered that yet.
This is an example of a MySQL date operation relevant to your question:
SELECT DATE_ADD( now( ) , INTERVAL -1 MONTH )
The above will return date time one month ago
So, you can use it, as follows:
SELECT *
FROM your_table
WHERE Your_Date_Column BETWEEN '2011-01-04'
AND DATE_ADD(NOW( ), INTERVAL -1 MONTH )
Sorry I've not tested this but I think it's done like this:
var filemap = new System.Configuration.ExeConfigurationFileMap();
System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(filemap, System.Configuration.ConfigurationUserLevel.None);
//usage: config.AppSettings["xxx"]
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
thisReader.GetString(int columnIndex)
Easily: Your data frame is A
b <- A[,1]
b <- b==1
b <- cumsum(b)
Then you get the column b.
I'd like to address a particular aspect of this question, as captured in this comment:
OAuth: before granting access to some feature, authentication must be done, right ?. so OAuth = what OpenId does + grants access to some features ? – Hassan Makarov Jun 21 at 1:57
Yes... and no. The answer is subtle, so bear with me.
When the OAuth flow redirects you to a target service (the OAuth provider, that is), it is likely that you'll need to authenticate with that service before a token will be handed back to the client application/service. The resulting token then allows the client app to make requests on behalf of a given user.
Note the generality of that last sentence: specifically, I wrote "on behalf of a given user", not "on behalf of you". It's a common error to assume that "having a capability to interact with a resource owned by a given user" implies "you and the owner of the target resource(s) are one in the same".
Don't make this mistake.
While it's true that you authenticate with the OAuth provider (say, by user name and password, or maybe SSL client certs, or some other means), what the client gets in return should not necessarily be taken as proof of identity. An example would be a flow in which access to another user's resources was delegated to you (and by proxy, the OAuth client). Authorization does not imply authentication.
To handle authentication, you'll likely want to look into OpenID Connect, which is essentially another layer on top of the foundation set by OAuth 2.0. Here's a quote that captures (in my opinion) the most salient points regarding OpenID Connect (from https://oauth.net/articles/authentication/):
OpenID Connect is an open standard published in early 2014 that defines an interoperable way to use OAuth 2.0 to perform user authentication. In essence, it is a widely published recipe for chocolate fudge that has been tried and tested by a wide number and variety of experts. Instead of building a different protocol to each potential identity provider, an application can speak one protocol to as many providers as they want to work with. Since it's an open standard, OpenID Connect can be implemented by anyone without restriction or intellectual property concerns.
OpenID Connect is built directly on OAuth 2.0 and in most cases is deployed right along with (or on top of) an OAuth infrastructure. OpenID Connect also uses the JSON Object Signing And Encryption (JOSE) suite of specifications for carrying signed and encrypted information around in different places. In fact, an OAuth 2.0 deployment with JOSE capabilities is already a long way to defining a fully compliant OpenID Connect system, and the delta between the two is relatively small. But that delta makes a big difference, and OpenID Connect manages to avoid many of the pitfalls discussed above by adding several key components to the OAuth base: [...]
The document then goes on to describe (among other things) token IDs and a UserInfo endpoint. The former provides a set of claims (who you are, when the token was issued, etc, and possibly a signature to verify the authenticity of the token via a published public key without having to ask the upstream service), and the latter provides a means of e.g. asking for the user's first/last name, email, and similar bits of info, all in a standardized way (as opposed to the ad-hoc extensions to OAuth that people used before OpenID Connect standardized things).
In Java a class can implement an interface. See http://en.wikipedia.org/wiki/Interface_(Java) for more details. Not sure about PHP.
Hope this helps.
Try placing $PATH at the end.
export PATH=/usr/local/git/bin:/usr/local/bin:$PATH
For me, the cause was using a specific Zookeeper that was not part of the Kafka package. That Zookeeper was already installed on the machine for other purposes. Apparently Kafka does not work with just any Zookeeper. Switching to the Zookeeper that came with Kafka solved it for me. To not conflict with the existing Zookeeper, I had to modify my confguration to have the Zookeeper listen on a different port:
[root@host /opt/kafka/config]# grep 2182 *
server.properties:zookeeper.connect=localhost:2182
zookeeper.properties:clientPort=2182
OFFSET is what you are looking for.
SELECT * FROM table LIMIT 10 OFFSET 10
Why don't you create a new object right in the .Select
:
.Select(x => new PInfo{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username }).ToList();
I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?
Create One Class With Name Startup this will help you..
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
I think you need a service
that handle the authentication process (and its storage).
In this service you'll need some basic methods :
isAuthenticated()
login()
logout()
This service should be injected in your controllers of each module :
service.isAuthenticated()
method) . if not, redirect to /loginservice.login()
methodA good and robust example for this behavior is the project angular-app and specifically its security module which is based over the awesome HTTP Auth Interceptor Module
Hope this helps
bootstrap.min.css is more specific than your own stylesheet if you just use .table td. So use this instead:
.table>tbody>tr>th, .table>tbody>tr>td {
border-top: none;
}
There is also an alternative way to use MarkupExtension
in order to use Binding
for a ConverterParameter
. With this solution you can still use the default IValueConverter
instead of the IMultiValueConverter
because the ConverterParameter
is passed into the IValueConverter
just like you expected in your first sample.
Here is my reusable MarkupExtension
:
/// <summary>
/// <example>
/// <TextBox>
/// <TextBox.Text>
/// <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
/// Converter="{StaticResource TestValueConverter}"
/// ConverterParameterBinding="{Binding ConcatSign}" />
/// </TextBox.Text>
/// </TextBox>
/// </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
#region Public Properties
public Binding Binding { get; set; }
public BindingMode Mode { get; set; }
public IValueConverter Converter { get; set; }
public Binding ConverterParameter { get; set; }
#endregion
public ConverterBindableParameter()
{ }
public ConverterBindableParameter(string path)
{
Binding = new Binding(path);
}
public ConverterBindableParameter(Binding binding)
{
Binding = binding;
}
#region Overridden Methods
public override object ProvideValue(IServiceProvider serviceProvider)
{
var multiBinding = new MultiBinding();
Binding.Mode = Mode;
multiBinding.Bindings.Add(Binding);
if (ConverterParameter != null)
{
ConverterParameter.Mode = BindingMode.OneWay;
multiBinding.Bindings.Add(ConverterParameter);
}
var adapter = new MultiValueConverterAdapter
{
Converter = Converter
};
multiBinding.Converter = adapter;
return multiBinding.ProvideValue(serviceProvider);
}
#endregion
[ContentProperty(nameof(Converter))]
private class MultiValueConverterAdapter : IMultiValueConverter
{
public IValueConverter Converter { get; set; }
private object lastParameter;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (Converter == null) return values[0]; // Required for VS design-time
if (values.Length > 1) lastParameter = values[1];
return Converter.Convert(values[0], targetType, lastParameter, culture);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
if (Converter == null) return new object[] { value }; // Required for VS design-time
return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
}
}
}
With this MarkupExtension
in your code base you can simply bind the ConverterParameter
the following way:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
Converter="{StaticResource AccessLevelToVisibilityConverter}"
ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />
</Setter.Value>
</Setter>
Which looks almost like your initial proposal.
You can rewrite the code likes this:
#include<iostream>
#include<stdio.h>
using namespace std;
Using guava you can just do something like Sets.newHashSet(charArray).toArray();
If you are not using any libraries, you can still use new HashSet<Char>()
and add your char
array there.
Effbot (aka Fredrik Lundh) has described Python's variable passing style as call-by-object: http://effbot.org/zone/call-by-object.htm
Objects are allocated on the heap and pointers to them can be passed around anywhere.
When you make an assignment such as x = 1000
, a dictionary entry is created that maps the string "x" in the current namespace to a pointer to the integer object containing one thousand.
When you update "x" with x = 2000
, a new integer object is created and the dictionary is updated to point at the new object. The old one thousand object is unchanged (and may or may not be alive depending on whether anything else refers to the object).
When you do a new assignment such as y = x
, a new dictionary entry "y" is created that points to the same object as the entry for "x".
Objects like strings and integers are immutable. This simply means that there are no methods that can change the object after it has been created. For example, once the integer object one-thousand is created, it will never change. Math is done by creating new integer objects.
Objects like lists are mutable. This means that the contents of the object can be changed by anything pointing to the object. For example, x = []; y = x; x.append(10); print y
will print [10]
. The empty list was created. Both "x" and "y" point to the same list. The append method mutates (updates) the list object (like adding a record to a database) and the result is visible to both "x" and "y" (just as a database update would be visible to every connection to that database).
Hope that clarifies the issue for you.
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:
select * from
(
select object_name objname, object_type, 'my object' details, 1 resolveOrder
from user_objects
where object_type not like 'SYNONYM'
union all
select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
from user_synonyms
union all
select synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')
I know this is late, but it does answer your original question.
/*Read the comments the same way that SQL runs the query
1) FROM
2) GROUP
3) SELECT
4) My final notes at the bottom
*/
SELECT
list.invoiceid
, cust.customernumber
, MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
, MAX(list.inv_amount) - SUM(list.pay_amount) AS [amount_due]
FROM
Customers AS cust
INNER JOIN
Payments AS pay
ON
pay.customerid = cust.customerid
INNER JOIN ( /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
SELECT
inpay.paymentid AS paymentid
, inv.invoiceid AS invoiceid
, inv.amount AS inv_amount
, pay.amount AS pay_amount
FROM
InvoicePayments AS inpay
INNER JOIN
Invoices AS inv
ON inv.invoiceid = inpay.invoiceid
INNER JOIN
Payments AS pay
ON pay.paymentid = inpay.paymentid
) AS list
ON
list.paymentid = pay.paymentid
/* so at this point my result set would look like:
-- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
-- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list)
-- Filter out all records in A that do not have a paymentid matching in (list)
-- we filter the result because there may be payments that did not go towards invoices!
*/
GROUP BY
/* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */
cust.customernumber
, list.invoiceid
/*
-- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery,
-- but this is what made sense to me when I was planning.
-- Hopefully it makes it clearer how the thought process works to leave it in there
-- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/
if (Control.ModifierKeys == Keys.Shift)
//Shift is pressed
The cursor x/y position is a property, and a keypress (like a mouse click/mousemove) is an event. Best practice is usually to let the interface be event driven. About the only time you would need the above is if you're trying to do a shift + mouseclick thing.
If you want to change the background color of the backdrop for a specific modal, you can access the backdrop element in this way:
$('#myModal').data('bs.modal').$backdrop
Then you can change any css property via .css jquery function. In particular, with background:
$('#myModal').data('bs.modal').$backdrop.css('background-color','orange')
Note that $('#myModal') has to be initialized, otherwise $backdrop is going to be null. Same applies to bs.modal data element.
$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter
If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
<?php
if ($_GET) {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
} else {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
?>
To call from command line chmod 755 /var/www/webroot/index.php
and use
/usr/bin/php /var/www/webroot/index.php arg1 arg2
To call from the browser, use
http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2
It may be something like this in HTML:
<div class="container-outer">
<div class="container-inner">
<!-- Your images over here -->
</div>
</div>
With this stylesheet:
.container-outer { overflow: scroll; width: 500px; height: 210px; }
.container-inner { width: 10000px; }
You can even create an intelligent script to calculate the inner container width, like this one:
$(document).ready(function() {
var container_width = SINGLE_IMAGE_WIDTH * $(".container-inner a").length;
$(".container-inner").css("width", container_width);
});
Had need of this myself, so I wrote a String extension that both allows for URLEncoding strings, as well as the more common end goal, converting a parameter dictionary into "GET" style URL Parameters:
extension String {
func URLEncodedString() -> String? {
var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
return escapedString
}
static func queryStringFromParameters(parameters: Dictionary<String,String>) -> String? {
if (parameters.count == 0)
{
return nil
}
var queryString : String? = nil
for (key, value) in parameters {
if let encodedKey = key.URLEncodedString() {
if let encodedValue = value.URLEncodedString() {
if queryString == nil
{
queryString = "?"
}
else
{
queryString! += "&"
}
queryString! += encodedKey + "=" + encodedValue
}
}
}
return queryString
}
}
Enjoy!
To remove new lines from string, follow the below code
$newstring = preg_replace("/[\n\r]/","",$subject);
Your are probably looking for eval $var
.
Try:
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();
oSheet.Cells[3, 9] = "Some Text"
When bash interprets the command line, it looks for commands in locations described in the environment variable $PATH
. To see it type:
echo $PATH
You will have some paths separated by colons. As you will see the current path .
is usually not in $PATH
. So Bash cannot find your command if it is in the current directory. You can change it by having:
PATH=$PATH:.
This line adds the current directory in $PATH
so you can do:
manage.py syncdb
It is not recommended as it has security issue, plus you can have weird behaviours, as .
varies upon the directory you are in :)
Avoid:
PATH=.:$PATH
As you can “mask” some standard command and open the door to security breach :)
Just my two cents.
To remove the .html extension from your urls, you can use the following code in root/htaccess :
RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]
NOTE: If you want to remove any other extension, for example to remove the .php extension, just replace the html everywhere with php in the code above.
For unit tests, you can use CollectionAssert.AreEqual
instead of Assert.AreEqual
.
It is probably the easiest way.
One can also use a test ApplicationContextInitializer to initialize a system property:
public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
@Override
public void initialize(ConfigurableApplicationContext applicationContext)
{
System.setProperty("myproperty", "value");
}
}
and then configure it on the test class in addition to the Spring context config file locations:
@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}
This way code duplication can be avoided if a certain system property should be set for all the unit tests.
hmm, well here's a workaround anyway:
function JSON_stringify(s, emit_unicode)
{
var json = JSON.stringify(s);
return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
test case:
js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"
This is the latest async/await
pattern solution.
export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {
const res: Response = await fetch(dataUrl);
const blob: Blob = await res.blob();
return new File([blob], fileName, { type: 'image/png' });
}
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
This should work:
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
The other answers will give you a good idea how to accomplish what you have asked for....
However
There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.
That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.
I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev). You get the Input stream of the image (from web)
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation).
When an event is triggered on an element, the following occurs:
The event is dispatched to its target
EventTarget
and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following theEventTarget
's parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including theDocument
.
Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here's an example of it in practice:
<ul onclick="alert(event.type + '!')">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
With that example if you were to click on any of the child <li>
nodes, you would see an alert of "click!"
, even though there is no click handler bound to the <li>
you clicked on. If we bound onclick="..."
to each <li>
you would get the same effect.
So what's the benefit?
Imagine you now have a need to dynamically add new <li>
items to the above list via DOM manipulation:
var newLi = document.createElement('li');
newLi.innerHTML = 'Four';
myUL.appendChild(newLi);
Without using event delegation you would have to "rebind" the "onclick"
event handler to the new <li>
element, in order for it to act the same way as its siblings. With event delegation you don't need to do anything. Just add the new <li>
to the list and you're done.
This is absolutely fantastic for web apps with event handlers bound to many elements, where new elements are dynamically created and/or removed in the DOM. With event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.
Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user's navigate to different pages often). But for long-lived applications it can be significant. There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I'm looking at you).
Here are some better concrete code examples of event delegation:
focus
and blur
events (which do not bubble)Quick and dirty:
#!/usr/bin/perl -w
use strict;
open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);
foreach(@lines) {
$_ =~ s/<PREF>/ABCD/g;
}
open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.
public T[] toArray(T[] a) - In this method we create a array with size of arraylist and pass it as argument and it will return array of element of arraylist
String[] arr = new String[list.size()];
arr = list.toArray(arr);
Java doesn't overload operators, so you'll usually need a method for non-basic types. Try the Arrays.equals() method.
//simple function to determine if a number is a prime number
//to state if it is a prime number
#include <iostream>
using namespace std;
int isPrime(int x); //functioned defined after int main()
int main()
{
int y;
cout<<"enter value"<<endl;
cin>>y;
isPrime(y);
return 0;
} //end of main function
//-------------function
int isPrime(int x)
{
int counter =0;
cout<<"factors of "<<x<<" are "<<"\n\n"; //print factors of the number
for (int i =0; i<=x; i++)
{
for (int j =0; j<=x; j++)
{
if (i * j == x) //check if the number has multiples;
{
cout<<i<<" , "; //output provided for the reader to see the
// muliples
++counter; //counts the number of factors
}
}
}
cout<<"\n\n";
if(counter>2)
{
cout<<"value is not a prime number"<<"\n\n";
}
if(counter<=2)
{
cout<<"value is a prime number"<<endl;
}
}
It depends.
Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding
And if none of those meet your particular needs, you could even look at using some kind of Database
In the WPF application, you can handle this by handling TextChanged
event:
void arsDigitTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
bool handle = regex.IsMatch(this.Text);
if (handle)
{
StringBuilder dd = new StringBuilder();
int i = -1;
int cursor = -1;
foreach (char item in this.Text)
{
i++;
if (char.IsDigit(item))
dd.Append(item);
else if(cursor == -1)
cursor = i;
}
this.Text = dd.ToString();
if (i == -1)
this.SelectionStart = this.Text.Length;
else
this.SelectionStart = cursor;
}
}
you can also do this
$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);
this is a better option if you set value on controller
$model = new SomeModelName();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->group_id]);
} else {
$model->hidden1 = 'your value';
return $this->render('create', [
'model' => $model,
]);
}
the following two ways work well:
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json
if the collections are under a specific user, you can use -u -p --authenticationDatabase
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid, String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password); System.out.println("connected"); Statement statement = conn.createStatement(); String queryString = "select * from cpl"; ResultSet rs = statement.executeQuery(queryString); while (rs.next()) { System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB", "sa", "0123");
}
}
In woocommerce,
Get regular price :
$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price
Get sale price:
$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price
>>> () is () True >>> 1 is 1 True >>> (1,) == (1,) True >>> (1,) is (1,) False >>> a = (1,) >>> b = a >>> a is b True
Some objects are singletons, and thus is
with them is equivalent to ==
. Most are not.
if anyone else has problem with the above mentioned solutions, I ended up just going for the event:
$("#jquery_audioPlayer").jPlayer({
ready:function () {
$(this).jPlayer("setMedia", {
mp3:"media/song.mp3"
})
...
pause: function () {
$('#yoursoundcontrol').click(function () {
$("#jquery_audioPlayer").jPlayer('play');
})
},
play: function () {
$('#yoursoundcontrol').click(function () {
$("#jquery_audioPlayer").jPlayer('pause');
})}
});
works for me.
refer to: How to get charles proxy work with Android 7 nougat?
From your computer, run Charles:
Open Proxy Settings: Proxy -> Proxy Settings, Proxies Tab, check "Enable transparent HTTP proxying", and remember "Port" in heart.
SSL Proxy Settings:Proxy -> SSL Proxy Settings, SSL Proxying tab, Check “enable SSL Proxying”, and add . to Locations:
Open Access Control Settings: Proxy -> Access Control Settings. Add your local subnet to authorize machines on you local network to use the proxy from another machine/mobile.
In Android Phone:
Configure your mobile: Go to Settings -> Wireless & networks -> WiFi -> Connect or modify your network, fill in the computer IP address and Port(8888):
Get Charles SSL Certificate. Visit this url from your mobile browser: http://charlesproxy.com/getssl
In “Name the certificate” enter whatever you want
Accept the security warning and install the certificate. If you install it successful, then you probably see sth like that: In your phone, Settings -> Security -> Trusted credentials:
Done.
then you can have some test on your mobile, the encrypted https request will be shown in Charles:
I faced this issue because my selector was depend on id
meanwhile I did not set id for my element
my selector
was
$("#EmployeeName")
but my HTML element
<input type="text" name="EmployeeName">
so just make sure that your selector criteria are valid
I had this same problem in a Maven project. After creating the src/test/java folder within the project the error went away.
You're not including the C file that contains main()
when compiling, so the linker isn't seeing it.
You need to add it:
$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp
Whether it's trivial or hard to crack, I'm not sure that it really makes much of a difference.
The likelihood of your app being cracked is far more proportional to its usefulness rather than the strength of the product key handling.
Personally, I think there are two classes of user. Those who pay. Those who don't. The ones that do will likely do so with even the most trivial protection. Those who don't will wait for a crack or look elsewhere. Either way, it won't get you any more money.
Few answers have given a solution with height and width 100% but I recommend you to not use percentage in css, use top/bottom and left/right positionning.
This is a better approach that allow you to control margin.
Here is the code :
body {
position: relative;
height: 3000px;
}
body div {
top:0px;
bottom: 0px;
right: 0px;
left:0px;
background-color: yellow;
position: absolute;
}
As per MSDN, In a case of spreadsheets inside of Excel it might not work because Excel files are not real databases. So you will be not able to get the sheets name in order of their visualization in workbook.
Code to get sheets name as per their visual appearance using interop:
Add reference to Microsoft Excel 12.0 Object Library.
Following code will give the sheets name in the actual order stored in workbook, not the sorted name.
Sample Code:
using Microsoft.Office.Interop.Excel;
string filename = "C:\\romil.xlsx";
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb =excel.Workbooks.Open(filename, missing, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
ArrayList sheetname = new ArrayList();
foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in wb.Sheets)
{
sheetname.Add(sheet.Name);
}
To escape XML characters, the easiest way is to use the Apache Commons Lang project, JAR downloadable from: http://commons.apache.org/lang/
The class is this: org.apache.commons.lang3.StringEscapeUtils;
It has a method named "escapeXml", that will return an appropriately escaped String.
page 1 : Detail page 2 : <% String id = request.getParameter("userid");%> // now you can using id for sql query of hsql detail product
(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...]
like this:
library(gsubfn) # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()
If you only need the first or second component these all work too:
list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()
(Of course, if you only needed one value then functionReturningTwoValues()[[1]]
or functionReturningTwoValues()[[2]]
would be sufficient.)
See the cited r-help thread for more examples.
(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with
:
myfun <- function() list(a = 1, b = 2)
list[a, b] <- myfun()
a + b
# same
with(myfun(), a + b)
(3) attach Another alternative is attach:
attach(myfun())
a + b
ADDED: with
and attach
If you have Existing Git repository:
cd existing_repo
git remote rename origin old-origin
git remote add origin https://gitlab.com/newproject
git push -u origin --all
git push -u origin --tags
If you have allow_url_fopen
set to true
:
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
Else use cURL:
$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
If you have included the assembly in your project, you can do :
var assemblies =
AppDomain.CurrentDomain.GetAssemblies();
foreach (var assem in assemblies)
{
Console.WriteLine(assem.FullName);
}
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
Use the valgrind option --track-origins=yes
to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])**
correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list? should it be x[2][2]?
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
Hope here is the exact what we are looking for.
private void button2_Click(object sender, RoutedEventArgs e)
{
UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}
private void UpdateExcel(string sheetName, int row, int col, string data)
{
Microsoft.Office.Interop.Excel.Application oXL = null;
Microsoft.Office.Interop.Excel._Workbook oWB = null;
Microsoft.Office.Interop.Excel._Worksheet oSheet = null;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];
oSheet.Cells[row, col] = data;
oWB.Save();
MessageBox.Show("Done!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (oWB != null)
oWB.Close();
}
}
Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:
with open('Path/to/file', 'r') as content_file:
content_list = content_file.read().strip().split("\n")
As can be seen, one needs to add the concatenated methods .strip().split("\n")
to the main answer in this thread.
Here, .strip()
just removes whitespace and newline characters at the endings of the entire file string,
and .split("\n")
produces the actual list via splitting the entire file string at every newline character \n.
Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.
As user1767754 said, the key here is to not make any selection initially.
Just place the cursor inside the variable name, don't double click to select it. For single character variables, place the cursor at the front or end of the variable to not make any selection initially.
Now keep hitting Cmd+D for next variable selection or Ctrl+Cmd+G for selecting all variables at once. It will magically select only the variables.
You can %HOMEDRIVE%%HOMEPATH%
for the drive + \docs settings\username
or \users\username
.
I know this is an old post, however I thought I'd share the method I use to remove new line characters.
s.Replace(Environment.NewLine, "");
References:
MSDN String.Replace Method and MSDN Environment.NewLine Property
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
Take a look at the jQuery alphanumeric plugin. https://github.com/KevinSheedy/jquery.alphanum
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});
if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:
select
psat.schemaname,
psat.relname,
pa.attname,
psat.relid
from
pg_catalog.pg_stat_all_tables psat,
pg_catalog.pg_attribute pa
where
psat.relid = pa.attrelid
change schema name:
ALTER SCHEMA "XXXXX" RENAME TO xxxxx;
change table names:
ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;
change column names:
ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
You can also just send the user name by writing:
curl -u USERNAME http://server.example
Curl will then ask you for the password, and the password will not be visible on the screen (or if you need to copy/paste the command).
To create simple hover enlarge plugin, try this. (DEMO)
HTML
<div id="content">
<img src="http://www.freevectorgallery.com/wp-content/uploads/2011/10/Vintage-Microphone- 11395-large.jpg" style="width:50%;" />
</div>
js
$(function () {
$('#content img').hover(function () {
$(this).toggle(function () {
$(this).width('70%');
});
});
});
I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :
Note: Ports 80 and 443 must be unused by any program.
If it is in use . Just edit ports. There is a lot of tutorials about that .
I guess there is an alternative way to achieve what you are looking for. I don't say its a complete solution but it served the purpose in my case.
What I did is instead of replacing the fragment I just added target fragment.
So basically you will be going to use add()
method instead replace()
.
What else I did. I hide my current fragment and also add it to backstack.
Hence it overlaps new fragment over the current fragment without destroying its view.(check that its onDestroyView()
method is not being called. Plus adding it to backstate
gives me the advantage of resuming the fragment.
Here is the code :
Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();
AFAIK System only calls onCreateView()
if the view is destroyed or not created.
But here we have saved the view by not removing it from memory. So it will not create a new view.
And when you get back from Destination Fragment it will pop the last FragmentTransaction
removing top fragment which will make the topmost(SourceFragment's) view to appear over the screen.
COMMENT: As I said it is not a complete solution as it doesn't remove the view of Source fragment and hence occupying more memory than usual. But still, serve the purpose. Also, we are using a totally different mechanism of hiding view instead of replacing it which is non traditional.
So it's not really for how you maintain the state, but for how you maintain the view.
Old question but.. I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer
works both in browser and Node. See documentation for all features.
Difference between Abstraction and Encapsulation :-
Abstraction
Encapsulation
In typescript with object/generic way, it could be alse implemented:
export interface INestedIterator<T> {
getChildren(): T[];
}
export class NestedIterator {
private static forEach<T extends INestedIterator<T>>(obj: T, fn: ((obj: T) => void)): void {
fn(obj);
if (obj.getChildren().length) {
for (const item of obj.getChildren()) {
NestedIterator.forEach(item, fn);
};
}
}
}
than you can implement interface INestedIterator<T>
:
class SomeNestedClass implements INestedIterator<SomeNestedClass>{
items: SomeNestedClass[];
getChildren() {
return this.items;
}
}
and then just call
NestedIterator.forEach(someNesteObject, (item) => {
console.log(item);
})
if you don't want use interfaces and strongly typed classes, just remove types
export class NestedIterator {
private static forEach(obj: any, fn: ((obj: any) => void)): void {
fn(obj);
if (obj.items && obj.items.length) {
for (const item of obj.items) {
NestedIterator.forEach(item, fn);
};
}
}
}
Here's a simple one that I often use:
# Set up logging to include a file record of the output
# Note: the file is always created, even if there is
# no actual output.
log4j.rootLogger=error, stdout, R
# Log format to standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n
# File based log output
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=owls_conditions.log
log4j.appender.R.MaxFileSize=10000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern= %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n
The format of the log is as follows:
ERROR [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44)
http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog.
Such a format is defined by the string %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n
. You can read the meaning of conversion characters in log4j javadoc for PatternLayout
.
Included comments should help in understanding what it does. Further notes:
owls_conditions.log
: change it according to your needs;I would recommend doing it in collectionView: willDisplay:
Then you can be sure that the collection view delegate delivers something.
Here my example:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
/// this is done to set the index on start to 1 to have at index 0 the last image to have a infinity loop
if !didScrollToSecondIndex {
self.scrollToItem(at: IndexPath(row: 1, section: 0), at: .left, animated: false)
didScrollToSecondIndex = true
}
}
CURL request by default is GET, you don't have to set any options to make a GET CURL request.
For me the simple solution works to set cookies in HttpRequestMessage object.
protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");
return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}
The direct methods and .delegate
are superior APIs to .on
and there is no intention of deprecating them.
The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an
event name rather than a silent bug. In my opinion, it's also easier to write and read click
than on("click"
The .delegate
is superior to .on
because of the argument's order:
$(elem).delegate( ".selector", {
click: function() {
},
mousemove: function() {
},
mouseup: function() {
},
mousedown: function() {
}
});
You know right away it's delegated because, well, it says delegate. You also instantly see the selector.
With .on
it's not immediately clear if it's even delegated and you have to look at the end for the selector:
$(elem).on({
click: function() {
},
mousemove: function() {
},
mouseup: function() {
},
mousedown: function() {
}
}, "selector" );
Now, the naming of .bind
is really terrible and is at face value worse than .on
. But .delegate
cannot do non-delegated events and there
are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
I followed everything from here: https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair
But still there was an error and SSH keys in my instance metadata wasn't getting recognized.
Solution: Check if your ssh key has any new-line. When I copied my public key using cat, it added into-lines into the key, thus breaking the key. Had to manually check any line-breaks and correct it.
You can try
echo implode(', ', (array)$ret);
Try this
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");
Just like in this question (npm global path prefix) all you need is to set proper npm prefix
.
UNIX:
$ npm config set prefix /usr/local
$ npm install -g bower
$ which bower
>> /usr/local/bin/bower
Windows ans NVM:
$ npm config set prefix /c/Users/xxxxxxx/AppData/Roaming/nvm/v8.9.2
$ npm install -g bower
Then bower
should be located just in your $PATH
.
I was trying to do the same thing and this is what worked for me (ES6/ES2015):
import myData from './data.json';
I got the solution from this answer on a react-native thread asking the same thing: https://stackoverflow.com/a/37781882/176002
I had this problem - I eventually worked out that the reason was that I'd included \
characters in the string. If you have any of these, "escape" them with \\
and it should work fine.
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Here's how i finally created the ~/.android/debug.keystore file.
First some background. I got a new travel laptop. Installed Android Studio. Cloned my android project from git hub. The project would not run. Finally figured out that the debug.keystore was not created ... and i could not figure out how to get Android Studio to create it.
Finally, i created a new blank project ... and that created the debug.keystore!
Hope this helps other who have this problem.
I installed it successfully using these commands:
sudo apt-get install libpq-dev python-dev
pip install psycopg2
You can update with a join if you only affect one table like this:
UPDATE table1
SET table1.name = table2.name
FROM table1, table2
WHERE table1.id = table2.id
AND table2.foobar ='stuff'
But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.
However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.
But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.
Along with @PaulStock's answer, Depending on your connection type, your variable names and SQLStatement/SQLStatementSource Changes
https://docs.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task
I will make my contribution here... why? just because :p Its a different implementation, based on the Any LINQ extension, and a delegate. Here it is:
public static class Extensions
{
public static int IndexOf<T>(
this IEnumerable<T> list,
Predicate<T> condition) {
int i = -1;
return list.Any(x => { i++; return condition(x); }) ? i : -1;
}
}
void Main()
{
TestGetsFirstItem();
TestGetsLastItem();
TestGetsMinusOneOnNotFound();
TestGetsMiddleItem();
TestGetsMinusOneOnEmptyList();
}
void TestGetsFirstItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("a"));
// Assert
if(index != 0)
{
throw new Exception("Index should be 0 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsLastItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("d"));
// Assert
if(index != 3)
{
throw new Exception("Index should be 3 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnNotFound()
{
// Arrange
var list = new string[] { "a", "b", "c", "d" };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMinusOneOnEmptyList()
{
// Arrange
var list = new string[] { };
// Act
int index = list.IndexOf(item => item.Equals("e"));
// Assert
if(index != -1)
{
throw new Exception("Index should be -1 but is: " + index);
}
"Test Successful".Dump();
}
void TestGetsMiddleItem()
{
// Arrange
var list = new string[] { "a", "b", "c", "d", "e" };
// Act
int index = list.IndexOf(item => item.Equals("c"));
// Assert
if(index != 2)
{
throw new Exception("Index should be 2 but is: " + index);
}
"Test Successful".Dump();
}
You should create a startup.bat
if you're using Windows, much more convenient:
C:\mongodb\mongodb-win32-x86_64-eiditon\bin\mongod.exe --dbpath C:\mongodb\data
And just dbclick startup.bat and mongodb will run using C:\mongodb\data
as its data folder.
What I found out is that while m2e is looking for v2.5 by default, my local repo has 2.6 and no 2.5.
Without going into investigation of how this came about simply adding the dependency to pom solved the problem
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</dependency>
This can be removed after running a build once
Marquis of Lorne's answer is accurate, I'm adding some info for debugging purposes:
To debug this issue (I wrote about it with more details in here) and understand what truststore is being used (or trying to use) you can add the property javax.net.debug=all and then filter the logs about truststore. You can also play with the property javax.net.ssl.trustStore to specify a specific truststore. For example :
java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=/Another/path/to/cacerts -jar test_get_https-0.0.1-SNAPSHOT-jar-with-dependencies.jar https://www.calca.com.py 2>&1| grep -i truststore
Alert: This answer is for MacOS only
Let suppose you have 2 versions of nodeJS inside your nvm, namely v13.10.1 & v15.4.0
And, v15.4.0 is default
> nvm list
v13.10.1
-> v15.4.0
system
default -> 15.4.0 (-> v15.4.0)
And, you want to switch the default to v13.10.1
Follow these steps on your Mac terminal:
Run the command:
nvm alias default 13.10.1
This will make the default point to v13.10.1 as...
default -> 13.10.1 (-> v13.10.1)
node -v
You will get...
v13.10.1
nvm list will also show the new default version.
nvm list
Just an info: The NodeJS versions taken as example above will have their different npm versions. You can cross-verify it in terminal by running npm -v
select orderID, sum(subtotal) as order_total from
(
select orderID, productID, price, qty, price * qty as subtotal
from product p inner join orderitem o on p.id = o.productID
where o.orderID = @orderID
) t
group by orderID
I guess you will have to bind the method to the React’s class instance. It’s safer to use a constructor to bind all methods in React. In your case when you pass the parameter to the method, the first parameter is used to bind the ‘this’ context of the method, thus you cannot access the value inside the method.
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
This is a small adition to @Andrew Dunn's post above
Combining the 2 is possible to generate readable JS and matching output
var foo = "Bob\n\
is\n\
cool.\n\";
You can create an extension for UIView to access these values in the design editor
extension UIView{
@IBInspectable var shadowOffset: CGSize{
get{
return self.layer.shadowOffset
}
set{
self.layer.shadowOffset = newValue
}
}
@IBInspectable var shadowColor: UIColor{
get{
return UIColor(cgColor: self.layer.shadowColor!)
}
set{
self.layer.shadowColor = newValue.cgColor
}
}
@IBInspectable var shadowRadius: CGFloat{
get{
return self.layer.shadowRadius
}
set{
self.layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOpacity: Float{
get{
return self.layer.shadowOpacity
}
set{
self.layer.shadowOpacity = newValue
}
}
}
To expand on my comment.
You can validate on the command line using php -l [filename]
, which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.
Here's an example of the output when run on a file containing:
<?php
echo no quotes or semicolon
Results in:
PHP Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2
Errors parsing badfile.php
I suggested you build your own validator.
A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l
and echos the output.
Note: this is not a security risk it does not execute the file, just checks for syntax errors.
Here's a really basic example of creating your own:
<?php
if (isset($_FILES['file'])) {
echo '<pre>';
passthru('php -l '.$_FILES['file']['tmp_name']);
echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
You should also try -ggdb instead of -g if you're compiling for Android!
Your terminal happens to be configured to UTF-8.
The fact that printing a
works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a
is a value of length two, containing two bytes, hex values C3 and A1, while ua
is a unicode value of length one, containing a codepoint U+00E1.
This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len()
of a byte string tells you how many bytes were used, not how many characters were encoded.
You can see the difference when you encode the unicode value to different output encodings:
>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'
Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.
Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x..
escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u....
is used instead, with a four-digit hex value.
It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:
Yo,
This is how you do it if you want just one type of holder stick when it starts getting out of the screen (we are not caring about any sections). There is only one way without breaking the internal RecyclerView logic of recycling items and that is to inflate additional view on top of the recyclerView's header item and pass data into it. I'll let the code speak.
import android.graphics.Canvas
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
class StickyHeaderItemDecoration(@LayoutRes private val headerId: Int, private val HEADER_TYPE: Int) : RecyclerView.ItemDecoration() {
private lateinit var stickyHeaderView: View
private lateinit var headerView: View
private var sticked = false
// executes on each bind and sets the stickyHeaderView
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val position = parent.getChildAdapterPosition(view)
val adapter = parent.adapter ?: return
val viewType = adapter.getItemViewType(position)
if (viewType == HEADER_TYPE) {
headerView = view
}
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
if (::headerView.isInitialized) {
if (headerView.y <= 0 && !sticked) {
stickyHeaderView = createHeaderView(parent)
fixLayoutSize(parent, stickyHeaderView)
sticked = true
}
if (headerView.y > 0 && sticked) {
sticked = false
}
if (sticked) {
drawStickedHeader(c)
}
}
}
private fun createHeaderView(parent: RecyclerView) = LayoutInflater.from(parent.context).inflate(headerId, parent, false)
private fun drawStickedHeader(c: Canvas) {
c.save()
c.translate(0f, Math.max(0f, stickyHeaderView.top.toFloat() - stickyHeaderView.height.toFloat()))
headerView.draw(c)
c.restore()
}
private fun fixLayoutSize(parent: ViewGroup, view: View) {
// Specs for parent (RecyclerView)
val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED)
// Specs for children (headers)
val childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, parent.paddingLeft + parent.paddingRight, view.getLayoutParams().width)
val childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, parent.paddingTop + parent.paddingBottom, view.getLayoutParams().height)
view.measure(childWidthSpec, childHeightSpec)
view.layout(0, 0, view.measuredWidth, view.measuredHeight)
}
}
And then you just do this in your adapter:
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
recyclerView.addItemDecoration(StickyHeaderItemDecoration(R.layout.item_time_filter, YOUR_STICKY_VIEW_HOLDER_TYPE))
}
Where YOUR_STICKY_VIEW_HOLDER_TYPE is viewType of your what is supposed to be sticky holder.
For those of you who don't want to create a bat file to edit for every project, or dont want to remember all the commands associated with the keytools and jarsigner programs and just want to get it done in one process use this program:
http://lukealderton.com/projects/programs/android-apk-signer-aligner.aspx
I built it because I was fed up with the lengthy process of having to type all the file locations every time.
This program can save your configuration so the next time you start it, you just need to hit Generate an it will handle it for you. That's it.
No install required, it's completely portable and saves its configurations in a CSV in the same folder.
An attribute is another term for a field. It's typically a public constant or a public variable that can be accessed directly. In this particular case, the array in Java is actually an object and you are accessing the public constant value that represents the length of the array.
@JsonSerialize and @JsonDeserialize worked fine for me. They eliminate the need to import the additional jsr310 module:
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate dateOfBirth;
Deserializer:
public class LocalDateDeserializer extends StdDeserializer<LocalDate> {
private static final long serialVersionUID = 1L;
protected LocalDateDeserializer() {
super(LocalDate.class);
}
@Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
return LocalDate.parse(jp.readValueAs(String.class));
}
}
Serializer:
public class LocalDateSerializer extends StdSerializer<LocalDate> {
private static final long serialVersionUID = 1L;
public LocalDateSerializer(){
super(LocalDate.class);
}
@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider sp) throws IOException, JsonProcessingException {
gen.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
Amyuni WebkitPDF could be used with JNI for a Windows-only solution. This is a HTML to PDF/XAML conversion library, free for commercial and non-commercial use.
If the output files are not needed immediately, for better scalability it may be better to have a queue and a few background processes taking items from there, converting them and storing then on the database or file system.
usual disclaimer applies
A little old but this works in L5:
<li class="{{ Request::is('mycategory/', '*') ? 'active' : ''}}">
This captures both /mycategory and /mycategory/slug
If you want to be really fancy, download TCPView from Sysinternals:
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, and XP, TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows.
Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true.
I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:
Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':
ssh-keygen -t rsa -C "[email protected]"
Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:
# Default GitHub
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
# Work GitHub
Host work.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_work
Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:
$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)
If your entries aren't there then run:
ssh-add ~/.ssh/id_rsa_work
Step 4: test
To test you've done this all correctly, I suggest the following quick check:
$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.
$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.
Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)
I found the same problem and i tried all the solution mentioned above and in github. Some works only in local repository, when i push my PR in remote repositories with travic-CI or Pipelines give me the same error back. Finally i fixed it by using the npm command below.
npm audit fix --force
As Jage's answer removes the element completely, including event handlers and data, I'm adding a simple solution that doesn't do that, thanks to the detach
function.
var element = $('#childNode').detach();
$('#parentNode').append(element);
Edit:
Igor Mukhin suggested an even shorter version in the comments below:
$("#childNode").detach().appendTo("#parentNode");
CKEDITOR.config.enterMode = CKEDITOR.ENTER_BR;
- this works perfectly for me.
Have you tried clearing your browser cache - this is an issue sometimes.
You can also check it out with the jQuery adapter:
<script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/js/ckeditor/adapters/jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#your_textarea').ckeditor({
toolbar: 'Full',
enterMode : CKEDITOR.ENTER_BR,
shiftEnterMode: CKEDITOR.ENTER_P
});
});
</script>
UPDATE according to @Tomkay's comment:
Since version 3.6 of CKEditor you can configure if you want inline content to be automatically wrapped with tags like <p></p>
. This is the correct setting:
CKEDITOR.config.autoParagraph = false;
Source: http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.autoParagraph
wait
releases the lock and sleep
doesn't. A thread in waiting state is eligible for waking up as soon as notify
or notifyAll
is called. But in case of sleep
the thread keeps the lock and it'll only be eligible once the sleep time is over.
Try using type
:
type foobar
For example:
$ type ls
ls is aliased to `ls --color=auto'
$ type foobar
-bash: type: foobar: not found
This is preferable to which
for a few reasons:
The default which
implementations only support the -a
option that shows all options, so you have to find an alternative version to support aliases
type
will tell you exactly what you are looking at (be it a Bash function or an alias or a proper binary).
type
doesn't require a subprocess
type
cannot be masked by a binary (for example, on a Linux box, if you create a program called which
which appears in path before the real which
, things hit the fan. type
, on the other hand, is a shell built-in (yes, a subordinate inadvertently did this once).
Convert set to list, and then use get
method of list
Set<Foo> set = ...;
List<Foo> list = new ArrayList<Foo>(set);
Foo obj = list.get(0);
I struggled like mad, but this is actually the right answer. For what it is worth, what I missed was is this:
By the way the page that explains it on Ron's site is now at http://www.rondebruin.nl/win/s2/win002.htm
And here is his example on how you enable /disable buttons on the Ribbon http://www.rondebruin.nl/win/s2/win013.htm
For other xml examples of ribbons please also see http://msdn.microsoft.com/en-us/library/office/aa338202%28v=office.12%29.aspx
For completeness, you can also use:
mystring = mystring.strip() # the while loop will leave a trailing space,
# so the trailing whitespace must be dealt with
# before or after the while loop
while ' ' in mystring:
mystring = mystring.replace(' ', ' ')
which will work quickly on strings with relatively few spaces (faster than re
in these situations).
In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).
In your example, using the default values of timeit.Timer.repeat(), I get the following times:
str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub: [3.741931446594549, 3.8389395858970374, 3.973777672860706]
split/join: [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]
EDIT:
Just came across this post which provides a rather long comparison of the speeds of these methods.
There are two major purposes of hashing functions:
It's impossible to recommend a hash without knowing what you're using it for.
If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.
If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
Another way to do this is to add the new characters to the string as follows:
Dim str As String
str = ""
To append text to your string this way:
str = str & "and this is more text"
I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.
Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.
Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.
If you have the latest browsers window.orientation
might not work. In that case use following code for getting angle -
var orientation = window.screen.orientation.angle;
This is still an experimental technology, you can check the browser compatibility here
For example if you use this code , you can load image from db (mysql) and display it in php5 ;)
<?php
$con =mysql_connect("localhost", "root" , "");
$sdb= mysql_select_db("my_database",$con);
$sql = "SELECT * FROM `news` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s=$row['photo'];
echo $row['photo'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
?>
If you want to finish and just add a resultCode
(without data), you can call setResult(int resultCode)
before finish()
.
For example:
...
if (everything_OK) {
setResult(Activity.RESULT_OK); // OK! (use whatever code you want)
finish();
}
else {
setResult(Activity.RESULT_CANCELED); // some error ...
finish();
}
...
Then in your calling activity, check the resultCode
, to see if we're OK.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == someCustomRequestCode) {
if (resultCode == Activity.RESULT_OK) {
// OK!
}
else if (resultCode = Activity.RESULT_CANCELED) {
// something went wrong :-(
}
}
}
Don't forget to call the activity with startActivityForResult(intent, someCustomRequestCode)
.
I thought I would expand on these answers for OSX and Linux folks (not that they need it):
I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.
$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found
DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.
I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)
Let's see:
$ which mvn
/usr/local/bin/mvn
There you are... you little b@stard.
Now where did you get installed to:
$ ls -l /usr/local/bin/mvn
lrwxr-xr-x 1 root wheel 39 Oct 31 13:00 /
/usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn
Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...
Do you have your little buddy mvnDebug with you?
$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
Good. Good. Very good. All going as planned.
Now move that little b@stard where I can remember him more easily.
$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
ln: /usr/local/bin/mvnDebug: Permission denied
Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!
$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)
$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000
Internally mvnDebug uses this:
MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
So you could modify it (I usually debug on port 9090).
This blog explains how to setup Eclipse remote debugging (shudder)
http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html
Ditto Netbeans
https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a
Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html
Here is some good docs on the -Xdebug command in general.
http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."
"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."
-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp
Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.
Nanda's answer wasn't enough in my setup. What I needed to do is:
This has been answered above, but I wanted to suggest an alternative.
When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names
from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles
, select this to change back to the original view.
This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.
TL;DR
Error #1064 means that MySQL can't understand your command. To fix it:
Read the error message. It tells you exactly where in your command MySQL got confused.
Examine your command. If you use a programming language to create your command, use
echo
,console.log()
, or its equivalent to show the entire command so you can see it.Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.
Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).
Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.
As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.
Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.
For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):
This sentence contains syntax error a.
Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.
It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.
Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…
MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:
UPDATE my_table WHERE id=101 SET name='foo'
That command yields the following error message:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1
MySQL is telling us that everything seemed fine up to the word WHERE
, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE
at that point.
Messages that say ...near '' at line...
simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.
Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:
$result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
If you write this this in two lines
$query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
$result = $mysqli->query($query);
then you can add echo $query;
or var_dump($query)
to see that the query actually says
UPDATE userSET name='foo' WHERE id=101
Often you'll see your error immediately and be able to fix it.
MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.
I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE
command. The very first thing on the page is the command's grammar (this is true for every command):
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [
and ]
are optional; vertical bars |
indicate alternatives; and ellipses ...
denote either an omission for brevity, or that the preceding clause may be repeated.
We already know that the parser believed everything in our command was okay prior to the WHERE
keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference
must be followed by the SET
keyword: whereas in our command it was actually followed by the WHERE
keyword. This explains why the parser reports that a problem was encountered at that point.
Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.
I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:
UPDATE my_table SET where='foo'
Again, the parser does not expect to encounter WHERE
at this point and so will raise a similar syntax error—but you hadn't intended for that where
to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.
[ deletia ]The identifier quote character is the backtick (“
`
”):mysql> SELECT * FROM `select` WHERE `select`.id > 100;
If the
ANSI_QUOTES
SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:mysql> CREATE TABLE "test" (col INT); ERROR 1064: You have an error in your SQL syntax... mysql> SET sql_mode='ANSI_QUOTES'; mysql> CREATE TABLE "test" (col INT); Query OK, 0 rows affected (0.00 sec)
Sometimes it's easier to do all the appending outside of pandas, then, just create the DataFrame in one shot.
>>> import pandas as pd
>>> simple_list=[['a','b']]
>>> simple_list.append(['e','f'])
>>> df=pd.DataFrame(simple_list,columns=['col1','col2'])
col1 col2
0 a b
1 e f
When you are done with a connection, just call connection.release()
and the connection will return to the pool, ready to be used again by someone else.
var mysql = require('mysql');
var pool = mysql.createPool(...);
pool.getConnection(function(err, connection) {
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});
If you would like to close the connection and remove it from the pool, use connection.destroy()
instead. The pool will create a new connection the next time one is needed.
Source: https://github.com/mysqljs/mysql
I found this answer here and I'm using it like this.
Code from my Library:
$.fn.customContextMenu = function(callBack){
$(this).each(function(){
$(this).bind("contextmenu",function(e){
e.preventDefault();
callBack();
});
});
}
Code from my page's script:
$("#newmagazine").customContextMenu(function(){
alert("some code");
});
You can do it like:
val df = sqlContext.emptyDataFrame
if( df.eq(sqlContext.emptyDataFrame) )
println("empty df ")
else
println("normal df")
Without any jQuery:
function decodeEntities(encodedString) {_x000D_
var textArea = document.createElement('textarea');_x000D_
textArea.innerHTML = encodedString;_x000D_
return textArea.value;_x000D_
}_x000D_
_x000D_
console.log(decodeEntities('1 & 2')); // '1 & 2'
_x000D_
This works similarly to the accepted answer, but is safe to use with untrusted user input.
As noted by Mike Samuel, doing this with a <div>
instead of a <textarea>
with untrusted user input is an XSS vulnerability, even if the <div>
is never added to the DOM:
function decodeEntities(encodedString) {_x000D_
var div = document.createElement('div');_x000D_
div.innerHTML = encodedString;_x000D_
return div.textContent;_x000D_
}_x000D_
_x000D_
// Shows an alert_x000D_
decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">')
_x000D_
However, this attack is not possible against a <textarea>
because there are no HTML elements that are permitted content of a <textarea>
. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.
function decodeEntities(encodedString) {_x000D_
var textArea = document.createElement('textarea');_x000D_
textArea.innerHTML = encodedString;_x000D_
return textArea.value;_x000D_
}_x000D_
_x000D_
// Safe, and returns the correct answer_x000D_
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))
_x000D_
Warning: Doing this using jQuery's
.html()
and.val()
methods instead of using.innerHTML
and.value
is also insecure* for some versions of jQuery, even when using atextarea
. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to.html()
. Hence code like this shows an alert in jQuery 1.8:
//<!-- CDATA_x000D_
// Shows alert_x000D_
$("<textarea>")_x000D_
.html("<script>alert(1337);</script>")_x000D_
.text();_x000D_
_x000D_
//-->
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
_x000D_
* Thanks to Eru Penkman for catching this vulnerability.
I did run into another condition with HugeClob in my Oracle database. The dbms_lob.substr
only allowed a value of 4000 in the function, ex:
dbms_lob.substr(column,4000,1)
so for my HughClob which was larger, I had to use two calls in select
:
select dbms_lob.substr(column,4000,1) part1,
dbms_lob.substr(column,4000,4001) part2 from .....
I was calling from a Java app so I simply concatenated part1 and part2 and sent as a email.
Is it possible to set a number to NaN or infinity?
Yes, in fact there are several ways. A few work without any imports, while others require import
, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).
The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float
:
+-------------------------------------------------------------------+
¦ result ¦ NaN ¦ Infinity ¦ -Infinity ¦
¦ module ¦ ¦ ¦ ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf") ¦ -float("inf") ¦
¦ ¦ ¦ float("infinity") ¦ -float("infinity") ¦
¦ ¦ ¦ float("+inf") ¦ float("-inf") ¦
¦ ¦ ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math ¦ math.nan ¦ math.inf ¦ -math.inf ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath ¦ cmath.nan ¦ cmath.inf ¦ -cmath.inf ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy ¦ numpy.nan ¦ numpy.PINF ¦ numpy.NINF ¦
¦ ¦ numpy.NaN ¦ numpy.inf ¦ -numpy.inf ¦
¦ ¦ numpy.NAN ¦ numpy.infty ¦ -numpy.infty ¦
¦ ¦ ¦ numpy.Inf ¦ -numpy.Inf ¦
¦ ¦ ¦ numpy.Infinity ¦ -numpy.Infinity ¦
+-------------------------------------------------------------------+
A couple remarks to the table:
float
constructor is actually case-insensitive, so you can also use float("NaN")
or float("InFiNiTy")
. cmath
and numpy
constants return plain Python float
objects.numpy.NINF
is actually the only constant I know of that doesn't require the -
.It is possible to create complex NaN and Infinity with complex
and cmath
:
+------------------------------------------------------------------------------------------+
¦ result ¦ NaN+0j ¦ 0+NaNj ¦ Inf+0j ¦ 0+Infj ¦
¦ module ¦ ¦ ¦ ¦ ¦
¦----------+----------------+-----------------+---------------------+----------------------¦
¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf") ¦ complex("infj") ¦
¦ ¦ ¦ ¦ complex("infinity") ¦ complex("infinityj") ¦
+----------+----------------+-----------------+---------------------+----------------------¦
¦ cmath ¦ cmath.nan ¹ ¦ cmath.nanj ¦ cmath.inf ¹ ¦ cmath.infj ¦
+------------------------------------------------------------------------------------------+
The options with ¹ return a plain float
, not a complex
.
is there any function to check whether a number is infinity or not?
Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import
:
+--------------------------------------------------------------+
¦ for ¦ NaN ¦ Infinity or ¦ not NaN and ¦
¦ ¦ ¦ -Infinity ¦ not Infinity and ¦
¦ module ¦ ¦ ¦ not -Infinity ¦
¦----------+-------------+----------------+--------------------¦
¦ math ¦ math.isnan ¦ math.isinf ¦ math.isfinite ¦
+----------+-------------+----------------+--------------------¦
¦ cmath ¦ cmath.isnan ¦ cmath.isinf ¦ cmath.isfinite ¦
+----------+-------------+----------------+--------------------¦
¦ numpy ¦ numpy.isnan ¦ numpy.isinf ¦ numpy.isfinite ¦
+--------------------------------------------------------------+
Again a couple of remarks:
cmath
and numpy
functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.numpy
functions also work for numpy
arrays and everything that can be converted to one (like lists, tuple, etc.)numpy.isposinf
and numpy.isneginf
.NaN
: pandas.isna
and pandas.isnull
(but not only NaN, it matches also None
and NaT
)Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):
def isnan(value):
return value != value # NaN is not equal to anything, not even itself
infinity = float("infinity")
def isinf(value):
return abs(value) == infinity
def isfinite(value):
return not (isnan(value) or isinf(value))
To summarize the expected results for these functions (assuming the input is a float):
+----------------------------------------------------------------------+
¦ input ¦ NaN ¦ Infinity ¦ -Infinity ¦ something else ¦
¦ function ¦ ¦ ¦ ¦ ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan ¦ True ¦ False ¦ False ¦ False ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf ¦ False ¦ True ¦ True ¦ False ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite ¦ False ¦ False ¦ False ¦ True ¦
+----------------------------------------------------------------------+
Is it possible to set an element of an array to NaN in Python?
In a list it's no problem, you can always include NaN (or Infinity) there:
>>> [math.nan, math.inf, -math.inf, 1] # python list
[nan, inf, -inf, 1]
However if you want to include it in an array
(for example array.array
or numpy.array
) then the type of the array must be float
or complex
because otherwise it will try to downcast it to the arrays type!
>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan, 0., 0.])
>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])
>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer
>>> import pandas as pd
>>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
>>> dict(sorted(df.values.tolist())) # Sort of sorted...
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> from collections import OrderedDict
>>> OrderedDict(df.values.tolist())
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
Explaining solution: dict(sorted(df.values.tolist()))
Given:
df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
[out]:
Letter Position
0 a 1
1 b 2
2 c 3
3 d 4
4 e 5
Try:
# Get the values out to a 2-D numpy array,
df.values
[out]:
array([['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5]], dtype=object)
Then optionally:
# Dump it into a list so that you can sort it using `sorted()`
sorted(df.values.tolist()) # Sort by key
Or:
# Sort by value:
from operator import itemgetter
sorted(df.values.tolist(), key=itemgetter(1))
[out]:
[['a', 1], ['b', 2], ['c', 3], ['d', 4], ['e', 5]]
Lastly, cast the list of list of 2 elements into a dict.
dict(sorted(df.values.tolist()))
[out]:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Answering @sbradbio comment:
If there are multiple values for a specific key and you would like to keep all of them, it's the not the most efficient but the most intuitive way is:
from collections import defaultdict
import pandas as pd
multivalue_dict = defaultdict(list)
df = pd.DataFrame({'Position':[1,2,4,4,4], 'Letter':['a', 'b', 'd', 'e', 'f']})
for idx,row in df.iterrows():
multivalue_dict[row['Position']].append(row['Letter'])
[out]:
>>> print(multivalue_dict)
defaultdict(list, {1: ['a'], 2: ['b'], 4: ['d', 'e', 'f']})
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
For Chrome, instead of
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
you need to add Content-Security-Policy
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from
header for Chrome (outputs error on console).
For details, see my answer here.
You can use methodsolver
to find Ruby functions.
Here is a small script,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
Running this prints
Found 1 methods
- Array#unshift
You can install methodsolver using
gem install methodsolver
Interesting. This isn't directly possible for the reasons called out earlier (spam clicks and malware injection), but consider this hack, which creates an impression of the same:
Let's say you've a div, you can use this css property to hide the real cursor:
.your_div {
cursor: none
}
Simply create an image, a cursor look-alike,and place it within your webpage, with position:absolute
.
This is easy. Check internet on how to get real mouse location (X & Y coordinates).
As the actual cursor move, move your pseudo cursor by same X & Y difference. Similarly, you can always generate a click event at any location on your webpage with javascript magic (just search the internet on how-to).
Now at this point, you can control the pesudo cursor the way you want, and your user will get the impression that the real cursor is moving.
Fair Warning: Do not do it. No one wants their cursor or computer controlled this way, unless if you've some specific use-case, or if you are determined to flee your users away.
Looking at your output maybe the following query can work, give it a try:
SELECT * FROM tablename
WHERE id IN
(SELECT MIN(id) FROM tablename GROUP BY EmailAddress)
This will select only one row for each distinct email address, the row with the minimum id
which is what your result seems to portray
Recent private repositories have a search field for searching through that repo.
Bafflingly, it looks like this functionality is not available to public repositories, though.
The options are the same as for the fopen function in the C standard library:
w
truncates the file, overwriting whatever was already there
a
appends to the file, adding onto whatever was already there
w+
opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file
a+
opens for appending and reading, allowing you both to append to the file and also read its contents
Much simpler to my opinion:
sed -r 's/\s+//g' filename
If it's important you really need to benchmark both options!
Having said that, I have always used the exception method, the reasoning being it's better to only hit the database once.
If anyone is getting this error after a Phpmyadmin export, using the custom options and adding the "drop tables" statements cleared this right up.
Here is how I do it. You will need to get the namespace URL and the element name from your generated code.
new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
new String("").getClass(),testDN);
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
function countInString(searchFor,searchIn){
var results=0;
var a=searchIn.indexOf(searchFor)
while(a!=-1){
searchIn=searchIn.slice(a*1+searchFor.length);
results++;
a=searchIn.indexOf(searchFor);
}
return results;
}
So you were on the right track. Inside your componentDidMount()
you could have finished the job by implementing setInterval()
to trigger the change, but remember the way to update a components state is via setState()
, so inside your componentDidMount()
you could have done this:
componentDidMount() {
setInterval(() => {
this.setState({time: Date.now()})
}, 1000)
}
Also, you use Date.now()
which works, with the componentDidMount()
implementation I offered above, but you will get a long set of nasty numbers updating that is not human readable, but it is technically the time updating every second in milliseconds since January 1, 1970, but we want to make this time readable to how we humans read time, so in addition to learning and implementing setInterval
you want to learn about new Date()
and toLocaleTimeString()
and you would implement it like so:
class TimeComponent extends Component {
state = { time: new Date().toLocaleTimeString() };
}
componentDidMount() {
setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000)
}
Notice I also removed the constructor()
function, you do not necessarily need it, my refactor is 100% equivalent to initializing site with the constructor()
function.
Function GetSearchArray(strSearch)
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress
For Each SHT In ThisWorkbook.Worksheets
Set rFND = Nothing
With SHT.UsedRange
Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rFND Is Nothing Then
sFirstAddress = rFND.Address
Do
If strResults = vbNullString Then
strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
Else
strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
End If
Set rFND = .FindNext(rFND)
Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
End If
End With
Next
If strResults = vbNullString Then
GetSearchArray = Null
ElseIf InStr(1, strResults, "|", 1) = 0 Then
GetSearchArray = Array(strResults)
Else
GetSearchArray = Split(strResults, "|")
End If
End Function
Sub test2()
For Each X In GetSearchArray("1")
Debug.Print X
Next
End Sub
Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.
a bit late, but it might be worth checking the "indicator" parameter of pd.merge.
See this other question for an example: Compare PandaS DataFrames and return rows that are missing from the first one
There are two options:
First
You can also use like is()
$('#dropDownId').is(':disabled');
Second
Using == true
by checking if the attributes value is disabled
. attr()
$('#dropDownId').attr('disabled');
whatever you feel fits better , you can use :)
Cheers!
I've tried some of those solution but nothing was working for me. I try this simple thing :
$isJson = json_decode($myJSON);
if ($isJson instanceof \stdClass || is_array($isJson)) {
echo("it's JSON confirmed");
} else {
echo("nope");
}
I think it's a fine solutiuon since JSON decode without the second parameter give an object.
EDIT : If you know what will be the input, you can adapt this code to your needs. In my case I know I have a Json wich begin by "{", so i don't need to check if it's an array.
Try adding the drive letter:
include_path='.;c:\xampplite\php\pear\PEAR'
also verify that PEAR.php is actually there, it might be in \php\ instead:
include_path='.;c:\xampplite\php'
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.
The following will return the string represention you wanted:
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)
Try this code, this should work:
import platform
print(platform.python_version())
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property: TextBox.AcceptsReturn = true
.
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement
, WordWrap
etc., only control how the TextBox interacts in the UI but do not affect the Multiline
behaviour.
If you only wanted to GROUP BY the SalesOrderID then you wouldn't be able to include the ProductID and OrderQty columns in the SELECT clause.
The PARTITION BY clause let's you break up your aggregate functions. One obvious and useful example would be if you wanted to generate line numbers for order lines on an order:
SELECT
O.order_id,
O.order_date,
ROW_NUMBER() OVER(PARTITION BY O.order_id) AS line_item_no,
OL.product_id
FROM
Orders O
INNER JOIN Order_Lines OL ON OL.order_id = O.order_id
(My syntax might be off slightly)
You would then get back something like:
order_id order_date line_item_no product_id
-------- ---------- ------------ ----------
1 2011-05-02 1 5
1 2011-05-02 2 4
1 2011-05-02 3 7
2 2011-05-12 1 8
2 2011-05-12 2 1
I would probably just do:
..
echo Before you enter your password, make sure no-one is looking!
set /P password=Password:
cls
echo Thanks, got that.
..
So you get a prompt, then the screen clears after it's entered.
Note that the entered password will be stored in the CMD history if the batch file is executed from a command prompt (Thanks @Mark K Cowan).
If that wasn't good enough, I would either switch to python, or write an executable instead of a script.
I know none of these are perfect soutions, but maybe one is good enough for you :)
.NET 4.0 has a built-in library to do this:
using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(str);
This is the simplest way.
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
You can try this:
For Date:
$date = new DateTime($from_date);
$date = $date->format('d-m-Y');
For Time:
$time = new DateTime($from_date);
$time = $time->format('H:i:s');
ioctl(<socketfd>, SIOCGIFCONF, (struct ifconf)&buffer);
Read /usr/include/linux/if.h
for information on the ifconf
and ifreq
structures. This should give you the IP address of each interface on the system. Also read /usr/include/linux/sockios.h
for additional ioctls.
Swift 2.0 Version:
private func adapteSizeLabel(label: UILabel, sizeMax: CGFloat) {
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
let maximumLabelSize = CGSizeMake(label.frame.size.width, sizeMax);
let expectSize = label.sizeThatFits(maximumLabelSize)
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, expectSize.width, expectSize.height)
}
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
I Suggest you to use both Input Submit / Button instead of anchor and put this line of code onClick="javascript:location.href = 'http://stackoverflow.com';"
in that Input Submit / Button which you want to work as link.
Submit Example
<input type="submit" value="Submit" onClick="javascript:location.href = 'some_url';" />
Button Example
<button type="button" onClick="javascript:location.href = 'some_url';" />Submit</button>
I'll add this in here as my problem had something todo with my virtualenv
:
I hadn't activated my virtual environment and was trying to install my requirements, this ultimately led to my install failing and throwing this error message.
So make sure you activate your virtualenv!
In testing IE7/8/9 I was getting an ActiveX
warning trying to use this code snippet:
filter:progid:DXImageTransform.Microsoft.gradient
After removing this the warning went away. I know this isn't an answer, but I thought it was worthwhile to note.
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
Using new Date().getTime() / 1000
is an incomplete solution for obtaining the seconds, because it produces timestamps with floating-point units.
const timestamp = new Date() / 1000; // 1405792936.933
// Technically, .933 would be milliseconds.
A better solution would be:
// Rounds the value
const timestamp = Math.round(new Date() / 1000); // 1405792937
// - OR -
// Floors the value
const timestamp = new Date() / 1000 | 0; // 1405792936
Values without floats are also safer for conditional statements, as the float may produce unwanted results. The granularity you obtain with a float may be more than needed.
if (1405792936.993 < 1405792937) // true
I just put the content in the question in a file called test.php
and ran php test.php
.
(In the folder where the test.php
is.)
$ php foo.php
15
The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content.
You can pass $event
with ng-click (ng-dblclick, and ng- mouse events), then you can determine which element caused the event:
<a ng-click="doSomething($event)">do something</a>
Controller:
$scope.doSomething = function(ev) {
var element = ev.srcElement ? ev.srcElement : ev.target;
console.log(element, angular.element(element))
...
}
UPDATE: this was solved by rebooting but there was another error when running app. This time tomcat woudnt start. To solve this (bugs with latest apache and netbeans versions) follow: Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command
What you want cannot be done, because plt.legend()
places a legend in the current axes, in your case in the last one.
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Hey Please have a look here-
I have same answer here on my blog ..
You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):
Function GetFillColor(Rng As Range) As Long
GetFillColor = Rng.Interior.ColorIndex
End Function
Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel
In your worksheet, you can use the following: =GetFillColor(B5)
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}