The requests.Session()
solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token
is required as a hidden field and add it to the payload with the username and password:
import requests
from bs4 import BeautifulSoup
payload = {
'email': '[email protected]',
'password': 'passw0rd'
}
with requests.Session() as sess:
res = sess.get(server_name + '/signin')
signin = BeautifulSoup(res._content, 'html.parser')
payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
res = sess.post(server_name + '/auth/login', data=payload)
In Grid use this code having ID as your Primary Element so to uniquely identify each ROW
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="Hf_ID" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
and to search the uique ID use the code in C# code behind (basically this is searching hidden field and storing it in a var)
protected void Grd_Registration_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var ID = (HiddenField)Grd_Registration.Rows[e.RowIndex].FindControl("ID");
//Your Delete Logic Goes here having ID to delete
GridBind();
}
In drawable I use this xml code to define the border and background:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#D8FDFB" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
<solid android:color="#f0600000"/>
</shape>
GUIDs may seem to be a natural choice for your primary key - and if you really must, you could probably argue to use it for the PRIMARY KEY of the table. What I'd strongly recommend not to do is use the GUID column as the clustering key, which SQL Server does by default, unless you specifically tell it not to.
You really need to keep two issues apart:
the primary key is a logical construct - one of the candidate keys that uniquely and reliably identifies every row in your table. This can be anything, really - an INT
, a GUID
, a string - pick what makes most sense for your scenario.
the clustering key (the column or columns that define the "clustered index" on the table) - this is a physical storage-related thing, and here, a small, stable, ever-increasing data type is your best pick - INT
or BIGINT
as your default option.
By default, the primary key on a SQL Server table is also used as the clustering key - but that doesn't need to be that way! I've personally seen massive performance gains when breaking up the previous GUID-based Primary / Clustered Key into two separate key - the primary (logical) key on the GUID, and the clustering (ordering) key on a separate INT IDENTITY(1,1)
column.
As Kimberly Tripp - the Queen of Indexing - and others have stated a great many times - a GUID
as the clustering key isn't optimal, since due to its randomness, it will lead to massive page and index fragmentation and to generally bad performance.
Yes, I know - there's newsequentialid()
in SQL Server 2005 and up - but even that is not truly and fully sequential and thus also suffers from the same problems as the GUID
- just a bit less prominently so.
Then there's another issue to consider: the clustering key on a table will be added to each and every entry on each and every non-clustered index on your table as well - thus you really want to make sure it's as small as possible. Typically, an INT
with 2+ billion rows should be sufficient for the vast majority of tables - and compared to a GUID
as the clustering key, you can save yourself hundreds of megabytes of storage on disk and in server memory.
Quick calculation - using INT
vs. GUID
as Primary and Clustering Key:
TOTAL: 25 MB vs. 106 MB - and that's just on a single table!
Some more food for thought - excellent stuff by Kimberly Tripp - read it, read it again, digest it! It's the SQL Server indexing gospel, really.
PS: of course, if you're dealing with just a few hundred or a few thousand rows - most of these arguments won't really have much of an impact on you. However: if you get into the tens or hundreds of thousands of rows, or you start counting in millions - then those points become very crucial and very important to understand.
Update: if you want to have your PKGUID
column as your primary key (but not your clustering key), and another column MYINT
(INT IDENTITY
) as your clustering key - use this:
CREATE TABLE dbo.MyTable
(PKGUID UNIQUEIDENTIFIER NOT NULL,
MyINT INT IDENTITY(1,1) NOT NULL,
.... add more columns as needed ...... )
ALTER TABLE dbo.MyTable
ADD CONSTRAINT PK_MyTable
PRIMARY KEY NONCLUSTERED (PKGUID)
CREATE UNIQUE CLUSTERED INDEX CIX_MyTable ON dbo.MyTable(MyINT)
Basically: you just have to explicitly tell the PRIMARY KEY
constraint that it's NONCLUSTERED
(otherwise it's created as your clustered index, by default) - and then you create a second index that's defined as CLUSTERED
This will work - and it's a valid option if you have an existing system that needs to be "re-engineered" for performance. For a new system, if you start from scratch, and you're not in a replication scenario, then I'd always pick ID INT IDENTITY(1,1)
as my clustered primary key - much more efficient than anything else!
This functionality is available from C# 4.0 - it was introduced in Visual Studio 2010. And you can use it in project for .NET 3.5. So there is no need to upgrade old projects in .NET 3.5 to .NET 4.0.
You have to just use Visual Studio 2010, but remember that it should compile to default language version (set it in project Properties->Buid->Advanced...)
This MSDN page has more information about optional parameters in VS 2010.
Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).
Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:
RGB
:
To shade:
newR = currentR * (1 - shade_factor)
newG = currentG * (1 - shade_factor)
newB = currentB * (1 - shade_factor)
To tint:
newR = currentR + (255 - currentR) * tint_factor
newG = currentG + (255 - currentG) * tint_factor
newB = currentB + (255 - currentB) * tint_factor
More generally, the color resulting in layering a color RGB(currentR,currentG,currentB)
with a color RGBA(aR,aG,aB,alpha)
is:
newR = currentR + (aR - currentR) * alpha
newG = currentG + (aG - currentG) * alpha
newB = currentB + (aB - currentB) * alpha
where (aR,aG,aB) = black = (0,0,0)
for shading, and (aR,aG,aB) = white = (255,255,255)
for tinting
HSV
or HSB
:
Value
/ Brightness
or increase the Saturation
Saturation
or increase the Value
/ Brightness
HSL
:
Lightness
Lightness
There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB
and want to use the HSV
model to shade for example, you can just convert to HSV
, do the shading and convert back to RGB
. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :
RGB
has the advantage of being really simple to implement, but:
HSV
or HSB
is kind of complex because you need to play with two parameters to get what you want (Saturation
& Value
/ Brightness
)HSL
is the best from my point of view:
50%
means an unaltered Hue>50%
means the Hue is lighter (tint)<50%
means the Hue is darker (shade)Lightness
part)some color tunings
audio {
filter: sepia(20%) saturate(70%) grayscale(1) contrast(99%) invert(12%);
width: 200px;
height: 25px;
}
MOVE /-Y Source Destination
Note:/-y will make the announcement of yes/no for overwrite
These are generally the scenarios where colon ':' is used in JavaScript
1- Declaring and Initializing an Object
var Car = {model:"2015", color:"blue"}; //car object with model and color properties
2- Setting a Label (Not recommended since it results in complicated control structure and Spaghetti code)
List:
while(counter < 50)
{
userInput += userInput;
counter++;
if(userInput > 10000)
{
break List;
}
}
3- In Switch Statement
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
4- In Ternary Operator
document.getElementById("demo").innerHTML = age>18? "True" : "False";
Well there are lot of answeres already provided and lot are making sense too.
Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.
I came across similar situation today and here is very simple query I came up with...
declare
begin
execute immediate '
create table "TBL" ("ID" number not null)';
exception when others then
if SQLCODE = -955 then null; else raise; end if;
end;
/
955 is failure code.
This is simple, if exception come while running query it will be suppressed. and you can use same for SQL
or Oracle
.
I was facing the same issue but it was not a permission issue.
When you are doing git clone it will create try to create replica of the respository structure.
When its trying to create the folder/directory with same name and path in your local os process is not allowing to do so and hence the error. There was "background" java process running in Task-manager which was accessing the resource of the directory(folder) and hence it was showing as permission denied for git operations. I have killed those process and that solved my problem. Cheers!!
If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:
query = """
{{
pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
id
txCount
reserveUSD
trackedReserveETH
volumeUSD
}}
}}
""".format(block=''.join(['{number: ', str(block), '}']))
query = gql(query)
Make sure to escape all curly braces like I did: "{{", "}}"
SmartPhone[] sp=new SmartPhone[4];
sp[0]=new SmartPhone(1,"HTC","desire","black",20000,10,true,true);
sp[1]=new SmartPhone(2,"samsung","grand","black",5000,10,false,true);
sp[2]=new SmartPhone(14,"google nexus","desire","black",2000,30,true,false);
sp[3]=new SmartPhone(13,"HTC","desire","white",50000,40,false,false);
The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake.
A. TCP/IP
It might be TCP/IP issue you need to resolve with your host or upgrade your OS most times connection is close before remote server before it finished downloading the content resulting to Connection reset by peer
.....
B. Kannel Bug
Note that there are some issues with TCP window scaling on some Linux kernels after v2.6.17. See the following bug reports for more information:
https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.17/+bug/59331
https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.20/+bug/89160
C. PHP & CURL Bug
You are using PHP/5.3.3
which has some serious bugs too ... i would advice you work with a more recent version of PHP
and CURL
https://bugs.php.net/bug.php?id=52828
https://bugs.php.net/bug.php?id=52827
https://bugs.php.net/bug.php?id=52202
https://bugs.php.net/bug.php?id=50410
D. Maximum Transmission Unit
One common cause of this error is that the MTU (Maximum Transmission Unit) size of packets travelling over your network connection have been changed from the default of 1500 bytes.
If you have configured VPN
this most likely must changed during configuration
D. Firewall : iptables
If you don't know your way around this guys they would cause some serious issues .. try and access the server you are connecting to check the following
Example
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT`
Example
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
Check for ALL DROP , REJECT and make sure they are not blocking your connection
Temporary allow all connection as see if it foes through
Try a different server or remote server ( So many fee cloud hosting online) and test the same script .. if it works then i guesses are as good as true ... You need to update your system
A. SSL
If Yii::app()->params['pdfUrl']
is a url with https
not including proper SSL setting can also cause this error in old version of curl
Resolution : Make sure OpenSSL is installed and enabled then add this to your code
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);
I hope it helps
Ternary operator works because the first part of it returns a Boolean value. In your case, jQuery's css method returns the jQuery object, thus not valid for ternary operation.
If you are using Sql Server Management Studio, you can obtain a list of all schemas, create your own schema or remove an existing one by browsing to:
Databases - [Your Database] - Security - Schemas
[
Layout Weight works like a ratio. For example, if there is a vertical layout and there are two items(such as buttons or textviews), one having layout weight 2 and the other having layout weight 3 respectively. Then the 1st item will occupy 2 out of 5 portion of the screen/layout and the other one 3 out of 5 portion. Here 5 is the weight sum. i.e. Weight sum divides the whole layout into defined portions. And Layout Weight defines how much portion does the particular item occupies out of the total Weight Sum pre-defined. Weight sum can be manually declared as well. Buttons, textviews, edittexts etc all are organized using weightsum and layout weight when using linear layouts for UI design.
What about using the following:
int number = input.nextInt();
if (number < 0) {
// negative
} else {
// it's a positive
}
Apart from custom class or .Net 4.0 Tuples, since C# 7.0 there is a new feature called ValueTuple, which is a struct that can be used in this case. Instead of writing:
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
and access values through t.Item1
and t.Item2
, you can simply do it like that:
(string message, int count) = ("Hello", 4);
or even:
(var message, var count) = ("Hello", 4);
I had a similar use case during testing hibernate event listeners which are only called on commit.
The solution was to wrap the code to be persistent into another method annotated with REQUIRES_NEW
. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.
Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.
Enter a guid in your assembly data. Add this guid to the registry. Enter a reg key where the application read it's own name and add the name as value there.
The other task watcher read the reg key and knows the app name.
Since it is not possible to make an async constructor, I use a static async method that returns a class instance created by a private constructor. This is not elegant but it works ok.
public class ViewModel
{
public ObservableCollection<TData> Data { get; set; }
//static async method that behave like a constructor
async public static Task<ViewModel> BuildViewModelAsync()
{
ObservableCollection<TData> tmpData = await GetDataTask();
return new ViewModel(tmpData);
}
// private constructor called by the async method
private ViewModel(ObservableCollection<TData> Data)
{
this.Data = Data;
}
}
list.append
returns None
, since it is an in-place operation and you are assigning it back to dates_dict[key]
. So, the next time when you do dates_dict.get(key, []).append
you are actually doing None.append
. That is why it is failing. Instead, you can simply do
dates_dict.setdefault(key, []).append(date)
But, we have collections.defaultdict
for this purpose only. You can do something like this
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
This will create a new list object, if the key
is not found in the dictionary.
Note: Since the defaultdict
will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.
Personally my comment style in say Java is like
/*
* My multi-line comment in Java
*/
So having single-line only comments isn't such a bad thing if your style is typical to the preceding example because in comparison you'd have
#
# My multi-line comment in Python
#
VB.NET is also a language with single-line only commenting, and personally I find it annoying as comments end up looking less likes comments and more like some kind of quote
'
' This is a VB.NET example
'
Single-line-only comments end up having less character-usage than multi-line comments, and are less likely to be escaped by some dodgy characters in a regex statement perhaps? I'd tend to agree with Ned though.
You can do it with jQuery UI without another JavaScript library. Just add a function to the .resizable
resize event to adjust the width of the other div.
$("#left_pane").resizable({
handles: 'e', // 'East' side of div draggable
resize: function() {
$("#right_pane").outerWidth( $("#container").innerWidth() - $("#left_pane").outerWidth() );
}
});
Here's the complete JSFiddle.
My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container);
Rect displayRectangle = new Rect();
Window window = getDialog().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
return v;
}
I've tested it on Android 5.0.1.
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
This may be helpful
byte[] bytes = System.Convert.FromBase64String(stringInBase64);
You have to count the li elements not the ul elements:
if ( $('#menu ul li').length > 1 ) {
If you need every UL element containing at least two LI elements, use the filter function:
$('#menu ul').filter(function(){ return $(this).children("li").length > 1 })
You can also use that in your condition:
if ( $('#menu ul').filter(function(){ return $(this).children("li").length > 1 }).length) {
Use forEach its a built-in array function. Array.forEach()
:
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=@fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("@Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +""
part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=@fName"
oCmd.Parameters.AddWithValue("@fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null
.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person>
.
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
A Maven SNAPSHOT is an artifact created by a Maven build and pretends to help developers in the software development cycle. A SNAPSHOT is an artifact (or project build result ) that is not pretended to be used anywhere, it's only a temporarily .jar, ear, ... created to test the build process or to test new requirements that are not yet ready to go to a production environment. After you are happy with the SNAPSHOT artifact quality, you can create a RELEASE artifact that can be used by other projects or can be deployed itself.
In your project, you can define a SNAPSHOT using the version element in the pom.xml file of Maven:
<groupId>example.project.maven</groupId>
<artifactId>MavenEclipseExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Maven pom example</description>
If you want to understand better Maven you can look into these articles too:
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
There is an Oracle article I found regarding Java 9 module system
By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.
As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible
for JDK8 and JDK9 are instructive. Specifically, JDK9 added
This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:
- C and D are in the same module.
- The member is public and D is public in a package that the module containing D exports to at least the module containing C.
- The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
- D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.
which highlights the significance of modules and their exports (in Java 9)
I've noticed something here myself.
I've defined .env
correctly, etc and i'd defined DATABASE_URL
in there but despite doing so another DATABASE_URL was being referenced, perhaps a global environment variable is referenced if it exists?
Anyhow, I found that when I defined TEST
and CONNECTION_STRING
within .env
these both were referenced correctly where as DATABASE_URL
continues to not be.
Thanks,
Michael
Steve Ebersole & other members,
Would you kindly explain the reason for an id with a larger gap(by default 50)?
I am using Hibernate 4.2.15 and found the following code in org.hibernate.id.enhanced.OptimizerFactory cass.
if ( lo > maxLo ) {
lastSourceValue = callback.getNextValue();
lo = lastSourceValue.eq( 0 ) ? 1 : 0;
hi = lastSourceValue.copy().multiplyBy( maxLo+1 );
}
value = hi.copy().add( lo++ );
Whenever it hits the inside of the if statement, hi value is getting much larger. So, my id during the testing with the frequent server restart generates the following sequence ids:
1, 2, 3, 4, 19, 250, 251, 252, 400, 550, 750, 751, 752, 850, 1100, 1150.
I know you already said it didn't conflict with the spec, but I believe this will be very unexpected situation for most developers.
Anyone's input will be much helpful.
Jihwan
UPDATE:
ne1410s: Thanks for the edit.
cfrick: OK. I will do that. It was my first post here and wasn't sure how to use it.
Now, I understood better why maxLo was used for two purposes: Since the hibernate calls the DB sequence once, keep increase the id in Java level, and saves it to the DB, the Java level id value should consider how much was changed without calling the DB sequence when it calls the sequence next time.
For example, sequence id was 1 at a point and hibernate entered 5, 6, 7, 8, 9 (with allocationSize = 5). Next time, when we get the next sequence number, DB returns 2, but hibernate needs to use 10, 11, 12... So, that is why "hi = lastSourceValue.copy().multiplyBy( maxLo+1 )" is used to get a next id 10 from the 2 returned from the DB sequence. It seems only bothering thing was during the frequent server restart and this was my issue with the larger gap.
So, when we use the SEQUENCE ID, the inserted id in the table will not match with the SEQUENCE number in DB.
Same errors for me. I tried -v but nothing. Then I realised I had changed the model so much that the controller was showing errors.
Once I fixed the errors in the controller it worked.
is simple for me use base64_encode
$term = base64_encode($term)
$url = $youurl.'?term='.$term
after you decode the term
$term = base64_decode($['GET']['term'])
this way encode the "/" and "\"
On Visual Studio 2015 just go to: help/about Microsoft Visual Studio Then you will see something like this:
Microsoft Visual Studio Enterprise 2015 Version 14.0.24720.00 Update 1 Microsoft .NET Framework Version 4.6.01055
...
TypeScript 1.7.6.0 TypeScript for Microsoft Visual Studio
....
my OS is ubuntu, XAMPP installed in /opt/lampp
, and I found php.ini in /opt/lampp/etc/php.ini
the Dictionary class implements ISerializable. The definition of Class Dictionary given below.
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
I don't think that is the problem. refer to the below link, which says that if you are having any other data type which is not serializable then Dictionary will not be serialized. http://forums.asp.net/t/1734187.aspx?Is+Dictionary+serializable+
Using Android Studio 3.0 or later version it is possible to pull database (also shared preference, cache directory and others) if application runs in debug mode on non-rooted device.
To pull database using android studio follow these steps.
I tried all the above and it did not work.
I found that in spite of uninstalling the app a new version of the app still gives the same error.
This is what solved it: go to Settings -> General -> application Manager -> choose your app -> click on the three dots on the top -> uninstall for all users
Once you do this, now it is actually uninstalled and will now allow your new version to install.
Hope this helps.
Lots of complicated and dangerous answers here, but it's actually easy:
git revert --no-commit 0766c053..HEAD
git commit
This will revert everything from the HEAD back to the commit hash, meaning it will recreate that commit state in the working tree as if every commit after 0766c053
had been walked back. You can then commit the current tree, and it will create a brand new commit essentially equivalent to the commit you "reverted" to.
(The --no-commit
flag lets git revert all the commits at once- otherwise you'll be prompted for a message for each commit in the range, littering your history with unnecessary new commits.)
This is a safe and easy way to rollback to a previous state. No history is destroyed, so it can be used for commits that have already been made public.
That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.
The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)
What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items
to access the array.
For example, to add another item to the array using dynamic values:
// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);
Interestingly enough, it is possible to initialize arrays in any way at any time in the program, provided they are members of a struct
or union
.
Example program:
#include <stdio.h>
struct ccont
{
char array[32];
};
struct icont
{
int array[32];
};
int main()
{
int cnt;
char carray[32] = { 'A', 66, 6*11+1 }; // 'A', 'B', 'C', '\0', '\0', ...
int iarray[32] = { 67, 42, 25 };
struct ccont cc = { 0 };
struct icont ic = { 0 };
/* these don't work
carray = { [0]=1 }; // expected expression before '{' token
carray = { [0 ... 31]=1 }; // (likewise)
carray = (char[32]){ [0]=3 }; // incompatible types when assigning to type 'char[32]' from type 'char *'
iarray = (int[32]){ 1 }; // (likewise, but s/char/int/g)
*/
// but these perfectly work...
cc = (struct ccont){ .array='a' }; // 'a', '\0', '\0', '\0', ...
// the following is a gcc extension,
cc = (struct ccont){ .array={ [0 ... 2]='a' } }; // 'a', 'a', 'a', '\0', '\0', ...
ic = (struct icont){ .array={ 42,67 } }; // 42, 67, 0, 0, 0, ...
// index ranges can overlap, the latter override the former
// (no compiler warning with -Wall -Wextra)
ic = (struct icont){ .array={ [0 ... 1]=42, [1 ... 2]=67 } }; // 42, 67, 67, 0, 0, ...
for (cnt=0; cnt<5; cnt++)
printf("%2d %c %2d %c\n",iarray[cnt], carray[cnt],ic.array[cnt],cc.array[cnt]);
return 0;
}
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
Use any of the standard version control tools like SVN or CVS. Limitations would depend on whats the objective. Apart from a small increase in size of the repository, i did'nt face any issues
Here is an easy way with String output (I created a method to do this):
public static String (String input){
String output = "";
try {
/* From ISO-8859-1 to UTF-8 */
output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
/* From UTF-8 to ISO-8859-1 */
output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return output;
}
// Example
input = "Música";
output = "Música";
You can register a BroadcastReceiver
to be notified when a WiFi connection is established (or if the connection changed).
Register the BroadcastReceiver
:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
And then in your BroadcastReceiver
do something like this:
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
//do stuff
} else {
// wifi connection was lost
}
}
}
For more info, see the documentation for BroadcastReceiver
and WifiManager
Of course you should check whether the device is already connected to WiFi before this.
EDIT: Thanks to ban-geoengineering, here's a method to check whether the device is already connected:
private boolean isConnectedViaWifi() {
ConnectivityManager connectivityManager = (ConnectivityManager) appObj.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
You can use the following registry location to check if computer is running 32 or 64 bit of Windows operating system:
HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0
You will see the following registry entries in the right pane:
Identifier REG_SZ x86 Family 6 Model 14 Stepping 12
Platform ID REG_DWORD 0x00000020(32)
The above x86
and 0x00000020(32)
indicate that the operating system version is 32 bit.
In case anyone was wondering - it was probably my css...
@font-face
font-family: "bingo"
src: url('bingo.eot')
src: local('bingo')
src: url('bingo.svg#bingo') format('svg')
src: url('bingo.otf') format('opentype')
will render as
@font-face {
font-family: "bingo";
src: url('bingo.eot');
src: local('bingo');
src: url('bingo.svg#bingo') format('svg');
src: url('bingo.otf') format('opentype'); }
which seems to be close enough... just need to check the SVG rendering
See the LayoutInflater
class.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);
You don't add or link directly against a DLL, you link against the LIB produced by the DLL.
A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).
To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:
#pragma comment(lib, "dll.lib")
With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).
Spring has a Pair<S,T>
type in the Data Utils package org.springframework.data.util
Pair<String,Integer> pair = Pair.of("Test", 123);
System.out.println(pair.getFirst());
System.out.println(pair.getSecond());
With jQuery (and without FormData API) you can use something like this:
function readFile(file){
var loader = new FileReader();
var def = $.Deferred(), promise = def.promise();
//--- provide classic deferred interface
loader.onload = function (e) { def.resolve(e.target.result); };
loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
loader.onerror = loader.onabort = function (e) { def.reject(e); };
promise.abort = function () { return loader.abort.apply(loader, arguments); };
loader.readAsBinaryString(file);
return promise;
}
function upload(url, data){
var def = $.Deferred(), promise = def.promise();
var mul = buildMultipart(data);
var req = $.ajax({
url: url,
data: mul.data,
processData: false,
type: "post",
async: true,
contentType: "multipart/form-data; boundary="+mul.bound,
xhr: function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
def.notify(percent);
}
}, false);
}
return xhr;
}
});
req.done(function(){ def.resolve.apply(def, arguments); })
.fail(function(){ def.reject.apply(def, arguments); });
promise.abort = function(){ return req.abort.apply(req, arguments); }
return promise;
}
var buildMultipart = function(data){
var key, crunks = [], bound = false;
while (!bound) {
bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
}
for (var key = 0, l = data.length; key < l; key++){
if (typeof(data[key].value) !== "string") {
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
"Content-Type: application/octet-stream\r\n"+
"Content-Transfer-Encoding: binary\r\n\r\n"+
data[key].value[0]);
}else{
crunks.push("--"+bound+"\r\n"+
"Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
data[key].value);
}
}
return {
bound: bound,
data: crunks.join("\r\n")+"\r\n--"+bound+"--"
};
};
//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
var formData = form.find(":input:not('#file')").serializeArray();
formData.file = [fileData, $file[0].files[0].name];
upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});
With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})
If settings.functionName
is already a function, you could do this:
settings.functionName(t.parentNode.id);
Otherwise this should also work if settings.functionName
is just the name of the function:
if (typeof window[settings.functionName] == "function") {
window[settings.functionName](t.parentNode.id);
}
This helped me: Print page without links
@media print {
a[href]:after {
content: none !important;
}
}
I've been playing around with the Google Autocomplete API for a bit and here's the best solution I could find for limiting your results to only countries:
var autocomplete = new google.maps.places.Autocomplete(input, options);
var result = autocomplete.getPlace();
console.log(result); // take a look at this result object
console.log(result.address_components); // a result has multiple address components
for(var i = 0; i < result.address_components.length; i += 1) {
var addressObj = result.address_components[i];
for(var j = 0; j < addressObj.types.length; j += 1) {
if (addressObj.types[j] === 'country') {
console.log(addressObj.types[j]); // confirm that this is 'country'
console.log(addressObj.long_name); // confirm that this is the country name
}
}
}
If you look at the result object that's returned, you'll see that there's an address_components array which will contain several objects representing different parts of an address. Within each of these objects, it will contain a 'types' array and within this 'types' array, you'll see the different labels associated with an address, including one for country.
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
This topic, especially the answer of Xotic750 was very helpful to me. I wanted to generate a json variable to pass it to a php script using ajax. My values were stored into two arrays, and i wanted them in json format. This is a generic example:
valArray1 = [121, 324, 42, 31];
valArray2 = [232, 131, 443];
myJson = {objArray1: {}, objArray2: {}};
for (var k = 1; k < valArray1.length; k++) {
var objName = 'obj' + k;
var objValue = valArray1[k];
myJson.objArray1[objName] = objValue;
}
for (var k = 1; k < valArray2.length; k++) {
var objName = 'obj' + k;
var objValue = valArray2[k];
myJson.objArray2[objName] = objValue;
}
console.log(JSON.stringify(myJson));
The result in the console Log should be something like this:
{
"objArray1": {
"obj1": 121,
"obj2": 324,
"obj3": 42,
"obj4": 31
},
"objArray2": {
"obj1": 232,
"obj2": 131,
"obj3": 443
}
}
Use versions:set
from the versions-maven plugin:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT
It will adjust all pom versions, parent versions and dependency versions in a multi-module project.
If you made a mistake, do
mvn versions:revert
afterwards, or
mvn versions:commit
if you're happy with the results.
Note: this solution assumes that all modules use the aggregate pom as parent pom also, a scenario that was considered standard at the time of this answer. If that is not the case, go for Garret Wilson's answer.
LIKE
should work in sqlite:
require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
name id
1 robert 2
2 peter 3
I've written a jQuery plugin that incorporates the solutions discussed here with cross-browser support:
https://github.com/adjohnson916/jquery-methodOverride
Check it out!
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
You have to do binding in a directive. Look at this:
angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
return {
restrict: 'A',
replace: true,
transclude: false,
compile: function(element, attrs) {
var html = '<div class="slider-range"></div>';
var slider = $(html);
element.replaceWith(slider);
var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;
return function (scope, slider, attrs, controller) {
var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;
var processChange = function() {
var vs = slider.slider("values"), f = vs[0], t = vs[1];
setterLeft(scope, f);
setterRight(scope, t);
}
slider.slider({
range: true,
min: 0,
max: 10,
step: 1,
change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
}).slider("values", [f, t]);
};
}
};
});
This shows you an example of a slider range, done with jQuery UI. Example usage:
<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
I had problems with using the getClass().getResource("filename.txt")
method.
Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'
. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:
src/main/com/mycompany/myapp
then you can add a resources folder as recommended by maven in:
src/main/resources
furthermore you can add subfolders in the resources folder
src/main/resources/textfiles
and say that your file is called myfile.txt
so you have
src/main/resources/textfiles/myfile.txt
Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package
, and you want to access the myfile.txt
file from your resource folder. Some say you need to give the:
"/main/resources/textfiles/myfile.txt" path
or
"/resources/textfiles/myfile.txt"
both of these are wrong. After I ran mvn clean compile
, the files and folders are copied in the:
myapp/target/classes
folder. But the resources folder is not there, just the folders in the resources folder. So you have:
myapp/target/classes/textfiles/myfile.txt
myapp/target/classes/com/mycompany/myapp/*
so the correct path to give to the getClass().getResource("")
method is:
"/textfiles/myfile.txt"
here it is:
getClass().getResource("/textfiles/myfile.txt")
This will no longer return null, but will return your class.
I hope this helps somebody. It is strange to me, that the "resources"
folder is not copied as well, but only the subfolders and files directly in the "resources"
folder. It would seem logical to me that the "resources"
folder would also be found under "myapp/target/classes"
Line numbers were added to the IDLE editor two days ago and will appear in the upcoming 3.8.0a3 and later 3.7.5. For new windows, they are off by default, but this can be reversed on the Setting dialog, General tab, Editor section. For existing windows, there is a new Show (Hide) Line Numbers entry on the Options menu. There is currently no hotkey. One can select a line or bloc of lines by clicking on a line or clicking and dragging.
Some people may have missed Edit / Go to Line. The right-click context menu Goto File/Line works on grep (Find in Files) output as well as on trackbacks.
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
After an hour or two of trying every combination of ui-view autoscroll=true
, $stateChangeStart
, $locationChangeStart
, $uiViewScrollProvider.useAnchorScroll()
, $provide('$uiViewScroll', ...)
, and many others, I couldn't get scroll-to-top-on-new-page to work as expected.
This was ultimately what worked for me. It captures pushState and replaceState and only updates scroll position when new pages are navigated to (back/forward button retain their scroll positions):
.run(function($anchorScroll, $window) {
// hack to scroll to top when navigating to new URLS but not back/forward
var wrap = function(method) {
var orig = $window.window.history[method];
$window.window.history[method] = function() {
var retval = orig.apply(this, Array.prototype.slice.call(arguments));
$anchorScroll();
return retval;
};
};
wrap('pushState');
wrap('replaceState');
})
If you have included jQuery, there may be a conflict. Try using jQuery
instead of $
.
The workaround is to export the collection as explained in other answers or references. This will export all requests in that collection to JSON file.
Then edit the JSON file to remove the requests you do not want using any editor; this is very simple.
Look for "item"
collection in file. This contains all your requests; one in each item. Remove the items you do not want to keep.
If you import this edited file in Postman where original collection already exists, Postman will ask you if you want to replace it or create a copy. If you want to avoid this, you may consider changing "_postman_id"
and "name"
under "info"
. If original collection will not exist while importing edited collection, then this change is not needed.
The absolute simplest example I can think of is to make incrementing an atomic operation.
With standard ints:
private volatile int counter;
public int getNextUniqueIndex() {
return counter++; // Not atomic, multiple threads could get the same result
}
With AtomicInteger:
private AtomicInteger counter;
public int getNextUniqueIndex() {
return counter.getAndIncrement();
}
The latter is a very simple way to perform simple mutations effects (especially counting, or unique-indexing), without having to resort to synchronizing all access.
More complex synchronization-free logic can be employed by using compareAndSet()
as a type of optimistic locking - get the current value, compute result based on this, set this result iff value is still the input used to do the calculation, else start again - but the counting examples are very useful, and I'll often use AtomicIntegers
for counting and VM-wide unique generators if there's any hint of multiple threads being involved, because they're so easy to work with I'd almost consider it premature optimisation to use plain ints
.
While you can almost always achieve the same synchronization guarantees with ints
and appropriate synchronized
declarations, the beauty of AtomicInteger
is that the thread-safety is built into the actual object itself, rather than you needing to worry about the possible interleavings, and monitors held, of every method that happens to access the int
value. It's much harder to accidentally violate threadsafety when calling getAndIncrement()
than when returning i++
and remembering (or not) to acquire the correct set of monitors beforehand.
You can resolve the error by providing the column names you are affecting.
> INSERT INTO table_name (column1,column2,column3)
`VALUES(50,'Jon Snow','Eye');`
please note that the semi colon should be added only after the statement providing values
You need a smoothed average, the easiest way is to take the current answer (the time to draw the last frame) and combine it with the previous answer.
// eg.
float smoothing = 0.9; // larger=more smoothing
measurement = (measurement * smoothing) + (current * (1.0-smoothing))
By adjusting the 0.9 / 0.1 ratio you can change the 'time constant' - that is how quickly the number responds to changes. A larger fraction in favour of the old answer gives a slower smoother change, a large fraction in favour of the new answer gives a quicker changing value. Obviously the two factors must add to one!
I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine
git reset
and git clean
can be overkill in some situations (and be a huge waste of time).
If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch>
is the best option.
If you're like me, your other option was to clean and perform a --hard reset
then recompile your project.
In IE you have to use attachEvent
rather than the standard addEventListener
.
A common practice is to check if the addEventListener
method is available and use it, otherwise use attachEvent
:
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
You can make a function to do it:
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
alert('element clicked');
});
You can run an example of the above code here.
The third argument of addEventListener
is useCapture
; if true, it indicates that the user wishes to initiate event capturing.
Well I know this answer is not an experienced programmer's approach and of an Old It consultant , but it worked for me .
the answer is "TRY TURNING IT ON AND OFF" . restart codeblocks and it works well reminds me of the 2006 comedy show It Crowd .
These all seem like very complicated answers for a very simple function:
public bool IsWindows7
{
get
{
return (Environment.OSVersion.Version.Major == 6 &
Environment.OSVersion.Version.Minor == 1);
}
}
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json
module uses re
for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/
I got similar error (org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15) while using aspectj 1.8.13. Solution was to align all compilation into jdk 8 and being careful not to put aspectj library's (1.6.13 for instance) other versions to buildpath/classpath.
A few other good references on those topics:
I use the index as a checkpoint.
When I'm about to make a change that might go awry — when I want to explore some direction that I'm not sure if I can follow through on or even whether it's a good idea, such as a conceptually demanding refactoring or changing a representation type — I checkpoint my work into the index.
If this is the first change I've made since my last commit, then I can use the local repository as a checkpoint, but often I've got one conceptual change that I'm implementing as a set of little steps.
I want to checkpoint after each step, but save the commit until I've gotten back to working, tested code.
Notes:
the workspace is the directory tree of (source) files that you see and edit.
The index is a single, large, binary file in
<baseOfRepo>/.git/index
, which lists all files in the current branch, their sha1 checksums, time stamps and the file name -- it is not another directory with a copy of files in it.The local repository is a hidden directory (
.git
) including anobjects
directory containing all versions of every file in the repo (local branches and copies of remote branches) as a compressed "blob" file.Don't think of the four 'disks' represented in the image above as separate copies of the repo files.
They are basically named references for Git commits. There are two major types of refs: tags and heads.
- Tags are fixed references that mark a specific point in history, for example v2.6.29.
- On the contrary, heads are always moved to reflect the current position of project development.
(note: as commented by Timo Huovinen, those arrows are not what the commits point to, it's the workflow order, basically showing arrows as 1 -> 2 -> 3 -> 4
where 1
is the first commit and 4
is the last)
Now we know what is happening in the project.
But to know what is happening right here, right now there is a special reference called HEAD. It serves two major purposes:
- it tells Git which commit to take files from when you checkout, and
- it tells Git where to put new commits when you commit.
When you run
git checkout ref
it pointsHEAD
to the ref you’ve designated and extracts files from it. When you rungit commit
it creates a new commit object, which becomes a child of currentHEAD
. NormallyHEAD
points to one of the heads, so everything works out just fine.
Try to edit your project build.gradle file and set the android build gradle plugin to classpath 'com.android.tools.build:gradle:3.2.1'
within the dependency section.
For newbie Powershell users it is important to know that '.' is a syntactic element of Powershell, so the switch has to be enclosed in double quotes:
mvn clean install "-Dmaven.javadoc.skip=true"
There is no draft requirement for JS to use a specific sorting algorthim. As many have mentioned here, Mozilla uses merge sort.However, In Chrome's v8 source code, as of today, it uses QuickSort and InsertionSort, for smaller arrays.
From Lines 807 - 891
var QuickSort = function QuickSort(a, from, to) {
var third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
InsertionSort(a, from, to);
return;
}
if (to - from > 1000) {
third_index = GetThirdIndex(a, from, to);
} else {
third_index = from + ((to - from) >> 1);
}
// Find a pivot as the median of first, last and middle element.
var v0 = a[from];
var v1 = a[to - 1];
var v2 = a[third_index];
var c01 = comparefn(v0, v1);
if (c01 > 0) {
// v1 < v0, so swap them.
var tmp = v0;
v0 = v1;
v1 = tmp;
} // v0 <= v1.
var c02 = comparefn(v0, v2);
if (c02 >= 0) {
// v2 <= v0 <= v1.
var tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
// v0 <= v1 && v0 < v2
var c12 = comparefn(v1, v2);
if (c12 > 0) {
// v0 <= v2 < v1
var tmp = v1;
v1 = v2;
v2 = tmp;
}
}
// v0 <= v1 <= v2
a[from] = v0;
a[to - 1] = v2;
var pivot = v1;
var low_end = from + 1; // Upper bound of elements lower than pivot.
var high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
// From low_end to i are elements equal to pivot.
// From i to high_start are elements that haven't been compared yet.
partition: for (var i = low_end + 1; i < high_start; i++) {
var element = a[i];
var order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start == i) break partition;
var top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
if (to - high_start < low_end - from) {
QuickSort(a, high_start, to);
to = low_end;
} else {
QuickSort(a, from, low_end);
from = high_start;
}
}
};
Update As of 2018 V8 uses TimSort, thanks @celwell. Source
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
There's this short command line script in python: https://github.com/rgrp/csv2ascii/blob/master/csv2ascii.py
Just download and place in your path. Usage is like
csv2ascii.py [options] csv-file-path
Convert csv file at csv-file-path
to ascii form returning the result on
stdout. If csv-file-path
= '-' then read from stdin.
Options:
-h, --help show this help message and exit -w WIDTH, --width=WIDTH Width of ascii output -c COLUMNS, --columns=COLUMNS Only display this number of columns
Using Encoding.UTF8.GetBytes
is faster than using MemoryStream
.
Here, I am using NewtonsoftJson to convert input object to JSON string and then getting bytes from JSON string.
byte[] SerializeObject(object value) =>Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));
Method | Mean | Error | StdDev | Median | Gen 0 | Allocated |
--------------------------|----------|-----------|-----------|----------|--------|-----------|
ObjectToByteArray | 4.983 us | 0.1183 us | 0.2622 us | 4.887 us | 0.9460 | 3.9 KB |
ObjectToByteArrayWithJson | 1.548 us | 0.0309 us | 0.0690 us | 1.528 us | 0.3090 | 1.27 KB |
// UITableViewCell set Identify "Cell"
// UITableView Name is tableReport
UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var tableReport: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Report Name"
return cell;
}
}
There's an even better solution. You don't even need to check if the element returns null
. You can simply do this:
if (document.getElementById('elementId')) {
console.log('exists')
}
That code will only log exists
to console if the element actually exists in the DOM.
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY
We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"
--
To make content itself clickable:
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
</label>
_x000D_
To make button change content:
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
<label for="activate-div">
//MY BUTTON STUFF
</label>
_x000D_
Hope it helps!!
The best way with the HTML you have would probably be to use the next
function, like so:
var div = $(this).next('.class2');
Since the click handler is happening to the <a>
, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent
and children
. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:
var div = $(this).parent().children('.class2');
If you wanted the "search" to not be limited to immediate children, you would use find
instead of children
in the example above.
Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div>
tags are going to have those classes, make the selector be div.class1
, div.class2
.
I think it's safer to cache credentials, instead of store forever:
git config --global credential.helper 'cache --timeout=10800'
now you can enter your username and password(git pull
or ...), and keep using git for next 3 hours.
nice and safe.
Timeout is in seconds(3 hours in the example).
Your xpath is just a little off:
count(//Property/long[text()=$parPropId])
Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId]
than the text() xpath, though you could make a case for the latter on readability grounds.
What can I say, I'm a bit tired today :)
For some reason, the above solutions were not working for me. I went with the following:
$('#container').on('mousedown', function(e) {
$(this).data('p0', { x: e.pageX, y: e.pageY });
}).on('mouseup', function(e) {
var p0 = $(this).data('p0'),
p1 = { x: e.pageX, y: e.pageY },
d = Math.sqrt(Math.pow(p1.x - p0.x, 2) + Math.pow(p1.y - p0.y, 2));
if (d < 4) {
alert('clicked');
}
})
You can tweak the distance limit to whatever you please, or even take it all the way to zero.
On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases
Lots of these solutions work, but this is an alternative.
String hex="#00FF00"; // green
long thisCol=Long.decode(hex)+4278190080L;
int useColour=(int)thisCol;
If you don't add 4278190080 (#FF000000) the colour has an Alpha of 0 and won't show.
For efficiency's sake you want to only hit the data once, as Harper does. However you don't want to use rank() because it will give you ties and further you want to group by language rather than order by language. From there you want add an order by clause to distinguish between rows, but you don't want to actually sort the data. To achieve this I would use "order by null" E.g.
count(*) over (group by language order by null)
The standard way is cin.get()
before your return statement.
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Hello World";
cin.get();
return 0;
}
You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.
You can use String.getBytes()
which returns the byte[]
array.
With the link provided by @mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
A crude way to do it -
var sel = document.getElementById('select_id');
sel.addEventListener('click', function(el){
var options = this.children;
for(var i=0; i < this.childElementCount; i++){
options[i].style.color = 'white';
}
var selected = this.children[this.selectedIndex];
selected.style.color = 'red';
}, false);
I use a List of NameValuePair and URLEncodedUtils to create the url string I want.
protected String addLocationToUrl(String url){
if(!url.endsWith("?"))
url += "?";
List<NameValuePair> params = new LinkedList<NameValuePair>();
if (lat != 0.0 && lon != 0.0){
params.add(new BasicNameValuePair("lat", String.valueOf(lat)));
params.add(new BasicNameValuePair("lon", String.valueOf(lon)));
}
if (address != null && address.getPostalCode() != null)
params.add(new BasicNameValuePair("postalCode", address.getPostalCode()));
if (address != null && address.getCountryCode() != null)
params.add(new BasicNameValuePair("country",address.getCountryCode()));
params.add(new BasicNameValuePair("user", agent.uniqueId));
String paramString = URLEncodedUtils.format(params, "utf-8");
url += paramString;
return url;
}
I had problems with all the other solutions offered but ended up doing this simple thing that is smooth as butter.
Set up your HTML like so:
<tr id=row1 style='height:0px'><td>
<div id=div1 style='display:none'>
Hidden row content goes here
</div>
</td></tr>
Then set up your javascript like so:
function toggleRow(rowid){
var row = document.getElementById("row" + rowid)
if(row.style.height == "0px"){
$('#div' + rowid).slideDown('fast');
row.style.height = "1px";
}else{
$('#div' + rowid).slideUp('fast');
row.style.height = "0px";
}
}
Basically, make the "invisible" row 0px high, with a div inside.
Use the animation on the div (not the row) and then set the row height to 1px.
To hide the row again, use the opposite animation on the div and set the row height back to 0px.
This category offers a neat way to compare NSDates:
#import <Foundation/Foundation.h>
@interface NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
//- (BOOL)isEqualToDate:(NSDate *)date; already part of the NSDate API
@end
And the implementation:
#import "NSDate+Compare.h"
@implementation NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);
}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}
@end
Simple to use:
if([aDateYouWantToCompare isEarlierThanOrEqualTo:[NSDate date]]) // [NSDate date] is now
{
// do your thing ...
}
Python 3.7.7
import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
print("It is a list")
I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:
sudo npm install -g bower
You can do this with "just the regular expression" as you asked for in a comment:
(?<=sentence).*
(?<=sentence)
is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence
without making that text itself part of the match. Consequently, (?<=sentence).*
will match any text after sentence
.
This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4})
is legal, but (?<=sentence\s*)
isn't.
What do you mean by delete
? In Python, removing a reference (or a name) can be done with the del
keyword, but if there are other names to the same object that object will not be deleted.
--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
compared to:
--> test = 5
--> other is test # check that both name refer to the exact same object
True
--> del test # gets rid of test, but the object is still referenced by other
--> print(other)
5
The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.
I suspect you've got the same problem at least twice.
Here:
namespace TimeTest
{
class TimeTest
{
}
... you're declaring a type with the same name as the namespace it's in. Don't do that.
Now you apparently have the same problem with Time2
. I suspect if you add:
using Time2;
to your list of using
directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it's a bad idea.)
(Additionally, unless you're really interested in writing time-based types, I'd advise you not to do so... and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)
git reset <hash> # you need to know the last good hash, so you can remove all your local commits
git fetch upstream
git checkout master
git merge upstream/master
git push origin master -f
voila, now your fork is back to same as upstream.
If you didn't commit it yet, you can only use
$ git checkout -f
It will undo the merge (and everything that you did).
I work with non-programmers who like a simple solution:
import code
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
This produces an interpreter that acts almost exactly like the real interpreter, including the current context, with only the output:
Paused. Press ^D (Ctrl+D) to continue. >>>
The Python Debugger is also a good way to pause.
import pdb
pdb.set_trace() # Python 2
or
breakpoint() # Python 3
Here's a method that should do the job just right.
public byte[] toByteArray(int value)
{
final byte[] destination = new byte[Integer.BYTES];
for(int index = Integer.BYTES - 1; index >= 0; index--)
{
destination[i] = (byte) value;
value = value >> 8;
};
return destination;
};
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
You can use the struct's pack:
In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'
The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:
In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'
In [13]: struct.pack("B", 1)
Out[13]: '\x01'
This works the same on both python 2 and python 3.
Note: the inverse operation (bytes to int) can be done with unpack.
Implement the return statement like the example below! You should be good. I hope it helps someone..
class Example(object):
def the_example(self):
itsProblem = "problem"
return itsProblem
theExample = Example()
print theExample.the_example()
After a lot of trial and error i actually find the best, clearest and easiest multidimensional array on bash is to use a regular var. Yep.
Advantages: You don't have to loop through a big array, you can just echo "$var" and use grep/awk/sed. It's easy and clear and you can have as many columns as you like.
Example:
$ var=$(echo -e 'kris hansen oslo\nthomas jonson peru\nbibi abu johnsonville\njohnny lipp peru')
$ echo "$var"
kris hansen oslo
thomas johnson peru
bibi abu johnsonville
johnny lipp peru
$ echo "$var" | grep peru
thomas johnson peru
johnny lipp peru
$ echo "$var" | sed -n -E '/(.+) (.+) peru/p'
thomas johnson peru
johnny lipp peru
$ echo "$var" | awk '{print $2}'
hansen
johnson
abu
johnny
$ echo "$var" |grep peru|grep thomas|awk '{print $2}'
johnson
Any query you can think of... supereasy.
$ var=$(echo "$var"|sed "s/thomas/pete/")
$ var=$(echo "$var"|sed "/thomas/d")
$ var=$(echo "$var"|sed -E "s/(thomas) (.+) (.+)/\1 test \3/")
$ echo "$var"
kris hansen oslo
thomas test peru
bibi abu johnsonville
johnny lipp peru
$ for i in "$var"; do echo "$i"; done
kris hansen oslo
thomas jonson peru
bibi abu johnsonville
johnny lipp peru
The only gotcha iv'e found with this is that you must always quote the var(in the example; both var and i) or things will look like this
$ for i in "$var"; do echo $i; done
kris hansen oslo thomas jonson peru bibi abu johnsonville johnny lipp peru
and someone will undoubtedly say it won't work if you have spaces in your input, however that can be fixed by using another delimeter in your input, eg(using an utf8 char now to emphasize that you can choose something your input won't contain, but you can choose whatever ofc):
$ var=$(echo -e 'field one?field two hello?field three yes moin\nfield 1?field 2?field 3 dsdds aq')
$ for i in "$var"; do echo "$i"; done
field one?field two hello?field three yes moin
field 1?field 2?field 3 dsdds aq
$ echo "$var" | awk -F '?' '{print $3}'
field three yes moin
field 3 dsdds aq
$ var=$(echo "$var"|sed -E "s/(field one)?(.+)?(.+)/\1?test?\3/")
$ echo "$var"
field one?test?field three yes moin
field 1?field 2?field 3 dsdds aq
If you want to store newlines in your input, you could convert the newline to something else before input and convert it back again on output(or don't use bash...). Enjoy!
One simple way to get dot access (but not array access), is to use a plain object in Python. Like this:
class YourObject:
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
...and use it like this:
>>> obj = YourObject(key="value")
>>> print(obj.key)
"value"
... to convert it to a dict:
>>> print(obj.__dict__)
{"key": "value"}
There are many great open source projects that make detection a lot easier. To name two:
The best way is actually to create a new Project from scratch, then go into the folder with the project files you want to copy over (project, form1, everything except folders). Rename the files (Except for form1 files) for example: I copied Ch4Ex1 files into my Ch4Ex2 project but first renamed the files to Ch4Ex2. Copy and paste those files into the Solution Explorer for the new project in Visual Studio. Then just overwrite the files and you should be good to go!
Old thread but I hope it helps anyone looking for this answer!
Figured out a workaround: I renamed my lgpl2.1_license.txt
to lgpl2.1_license.txt.py
, and put some triple quotes around the text. Now I don't need to use the data_files
option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.
This is simple and sort. Use hsla css function like below
.transparent {
background-color: hsla(0,0%,4%,.4);
}
I have used this simple code, and it works!
for (int i = 0; i < N * N; i++)
{
Thread.Sleep(50);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
(float)10.25, FontStyle.Bold),
Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
}
It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#
I used this code, and it does work.
Might be easier to simply make sure that duplicates are not added to the list.
if(items.IndexOf(new_item) < 0)
items.add(new_item)
NOTE: Confirmed with Access 2003, don't know about earlier versions.
For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the Description property.
You're limited to 256 characters, but it's better than nothing.
You can get at the description programatically with something like this:
Dim db As Database
Dim qry As QueryDef
Set db = Application.CurrentDb
Set qry = db.QueryDefs("myQuery")
Debug.Print qry.Properties("Description")
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
Go to Project section, click on properties > then to Java compiler > check compiler compliance level is 1.8 , or there should be no yellow warning at bottom
matplotlib.pyplot.vlines
vs. matplotlib.pyplot.axvline
vlines
accepts 1 or more locations for x
, while axvline
permits one location.
x=37
x=[37, 38, 39]
vlines
takes ymin
and ymax
as a position on the y-axis, while axvline
takes ymin
and ymax
as a percentage of the y-axis range.
vlines
, pass a list
to ymin
and ymax
.fig, ax = plt.subplots()
, then replace plt.vlines
or plt.axvline
with ax.vlines
or ax.axvline
, respectively.import numpy as np
import matplotlib.pyplot as plt
xs = np.linspace(1, 21, 200)
plt.figure(figsize=(10, 7))
# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')
# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
plt.show()
To add useful information to the conversation, I came across 404 errors for my bundles in the deployment (it was fine in the local dev environment).
For the bundle names, I including version numbers like such:
bundles.Add(new ScriptBundle("~/bundles/jquerymobile.1.4.3").Include(
...
);
On a whim, I removed all the dots and all was working magically again:
bundles.Add(new ScriptBundle("~/bundles/jquerymobile143").Include(
...
);
Hope that helps someone save some time and frustration.
"put" has been deprecated, refrain from using it, use .of instead
ImmutableMap<String, String> myMap = ImmutableMap.of(
"city1", "Seattle",
"city2", "Delhi"
);
Yes, it's possible. PPF design pattern just solves this.
PPF stands for Private Prototype Functions. Basic PPF solves these issues:
For the first, just:
It's that simple. For example:
// Helper class to store private data.
function Data() {};
// Object constructor
function Point(x, y)
{
// container for private vars: all private vars go here
// we want x, y be changeable via methods only
var data = new Data;
data.x = x;
data.y = y;
...
}
// Prototype functions now have access to private instance data
Point.prototype.getX = function(data)
{
return data.x;
}
Point.prototype.getY = function(data)
{
return data.y;
}
...
Read the full story here:
Copy =VLOOKUP(M3,A$2:Q$47,13,FALSE)
to other sheets, then search for ! replace by !$, search for : replace by :$ one time for all sheets
I think it is fine because I've seen many people doing this way.
If you are just defining the event handler within the directive, you do not have to define it on the scope, though. Following would be fine.
myApp.directive('clickme', function() {
return function(scope, element, attrs) {
var clickingCallback = function() {
alert('clicked!')
};
element.bind('click', clickingCallback);
}
});
Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.
Excellent answers so far but some tidbits are missing. A single leading underscore isn't exactly just a convention: if you use from foobar import *
, and module foobar
does not define an __all__
list, the names imported from the module do not include those with a leading underscore. Let's say it's mostly a convention, since this case is a pretty obscure corner;-).
The leading-underscore convention is widely used not just for private names, but also for what C++ would call protected ones -- for example, names of methods that are fully intended to be overridden by subclasses (even ones that have to be overridden since in the base class they raise NotImplementedError
!-) are often single-leading-underscore names to indicate to code using instances of that class (or subclasses) that said methods are not meant to be called directly.
For example, to make a thread-safe queue with a different queueing discipline than FIFO, one imports Queue, subclasses Queue.Queue, and overrides such methods as _get
and _put
; "client code" never calls those ("hook") methods, but rather the ("organizing") public methods such as put
and get
(this is known as the Template Method design pattern -- see e.g. here for an interesting presentation based on a video of a talk of mine on the subject, with the addition of synopses of the transcript).
Edit: The video links in the description of the talks are now broken. You can find the first two videos here and here.
I think is not possible to do that. It would be a huge security risk if a browser access to that kind of personal information
If it's just for passing values between pages and you only require it for the one request. Use Context.
Context
The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:
// Add item to
Context Context.Items["myKey"] = myValue;
// Read an item from the
Context Response.Write(Context["myKey"]);
http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6
Using the above. If you then do a Server.Transfer
the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.
I created a tiny JQuery plugin for this. You may try it:
$.poll('http://my/url', 100, (xhr, status, data) => {
return data.hello === 'world';
})
Here is the solution I used for me Is works for fetching JSON from string
protected String getJSONFromString(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("model"))
.toString();
}
In 1985, individuals from companies throughout the computer industry joined together to develop the POSIX (Portable Operating System Interface for Computer Environments) standard, which is based largely on the UNIX System V Interface Definition (SVID) and other earlier standardization efforts. These efforts were spurred by the U.S. government, which needed a standard computing environment to minimize its training and procurement costs. Released in 1988, POSIX is a group of IEEE standards that define the API, shell, and utility interfaces for an operating system. Although aimed at UNIX-like systems, the standards can apply to any compatible operating system. Now that these stan- dards have gained acceptance, software developers are able to develop applications that run on all conforming versions of UNIX, Linux, and other operating systems.
From the book: A Practical Guide To Linux
Not sure if this is the fastest way, but this is something I stumbled upon (long time ago in high-school) when I was bored and playing with my calculator during math class. At that time, I was really amazed this was working...
public static boolean isIntRoot(int number) {
return isIntRootHelper(number, 1);
}
private static boolean isIntRootHelper(int number, int index) {
if (number == index) {
return true;
}
if (number < index) {
return false;
}
else {
return isIntRootHelper(number - 2 * index, index + 1);
}
}
Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:
return (dateOne.Value.Date - dateTwo.Value.Date).Days;
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
Velocity is a good candidate for writing this kind of stuff.
It allows you to keep your html and data-generation code as separated as possible.
If you are calling from within Stored Procedure don't use @. In my case it returns 0
CALL SP_NAME(L_OUTPUT_PARAM)
Necromancing.
I usually just create a class, which I can wrap around main in an IDisposable.
So I can log the console output to a file without modifying the rest of the code.
That way, I have the output in both the console and for later reference in a text-file.
public class Program
{
public static async System.Threading.Tasks.Task Main(string[] args)
{
using (ConsoleOutputMultiplexer co = new ConsoleOutputMultiplexer())
{
// Do something here
System.Console.WriteLine("Hello Logfile and Console 1 !");
System.Console.WriteLine("Hello Logfile and Console 2 !");
System.Console.WriteLine("Hello Logfile and Console 3 !");
} // End Using co
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
await System.Threading.Tasks.Task.CompletedTask;
} // End Task Main
}
with
public class MultiTextWriter
: System.IO.TextWriter
{
protected System.Text.Encoding m_encoding;
protected System.Collections.Generic.IEnumerable<System.IO.TextWriter> m_writers;
public override System.Text.Encoding Encoding => this.m_encoding;
public override System.IFormatProvider FormatProvider
{
get
{
return base.FormatProvider;
}
}
public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters, System.Text.Encoding encoding)
{
this.m_writers = textWriters;
this.m_encoding = encoding;
}
public MultiTextWriter(System.Collections.Generic.IEnumerable<System.IO.TextWriter> textWriters)
: this(textWriters, textWriters.GetEnumerator().Current.Encoding)
{ }
public MultiTextWriter(System.Text.Encoding enc, params System.IO.TextWriter[] textWriters)
: this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters, enc)
{ }
public MultiTextWriter(params System.IO.TextWriter[] textWriters)
: this((System.Collections.Generic.IEnumerable<System.IO.TextWriter>)textWriters)
{ }
public override void Flush()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Flush();
}
}
public async override System.Threading.Tasks.Task FlushAsync()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.FlushAsync();
}
await System.Threading.Tasks.Task.CompletedTask;
}
public override void Write(char[] buffer, int index, int count)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Write(buffer, index, count);
}
}
public override void Write(System.ReadOnlySpan<char> buffer)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Write(buffer);
}
}
public async override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.WriteAsync(buffer, index, count);
}
await System.Threading.Tasks.Task.CompletedTask;
}
public async override System.Threading.Tasks.Task WriteAsync(System.ReadOnlyMemory<char> buffer, System.Threading.CancellationToken cancellationToken = default)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.WriteAsync(buffer, cancellationToken);
}
await System.Threading.Tasks.Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Dispose();
}
}
public async override System.Threading.Tasks.ValueTask DisposeAsync()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
await thisWriter.DisposeAsync();
}
await System.Threading.Tasks.Task.CompletedTask;
}
public override void Close()
{
foreach (System.IO.TextWriter thisWriter in this.m_writers)
{
thisWriter.Close();
}
} // End Sub Close
} // End Class MultiTextWriter
public class ConsoleOutputMultiplexer
: System.IDisposable
{
protected System.IO.TextWriter m_oldOut;
protected System.IO.FileStream m_logStream;
protected System.IO.StreamWriter m_logWriter;
protected MultiTextWriter m_multiPlexer;
public ConsoleOutputMultiplexer()
{
this.m_oldOut = System.Console.Out;
try
{
this.m_logStream = new System.IO.FileStream("./Redirect.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
this.m_logWriter = new System.IO.StreamWriter(this.m_logStream);
this.m_multiPlexer = new MultiTextWriter(this.m_oldOut.Encoding, this.m_oldOut, this.m_logWriter);
System.Console.SetOut(this.m_multiPlexer);
}
catch (System.Exception e)
{
System.Console.WriteLine("Cannot open Redirect.txt for writing");
System.Console.WriteLine(e.Message);
return;
}
} // End Constructor
void System.IDisposable.Dispose()
{
System.Console.SetOut(this.m_oldOut);
if (this.m_multiPlexer != null)
{
this.m_multiPlexer.Flush();
if (this.m_logStream != null)
this.m_logStream.Flush();
this.m_multiPlexer.Close();
}
if(this.m_logStream != null)
this.m_logStream.Close();
} // End Sub Dispose
} // End Class ConsoleOutputMultiplexer
Here is a generic python function that given a tablename, columns and values, generates the upsert equivalent for postgresql.
import json
def upsert(table_name, id_column, other_columns, values_hash):
template = """
WITH new_values ($$ALL_COLUMNS$$) as (
values
($$VALUES_LIST$$)
),
upsert as
(
update $$TABLE_NAME$$ m
set
$$SET_MAPPINGS$$
FROM new_values nv
WHERE m.$$ID_COLUMN$$ = nv.$$ID_COLUMN$$
RETURNING m.*
)
INSERT INTO $$TABLE_NAME$$ ($$ALL_COLUMNS$$)
SELECT $$ALL_COLUMNS$$
FROM new_values
WHERE NOT EXISTS (SELECT 1
FROM upsert up
WHERE up.$$ID_COLUMN$$ = new_values.$$ID_COLUMN$$)
"""
all_columns = [id_column] + other_columns
all_columns_csv = ",".join(all_columns)
all_values_csv = ','.join([query_value(values_hash[column_name]) for column_name in all_columns])
set_mappings = ",".join([ c+ " = nv." +c for c in other_columns])
q = template
q = q.replace("$$TABLE_NAME$$", table_name)
q = q.replace("$$ID_COLUMN$$", id_column)
q = q.replace("$$ALL_COLUMNS$$", all_columns_csv)
q = q.replace("$$VALUES_LIST$$", all_values_csv)
q = q.replace("$$SET_MAPPINGS$$", set_mappings)
return q
def query_value(value):
if value is None:
return "NULL"
if type(value) in [str, unicode]:
return "'%s'" % value.replace("'", "''")
if type(value) == dict:
return "'%s'" % json.dumps(value).replace("'", "''")
if type(value) == bool:
return "%s" % value
if type(value) == int:
return "%s" % value
return value
if __name__ == "__main__":
my_table_name = 'mytable'
my_id_column = 'id'
my_other_columns = ['field1', 'field2']
my_values_hash = {
'id': 123,
'field1': "john",
'field2': "doe"
}
print upsert(my_table_name, my_id_column, my_other_columns, my_values_hash)
You can't, with language primitives. As has been called out, the abc package provides this functionality in Python 2.6 and later, but there are no options for Python 2.5 and earlier. The abc
package is not a new feature of Python; instead, it adds functionality by adding explicit "does this class say it does this?" checks, with manually-implemented consistency checks to cause an error during initialization if such declarations are made falsely.
Python is a militantly dynamically-typed language. It does not specify language primitives to allow you to prevent a program from compiling because an object does not match type requirements; this can only be discovered at run time. If you require that a subclass implement a method, document that, and then just call the method in the blind hope that it will be there.
If it's there, fantastic, it simply works; this is called duck typing, and your object has quacked enough like a duck to satisfy the interface. This works just fine even if self
is the object you're calling such a method on, for the purposes of mandatory overrides due to base methods that need specific implementations of features (generic functions), because self
is a convention, not anything actually special.
The exception is in __init__
, because when your initializer is being called, the derived type's initializer hasn't, so it hasn't had the opportunity to staple its own methods onto the object yet.
If the method was't implemented, you'll get an AttributeError (if it's not there at all) or a TypeError (if something by that name is there but it's not a function or it didn't have that signature). It's up to you how you handle that- either call it programmer error and let it crash the program (and it "should" be obvious to a python developer what causes that kind of error there- an unmet duck interface), or catch and handle those exceptions when you discover that your object didn't support what you wish it did. Catching AttributeError and TypeError is important in a lot of situations, actually.
Using jQuery in 2016, to get click coordinates relative to the canvas, I do:
$(canvas).click(function(jqEvent) {
var coords = {
x: jqEvent.pageX - $(canvas).offset().left,
y: jqEvent.pageY - $(canvas).offset().top
};
});
This works since both canvas offset() and jqEvent.pageX/Y are relative to the document regardless of scroll position.
Note that if your canvas is scaled then these coordinates are not the same as canvas logical coordinates. To get those, you would also do:
var logicalCoords = {
x: coords.x * (canvas.width / $(canvas).width()),
y: coords.y * (canvas.height / $(canvas).height())
}
char *name
You can change the char to which name
points, and also the char at which it points.
const char* name
You can change the char to which name
points, but you cannot modify the char at which it points.
correction: You can change the pointer, but not the char to which name
points to (https://msdn.microsoft.com/en-us/library/vstudio/whkd4k6a(v=vs.100).aspx, see "Examples"). In this case, the const
specifier applies to char
, not the asterisk.
According to the MSDN page and http://en.cppreference.com/w/cpp/language/declarations, the const
before the *
is part of the decl-specifier sequence, while the const
after *
is part of the declarator.
A declaration specifier sequence can be followed by multiple declarators, which is why const char * c1, c2
declares c1
as const char *
and c2
as const char
.
EDIT:
From the comments, your question seems to be asking about the difference between the two declarations when the pointer points to a string literal.
In that case, you should not modify the char to which name
points, as it could result in Undefined Behavior.
String literals may be allocated in read only memory regions (implementation defined) and an user program should not modify it in anyway. Any attempt to do so results in Undefined Behavior.
So the only difference in that case (of usage with string literals) is that the second declaration gives you a slight advantage. Compilers will usually give you a warning in case you attempt to modify the string literal in the second case.
#include <string.h>
int main()
{
char *str1 = "string Literal";
const char *str2 = "string Literal";
char source[] = "Sample string";
strcpy(str1,source); //No warning or error, just Undefined Behavior
strcpy(str2,source); //Compiler issues a warning
return 0;
}
Output:
cc1: warnings being treated as errors
prog.c: In function ‘main’:
prog.c:9: error: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type
Notice the compiler warns for the second case but not for the first.
You must specify the file to be downloaded (attachment) by the client in the http header:
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"
http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html
One place the parentheses suggestion fails is if say both numbers are HTML input variables. Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.
Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.
How about netstat?
http://support.microsoft.com/kb/907980
The command is netstat -anob
.
(Make sure you run command as admin)
I get:
C:\Windows\system32>netstat -anob
Active Connections
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 692
RpcSs
[svchost.exe]
TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 7540
[Skype.exe]
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
Can not obtain ownership information
TCP 0.0.0.0:623 0.0.0.0:0 LISTENING 564
[LMS.exe]
TCP 0.0.0.0:912 0.0.0.0:0 LISTENING 4480
[vmware-authd.exe]
And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path
Plotly is missing in this list. I've linked the python binding page. It definitively has animated and interative 3D Charts. And since it is Open Source most of that is available offline. Of course it is working with Jupyter
Yeah.
command >> file
to redirect just stdout of command
.
command >> file 2>&1
to redirect stdout and stderr to the file (works in bash, zsh)
And if you need to use sudo
, remember that just
sudo command >> /file/requiring/sudo/privileges
does not work, as privilege elevation applies to command
but not shell redirection part. However, simply using
tee
solves the problem:
command | sudo tee -a /file/requiring/sudo/privileges
In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.
To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.
Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.
At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.
If the datatype is timestamp then the visible format is irrelevant.
You should avoid converting the data to date or use of to_char. Instead compare the timestamp data to timestamp values using TO_TIMESTAMP()
WHERE start_ts >= TO_TIMESTAMP('2016-05-13', 'YYYY-MM-DD')
AND start_ts < TO_TIMESTAMP('2016-05-14', 'YYYY-MM-DD')
I found I can make the match when I input a hard-coded non-breaking space (U+00A0) by typing Alt+0160 on Windows between the two quotes...
//table[@id='TableID']//td[text()=' ']
worked for me with the special char.
From what I understood, the XPath 1.0 standard doesn't handle escaping Unicode chars. There seems to be functions for that in XPath 2.0 but it looks like Firefox doesn't support it (or I misunderstood something). So you have to do with local codepage. Ugly, I know.
Actually, it looks like the standard is relying on the programming language using XPath to provide the correct Unicode escape sequence... So, somehow, I did the right thing.
equals()
(javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null)
must always return false.
hashCode()
(javadoc) must also be consistent (if the object is not modified in terms of equals()
, it must keep returning the same value).
The relation between the two methods is:
Whenever
a.equals(b)
, thena.hashCode()
must be same asb.hashCode()
.
If you override one, then you should override the other.
Use the same set of fields that you use to compute equals()
to compute hashCode()
.
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:
public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.
Vlad's code is overquoted. Should be:
MY_PATH=`dirname "$0"`
MY_PATH=`( cd "$MY_PATH" && pwd )`
It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):
import pytz
from datetime import datetime
from tzwhere import tzwhere
def timezoned_unixtime(latitude, longitude, dt):
tzw = tzwhere.tzwhere()
timezone_str = tzw.tzNameAt(latitude, longitude)
timezone = pytz.timezone(timezone_str)
timezone_aware_datetime = timezone.localize(dt, is_dst=None)
unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
return unix_time
dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)
Yes, you can definitely do this. Just use something like
.parent:hover .child {
/* ... */
}
According to this page it's supported by all major browsers.
You can create an anchor like the one showed below to download the base64 pdf:
<a download=pdfTitle href=pdfData title='Download pdf document' />
where pdfData is your base64 encoded pdf like "data:application/pdf;base64,JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nO1cyY4ktxG911fUWUC3kjsTaBTQ1Ytg32QN4IPgk23JMDQ2LB/0+2YsZAQzmZk1PSPIEB..."
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
Try Logic Friday 1
It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.
The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.
Your expression simplifies to C
.
You're doing a few things wrong.
First, browserHistory isn't a thing in V4, so you can remove that.
Second, you're importing everything from react-router
, it should be react-router-dom
.
Third, react-router-dom
doesn't export a Router
, instead, it exports a BrowserRouter
so you need to import { BrowserRouter as Router } from 'react-router-dom
.
Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.
"FEB-2010" is not a Date, so it would not make a lot of sense to store it in a date column.
You can always extract the string part you need , in your case "MON-YYYY" using the TO_CHAR logic you showed above.
If this is for a DIMENSION table in a Data warehouse environment and you want to include these as separate columns in the Dimension table (as Data attributes), you will need to store the month and Year in two different columns, with appropriate Datatypes...
Example..
Month varchar2(3) --Month code in Alpha..
Year NUMBER -- Year in number
or
Month number(2) --Month Number in Year.
Year NUMBER -- Year in number
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
Are you specifically trying to rotate the links only? Because doing it on the LI tags seems to work fine.
According to Snook transforms require the elements affected be block. He's also got some code there to make this work for IE using filters, if you care to add it on(though there appears to be some limitation on values).
I got the unexpected token export error also when I was trying to import a local javascript module in my project. I solved it by declaring a type as a module when adding a script tag in my index.html file.
<script src = "./path/to/the/module/" type = "module"></script>
Put this code in a file called p.php
:
<?php
class yoyo{
function salt(){
}
function pepper(){
salt();
}
}
$y = new yoyo();
$y->pepper();
?>
Run it like this:
php p.php
We get error:
PHP Fatal error: Call to undefined function salt() in
/home/el/foo/p.php on line 6
Solution: use $this->salt();
instead of salt();
So do it like this instead:
<?php
class yoyo{
function salt(){
}
function pepper(){
$this->salt();
}
}
$y = new yoyo();
$y->pepper();
?>
If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.
I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).
# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase
And a good way to find out where a branch started is to do a svn log
it and find the first one on the branch (the last one listed when doing):
svn log --stop-on-copy svn://some/repo/branch/some-branch
So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.
Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.
As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:
np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])
select top {LIMIT HERE} * from (
select *, ROW_NUMBER() over (order by {ORDER FIELD}) as r_n_n
from {YOUR TABLES} where {OTHER OPTIONAL FILTERS}
) xx where r_n_n >={OFFSET HERE}
A note:
This solution will only work in SQL Server 2005 or above, since this was when ROW_NUMBER()
was implemented.
In loop with .map
work like this:
{
dataForm.map(({ id, placeholder, type }) => {
return <Input
value={this.state.type}
onChangeText={(text) => this.setState({ [type]: text })}
placeholder={placeholder}
key={id} />
})
}
Note the []
in type
parameter.
Hope this helps :)
I Concatenated my formula as normal but at the start I had '=
instead of =
.
Then I copy and paste as text to where I need it. Then I highlight the section saved as text and press ctrl + H to find and replace.
I replace '=
with =
and all of my functions are active.
Its a few stages but it avoids VBA.
I hope this helps,
Rob
To add to the above correct answer :-
For my case in shell, this code worked (working on sqoop
)
ROOT_PATH="path/to/the/folder"
--options-file $ROOT_PATH/query.txt
The author of this question mentions that it’s usually only after
MySQL prints its output that he realises that the wrong query was executed.
As noted, in this case, Ctrl-C
doesn’t help. However, I’ve noticed that it
will abort the current query – if you catch it before any output is
printed. For example:
mysql> select * from jos_users, jos_comprofiler;
MySQL gets busy generating the Cartesian Product of the above two tables and
you soon notice that MySQL hasn't printed any output to screen (the process
state is Sending data) so you type Ctrl-C
:
Ctrl-C -- sending "KILL QUERY 113240" to server ...
Ctrl-C -- query aborted.
ERROR 1317 (70100): Query execution was interrupted
Ctrl-C
can similarly be used to stop an UPDATE
query.
=IF(B1<>"",COUNTA($B$1:B1)&".","")
Using formula
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
Check out Intel Open CV library ...
Change
var svg = document.documentElement;
to
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
so that you create a SVG
element.
For the link to be an hyperlink, simply add a href
attribute :
h.setAttributeNS(null, 'href', 'http://www.google.com');
Seems all kinds of python web frameworks can implement RESTful interfaces now.
For Django, besides tastypie and piston, django-rest-framework is a promising one worth to mention. I've already migrated one of my project on it smoothly.
Django REST framework is a lightweight REST framework for Django, that aims to make it easy to build well-connected, self-describing RESTful Web APIs.
Quick example:
from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel
class MyResource(ModelResource):
model = MyModel
urlpatterns = patterns('',
url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)
Take the example from official site, all above codes provide api, self explained document(like soap based webservice) and even sandbox to test a bit. Very convenience.
The more secure option would be to add allowedHosts to your Webpack config like this:
module.exports = {
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
};
The array contains all allowed host, you can also specify subdomians. check out more here
Go to the Team Explorer tab then click Branches. In the branches select your branch from remotes/origin. For example, you want to reset your master branch. Right-click at the master branch in remotes/origin then select Reset then click Delete changes. This will reset your local branch and removes all locally committed changes.
document.body.style.cursor = 'cursorurl';
Try This is[\s\S]*sentence
, works in javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
What worked for me when trying to git clone
inside of a Dockerfile
was to fetch the SSL certificate and add it to the local certificate list:
openssl s_client -showcerts -servername git.mycompany.com -connect git.mycompany.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' > git-mycompany-com.pem
cat git-mycompany-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt
Credits: https://fabianlee.org/2019/01/28/git-client-error-server-certificate-verification-failed/