Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
Jet Brains IDEA has this feature. You can use hotkey surround with for that (ctrl + alt + T). It's just IDEA feature.
Regions there look like this:
//region Description
Some code
//endregion
By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable.
A good way to test if a string is a correct date is to use the command date:
if date -d "${DATE}" >/dev/null 2>&1
then
# do what you need to do with your date
else
echo "${DATE} incorrect date" >&2
exit 1
fi
from comment: one can use formatting
if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ]
You can do (pre-Java 8):
List<Enum> enumValues = Arrays.asList(Enum.values());
or
List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
Using Java 8 features, you can map each constant to its name:
List<String> enumNames = Stream.of(Enum.values())
.map(Enum::name)
.collect(Collectors.toList());
PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options
The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values
Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String
Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True
End Sub
First try the most popular solution provided by Ravindra Bagale.
If your connection from localhost to the database still fails with error similar to the following:
Can't connect to SQL Server DB. Error: The TCP/IP connection to the host [IP address], port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall."
Under the "IP Addresses" section, find subsections with IP address 127.0.0.1 (for IPv4) and ::1 (for IPv6) and set both "Enabled" and "Active" to "Yes", and TCP port to 1433.
Go to Start > Control Panel > Administrative Tools > Services
, and restart the SQL Server service (SQLEXPRESS
).
your log files shows it is stopping on error "0x8004C000"
From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):
Setup Status
Block
Restart not required
0x80044000 [-2147205120]
Restart required
0x8004C000 [-2147172352]
Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).
C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]
* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.
Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.
A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.
Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]
Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]
Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.
Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]
More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.
Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]
More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]
Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]
C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]
C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]
C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]
C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]
Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.
Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format
throughout all examples.
Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]
C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)
C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]
Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.
The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".
C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]
The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]
C++11/14/17/… References:
The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.
The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.
Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.
The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.
The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.
cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.
Note: Some information contained within these books may not be up-to-date or no longer considered best practice.
The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.
Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]
Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.
Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.
Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.
The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.
Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const
), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.
Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.
For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.
In order to save the Fragment state you need to implement onSaveInstanceState()
:
"Also like an activity, you can retain the state of a fragment using a Bundle, in case the activity's process is killed and you need to restore the fragment state when the activity is recreated. You can save the state during the fragment's onSaveInstanceState()
callback and restore it during either onCreate()
, onCreateView()
, or onActivityCreated()
. For more information about saving state, see the Activities document."
http://developer.android.com/guide/components/fragments.html#Lifecycle
You should use @input
:
<input @input="handleInput" />
@input
fires when user changes input value.
@change
fires when user changed value and unfocus input (for example clicked somewhere outside)
You can see the difference here: https://jsfiddle.net/posva/oqe9e8pb/
Disclaimer: I have read this question for days, but it is beyond my knowledge to understand the math.
I tried to solve it using set:
arr=[1,2,4,5,7,8,10] # missing 3,6,9
NMissing=3
arr_origin = list(range(1,arr[-1]+1))
for i in range(NMissing):
arr.append(arr[-1]) ##### assuming you do not delete the last one
arr=set(arr)
arr_origin=set(arr_origin)
missing=arr_origin-arr # 3 6 9
var geturl;
geturl = $.ajax({
type: "GET",
url: 'http://....',
success: function () {
alert("done!"+ geturl.getAllResponseHeaders());
}
});
Copied answer from the attached question.
You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.
Install PM2
$ npm install pm2 -g
Start an application
$ pm2 start app.js
If you using express then you can start your app like
pm2 start ./bin/www --name="app"
Listing all running processes:
$ pm2 list
It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.
$ pm2 stop all
$ pm2 stop 0
$ pm2 restart all
To display logs
$ pm2 logs ['all'|app_name|app_id]
@Jan Kuiken's answer is certainly well-thought and thorough, but there are some caveats:
A much simpler approach is to annotate the last point of each plot. The point can also be circled, for emphasis. This can be accomplished with one extra line:
from matplotlib import pyplot as plt
for i, (x, y) in enumerate(samples):
plt.plot(x, y)
plt.text(x[-1], y[-1], 'sample {i}'.format(i=i))
A variant would be to use ax.annotate
.
The solution provided by @user152949, as it was noted in commentaries, skips the first process and doesn't break when "exists" is set to true. Let me provide a fixed version:
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
bool IsProcessRunning(const TCHAR* const executableName) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) {
CloseHandle(snapshot);
return false;
}
do {
if (!_tcsicmp(entry.szExeFile, executableName)) {
CloseHandle(snapshot);
return true;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return false;
}
Yes, you can do this by creating a DoubleStream
from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
If you want to filter a reference array that is not an Object[]
you will need to use the toArray
method which takes an IntFunction
to get an array of the original type as the result:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
private static T[] prepareArray<T>(T[] arrayToCopy, T value)
{
Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
arrayToCopy[arrayToCopy.Length - 1] = value;
return (T[])arrayToCopy;
}
I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.
You can do this by subsetting the data you pass into your merge:
merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)
Or you can simply delete the column after your current merge :)
give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="click me"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_weight="0.5"/>
</LinearLayout>
A rather roundabout way, just for completeness:
for /f "delims=" %i in ('type CON') do set inp=%i
Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.
I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:
GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
While loading csv file contain date column.We have two approach to to make pandas to recognize date column i.e
Pandas explicit recognize the format by arg date_parser=mydateparser
Pandas implicit recognize the format by agr infer_datetime_format=True
Some of the date column data
01/01/18
01/02/18
Here we don't know the first two things It may be month or day. So in this case we have to use Method 1:- Explicit pass the format
mydateparser = lambda x: pd.datetime.strptime(x, "%m/%d/%y")
df = pd.read_csv(file_name, parse_dates=['date_col_name'],
date_parser=mydateparser)
Method 2:- Implicit or Automatically recognize the format
df = pd.read_csv(file_name, parse_dates=[date_col_name],infer_datetime_format=True)
I had this problem when I wanted to make a vnc connection via a tunnel.
But the vncserver was not running.
I solved it by opening the channel on the remote machine with vncserver :3
.
KEY and INDEX are synonyms.
You should add an index when performance measurements and EXPLAIN shows you that the query is inefficient because of a missing index. Adding an index can improve the performance of queries (but it can slow down modifications to the table).
You should use UNIQUE when you want to contrain the values in that column (or columns) to be unique, so that attempts to insert duplicate values result in an error.
A PRIMARY KEY is both a unique constraint and it also implies that the column is NOT NULL. It is used to give an identity to each row. This can be useful for joining with another table via a foreign key constraint. While it is not required for a table to have a PRIMARY KEY it is usually a good idea.
I used it like that in my base controller. Just sharing for ready to use.
public string GetCurrentUserEmail() {
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
var email = claims.Where(c => c.Type == ClaimTypes.Email).ToList();
return email[0].Value.ToString();
}
public string GetCurrentUserRole()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
var role = claims.Where(c => c.Type == ClaimTypes.Role).ToList();
return role[0].Value.ToString();
}
You just need to add proper name space in your root tag . xmlns:android="http://schemas.android.com/apk/res/android" Android elemets are declared in this name space.Its same as importing class or package.
You can also use a regexp with re.sub
:
article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
article_title_str, flags=re.IGNORECASE)
For a more generic and extensible way check mergedict. It uses singledispatch
and can merge values based on its types.
Example:
from mergedict import MergeDict
class SumDict(MergeDict):
@MergeDict.dispatch(int)
def merge_int(this, other):
return this + other
d2 = SumDict({'a': 1, 'b': 'one'})
d2.merge({'a':2, 'b': 'two'})
assert d2 == {'a': 3, 'b': 'two'}
Just add this to viewdidload
:
let insets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
scrollVIew.contentInset = insets
scrollVIew.scrollIndicatorInsets = insets
The most common solution is to strip the integer portion of the number and compare it to zero like so:
function Test()
{
var startVal = 123.456
alert( (startVal - Math.floor(startVal)) != 0 )
}
__all__
is used to document the public API of a Python module. Although it is optional, __all__
should be used.
Here is the relevant excerpt from the Python language reference:
The public names defined by a module are determined by checking the module’s namespace for a variable named
__all__
; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in__all__
are all considered public and are required to exist. If__all__
is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_').__all__
should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).
PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__
is absent:
To better support introspection, modules should explicitly declare the names in their public API using the
__all__
attribute. Setting__all__
to an empty list indicates that the module has no public API.[...]
Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as
os.path
or a package's__init__
module that exposes functionality from submodules.
Furthermore, as pointed out in other answers, __all__
is used to enable wildcard importing for packages:
The import statement uses the following convention: if a package’s
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported whenfrom package import *
is encountered.
If I understand correctly, you should be able to do what you want by dropping the foreign key constraint, adding a new one (which will cascade), doing your stuff, and recreating the restricting foreign key constraint.
For example:
testing=# create table a (id integer primary key);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "a_pkey" for table "a"
CREATE TABLE
testing=# create table b (id integer references a);
CREATE TABLE
-- put some data in the table
testing=# insert into a values(1);
INSERT 0 1
testing=# insert into a values(2);
INSERT 0 1
testing=# insert into b values(2);
INSERT 0 1
testing=# insert into b values(1);
INSERT 0 1
-- restricting works
testing=# delete from a where id=1;
ERROR: update or delete on table "a" violates foreign key constraint "b_id_fkey" on table "b"
DETAIL: Key (id)=(1) is still referenced from table "b".
-- find the name of the constraint
testing=# \d b;
Table "public.b"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Foreign-key constraints:
"b_id_fkey" FOREIGN KEY (id) REFERENCES a(id)
-- drop the constraint
testing=# alter table b drop constraint b_a_id_fkey;
ALTER TABLE
-- create a cascading one
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete cascade;
ALTER TABLE
testing=# delete from a where id=1;
DELETE 1
testing=# select * from a;
id
----
2
(1 row)
testing=# select * from b;
id
----
2
(1 row)
-- it works, do your stuff.
-- [stuff]
-- recreate the previous state
testing=# \d b;
Table "public.b"
Column | Type | Modifiers
--------+---------+-----------
id | integer |
Foreign-key constraints:
"b_id_fkey" FOREIGN KEY (id) REFERENCES a(id) ON DELETE CASCADE
testing=# alter table b drop constraint b_id_fkey;
ALTER TABLE
testing=# alter table b add FOREIGN KEY (id) references a(id) on delete restrict;
ALTER TABLE
Of course, you should abstract stuff like that into a procedure, for the sake of your mental health.
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
Reverse a string in python without using reversed() or [::-1]
def reverse(test):
n = len(test)
x=""
for i in range(n-1,-1,-1):
x += test[i]
return x
You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.
To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white"))
to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL)
would set the background to null for the legend, but it did not. Perhaps worth another question.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
To get rid of the black background in the legend, you need to use the override.aes
argument to the guide_legend
. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
You need good starting values such that the curve_fit
function converges at "good" values. I can not really say why your fit did not converge (even though the definition of your mean is strange - check below) but I will give you a strategy that works for non-normalized Gaussian-functions like your one.
The estimated parameters should be close to the final values (use the weighted arithmetic mean - divide by the sum of all values):
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
x = np.arange(10)
y = np.array([0, 1, 2, 3, 4, 5, 4, 3, 2, 1])
# weighted arithmetic mean (corrected - check the section below)
mean = sum(x * y) / sum(y)
sigma = np.sqrt(sum(y * (x - mean)**2) / sum(y))
def Gauss(x, a, x0, sigma):
return a * np.exp(-(x - x0)**2 / (2 * sigma**2))
popt,pcov = curve_fit(Gauss, x, y, p0=[max(y), mean, sigma])
plt.plot(x, y, 'b+:', label='data')
plt.plot(x, Gauss(x, *popt), 'r-', label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()
I personally prefer using numpy.
Since the reviewers did not like my edit on #Developer's code, I will explain for what case I would suggest an improved code. The mean of developer does not correspond to one of the normal definitions of the mean.
Your definition returns:
>>> sum(x * y)
125
Developer's definition returns:
>>> sum(x * y) / len(x)
12.5 #for Python 3.x
The weighted arithmetic mean:
>>> sum(x * y) / sum(y)
5.0
Similarly you can compare the definitions of standard deviation (sigma
). Compare with the figure of the resulting fit:
In Python 2.x you should additionally use the new division to not run into weird results or convert the the numbers before the division explicitly:
from __future__ import division
or e.g.
sum(x * y) * 1. / sum(y)
Yes. You should add this file to your version control system, i.e. You should commit it.
This file is intended to be committed into source repositories
You can read more about what it is/what it does here:
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
My code to make animation slide up, slide down without XML
private static ObjectAnimator createBottomUpAnimation(View view,
AnimatorListenerAdapter listener, float distance) {
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", -distance);
// animator.setDuration(???)
animator.removeAllListeners();
if (listener != null) {
animator.addListener(listener);
}
return animator;
}
public static ObjectAnimator createTopDownAnimation(View view, AnimatorListenerAdapter listener,
float distance) {
view.setTranslationY(-distance);
ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", 0);
animator.removeAllListeners();
if (listener != null) {
animator.addListener(listener);
}
return animator;
}
Using For slide down
createTopDownAnimation(myYellowView, null, myYellowView.getHeight()).start();
For slide up
createBottomUpAnimation(myYellowView, null, myYellowView.getHeight()).start();
As user3486832 mentioned, you can use archive.org: http://web.archive.org/web/*/https://developer.android.com/tools/sdk/ndk/index.html
replace serviceWorker.unregister() to serviceWorker.register() in index.js file
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
Since this post is ranking high in Google for "Create Directory Tree", I am going to post an answer that will work for Windows — this will work using Win32 API compiled for UNICODE or MBCS. This is ported from Mark's code above.
Since this is Windows we are working with, directory separators are BACK-slashes, not forward slashes. If you would rather have forward slashes, change '\\'
to '/'
It will work with:
c:\foo\bar\hello\world
and
c:\foo\bar\hellp\world\
(i.e.: does not need trailing slash, so you don't have to check for it.)
Before saying "Just use SHCreateDirectoryEx() in Windows", note that SHCreateDirectoryEx() is deprecated and could be removed at any time from future versions of Windows.
bool CreateDirectoryTree(LPCTSTR szPathTree, LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL){
bool bSuccess = false;
const BOOL bCD = CreateDirectory(szPathTree, lpSecurityAttributes);
DWORD dwLastError = 0;
if(!bCD){
dwLastError = GetLastError();
}else{
return true;
}
switch(dwLastError){
case ERROR_ALREADY_EXISTS:
bSuccess = true;
break;
case ERROR_PATH_NOT_FOUND:
{
TCHAR szPrev[MAX_PATH] = {0};
LPCTSTR szLast = _tcsrchr(szPathTree,'\\');
_tcsnccpy(szPrev,szPathTree,(int)(szLast-szPathTree));
if(CreateDirectoryTree(szPrev,lpSecurityAttributes)){
bSuccess = CreateDirectory(szPathTree,lpSecurityAttributes)!=0;
if(!bSuccess){
bSuccess = (GetLastError()==ERROR_ALREADY_EXISTS);
}
}else{
bSuccess = false;
}
}
break;
default:
bSuccess = false;
break;
}
return bSuccess;
}
Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.
5 Amazing Ways To Underline A TextView In Android - Kotlin/Java & XML
String html = "<u>Underline using Html.fromHtml()</u>";
textview.setText(Html.fromHtml(html));
But Html.fromHtml(String resource) was deprecated in API 24.
So you can use the latest android support library androidx.core.text.HtmlCompat. Before that, you need to include the dependency in your project.
`implementation 'androidx.core:core:1.0.1'`
String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>";
//underline textview using HtmlCompat.fromHtml() method
textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));
Using strings.xml,
<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
textview13.setText(HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY));
using PaintFlags
textview2.setPaintFlags(textview2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
textview2.setText("2. Underline using setPaintFlags()");
using SpannableString
`String content1 = "3.1 Underline using SpannableString";
SpannableString spannableString1 = new SpannableString(content1);
spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
textview31.setText(spannableString1);`
brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r
This way, everything is packager managed, so there's no need to manually download and install anything.
To really properly do a merge which takes only input from the branch you are merging you can do
git merge --strategy=ours ref-to-be-merged
git diff --binary ref-to-be-merged | git apply --reverse --index
git commit --amend
There will be no conflicts in any scenario I know of, you don't have to make additional branches, and it acts like a normal merge commit.
This doesn't play nice with submodules however.
x(end+1) = newElem
is a bit more robust.
x = [x newElem]
will only work if x
is a row-vector, if it is a column vector x = [x; newElem]
should be used. x(end+1) = newElem
, however, works for both row- and column-vectors.
In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)
if you can use jQuery you can use this
<form method="get" action="something.php" id="myForm">
<input type="text" name="name" />
<input type="submit" style="display:none" />
</form>
<input type="button" value="Submit" id="myButton" />
<script type="text/javascript">
$(document).ready(function() {
$("#myButton").click(function() {
$("#myForm").submit();
});
});
</script>
So, the bottom line is to create a button like Submit, and put the real submit button in the form(of course hiding it), and submit form by jquery via clicking the 'Fake Submit' button. Hope it helps.
Java and C:
You may find more information in Android developers site.
Any operation/function on different data structures is defined for particular actions. Here in your case i.e. removing an element, delete, Pop and remove. (If you consider sets, Add another operation - discard) Other confusing case is while adding. Insert/Append. For Demonstration, Let us Implement deque. deque is a hybrid linear data structure, where you can add elements / remove elements from both ends.(Rear and front Ends)
class Deque(object):
def __init__(self):
self.items=[]
def addFront(self,item):
return self.items.insert(0,item)
def addRear(self,item):
return self.items.append(item)
def deleteFront(self):
return self.items.pop(0)
def deleteRear(self):
return self.items.pop()
def returnAll(self):
return self.items[:]
In here, see the operations:
def deleteFront(self):
return self.items.pop(0)
def deleteRear(self):
return self.items.pop()
Operations have to return something. So, pop - With and without an index. If I don't want to return the value: del self.items[0]
Delete by value not Index:
remove :
list_ez=[1,2,3,4,5,6,7,8]
for i in list_ez:
if i%2==0:
list_ez.remove(i)
print list_ez
let us consider the case of sets.
set_ez=set_ez=set(range(10))
set_ez.remove(11)
# Gives Key Value Error.
##KeyError: 11
set_ez.discard(11)
# Does Not return any errors.
Its ec2-user for Amazon Linux AMI's and ubuntu for Ubuntu images. Also, RHEL 6.4 and later ec2-user RHEL 6.3 and earlier root Fedora ec2-user Centos root
Using MAMP I changed the host=localhost
to host=127.0.0.1
. But a new issue came "connection refused"
Solved this by putting 'port' => '8889'
, in 'Datasources' => [
There's an easier solution for this, but it requires that you know exactly how much inheritance your current class has gone through. Fortunately, get_parent_class()'s arguments allow your class array member to be the class name as a string as well as an instance itself.
Bear in mind that this also inherently relies on calling a class' __construct() method statically, though within the instanced scope of an inheriting object the difference in this particular case is negligible (ah, PHP).
Consider the following:
class Foo {
var $f = 'bad (Foo)';
function __construct() {
$this->f = 'Good!';
}
}
class Bar extends Foo {
var $f = 'bad (Bar)';
}
class FooBar extends Bar {
var $f = 'bad (FooBar)';
function __construct() {
# FooBar constructor logic here
call_user_func(array(get_parent_class(get_parent_class($this)), '__construct'));
}
}
$foo = new FooBar();
echo $foo->f; #=> 'Good!'
Again, this isn't a viable solution for a situation where you have no idea how much inheritance has taken place, due to the limitations of debug_backtrace(), but in controlled circumstances, it works as intended.
.navbar-nav {
float: left;
margin: 0;
margin-left: 40%;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
margin-left: 0;
}
Since You Have used the float
property we don't have many options except to adjust it manually.
Developing on OS X? Using Xcode? You're likely to be in luck!
As described in a comment by qungu, OS X maintains an autosaved version history of files, even if you're not using time machine.
So, if you've blown away your unstaged local changes with a careless git checkout .
, here's how you can probably recover all your work.
If somebody finds this thread having destroyed some work in XCode, there is a way to get the AutoSave history. XCode itself does not have a menu entry to see the AutoSave history, but it does store it. If you open the files in question in TextEdit, you can revert and look through the AutoSave history under File > Revert.
Which is awesome, and recovered about a day of work for me, yesterday.
You might ask, "Why doesn't the git command-line UI, the premier VCS used for software engineering in 2016 2017 2018 2019 2020, at least back up files before just blowing them away? Like, you know, well written software tools for about the last three decades."
Or perhaps you ask, "Why is this insanely awesome file history feature accessible in TextEdit but not Xcode where I actually need it?"
… and both of those, I think, will tell you quite a lot about our industry. Or maybe you'll go and fix those tools. Which would be super.
Try SQLDeveloper - there is a migration workbench there
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
ALL_CONSTRAINTS
describes constraint definitions on tables accessible to the current user.
DBA_CONSTRAINTS
describes all constraint definitions in the database.
USER_CONSTRAINTS
describes constraint definitions on tables in the current user's schema
Select CONSTRAINT_NAME,CONSTRAINT_TYPE ,TABLE_NAME ,STATUS from
USER_CONSTRAINTS;
select top 10 p.id from(select distinct p.id from tablename)tablename
How about subtracting one and changing Sunday
IF(DAYOFWEEK() = 1, 7, DAYOFWEEK() - 1)
Of course you would have to do this for every query.
First, add a pom.xml and make it a maven project and then build it. It will create a War file for you in the target folder after that you can deploy it wherever you want.
pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 it.megadix create-react-app-servlet 0.0.1-SNAPSHOT war
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<npm.output.directory>build</npm.output.directory>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Standard plugin to generate WAR -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>${npm.output.directory}</directory>
</resource>
</webResources>
<webXml>${basedir}/web.xml</webXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<!-- Required: The following will ensure `npm install` is called
before anything else during the 'Default Lifecycle' -->
<execution>
<id>npm install (initialize)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>initialize</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<!-- Required: The following will ensure `npm install` is called
before anything else during the 'Clean Lifecycle' -->
<execution>
<id>npm install (clean)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>pre-clean</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<!-- Required: This following calls `npm run build` where 'build' is
the script name I used in my project, change this if yours is
different -->
<execution>
<id>npm run build (compile)</id>
<goals>
<goal>exec</goal>
</goals>
<phase>compile</phase>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
</executions>
<configuration>
<environmentVariables>
<CI>true</CI>
<!-- The following parameters create an NPM sandbox for CI -->
<NPM_CONFIG_PREFIX>${basedir}/npm</NPM_CONFIG_PREFIX>
<NPM_CONFIG_CACHE>${NPM_CONFIG_PREFIX}/cache</NPM_CONFIG_CACHE>
<NPM_CONFIG_TMP>${project.build.directory}/npmtmp</NPM_CONFIG_TMP>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<environmentVariables>
<PUBLIC_URL>http://localhost:8080/${project.artifactId}</PUBLIC_URL>
<REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>prod</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<environmentVariables>
<PUBLIC_URL>http://my-awesome-production-host/${project.artifactId}</PUBLIC_URL>
<REACT_APP_ROUTER_BASE>/${project.artifactId}</REACT_APP_ROUTER_BASE>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Note:- If you find a blank page after running your project then clear your cache or restart your IDE.
Branches in SVN are essentially directories; you don't name the branch so much as choose the name of the directory to branch into.
The common way of 'naming' a branch is to place it under a directory called branches
in your repository. In the "To URL:" portion of TortoiseSVN's Branch dialog, you would therefore enter something like:
(svn/http)://path-to-repo/branches/your-branch-name
The main branch of a project is referred to as the trunk, and is usually located in:
(svn/http)://path-to-repo/trunk
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
Use the Bit
datatype. It has values 1 and 0 when dealing with it in native T-SQL
I noticed this issue recently and it is frustrating that excel changes a blank string into a 0. I do not think that a formula should solve this issue because adding more logic to a complex formula may be cumbersome and might even end up breaking the original formula. I have two non formula options below.
If you want to keep the formulas in the cells and have them return 0 instead of "" use the following Click Path:
Scroll to "Display options for this worksheet:"
I also want to give a simple manual solution if you want to change a value (as opposed to a formula) from 0 to a blank string. This solution is better than Find and Replace because it will not replace a number like 101 with 11.
The other data will remain if you used the filter properly and the back button is always there if something goes wrong. I understand option 2 is very manual and "unelegant" but it does successfully convert a 0 into a blank string and it may relieve a frustrated individual who does not want to use an if statement.
I personally learned something exploring this (very dry) excel issue today and I am personally using these methods moving forward. A quick macro of option 2 could be a good option if this is a frequent task for an intermediate excel user.
In a bash terminal I like to use the double dash. Using VS Code, you can right click on the spec file in the explorer, or on the open tab. Then select 'Copy Relative Path'. Run the command below pasting the relative path in from the clipboard.
npm t -- --include relative/path/to/file.spec.ts
The double dash signals the end of your command options for npm t
and passes anything after that to the next command which is pointing to ng t
. It's doesn't require any modification and quickly gives desired results.
If you develop browser extensions you can try browser.cookies.getAll()
This is a pretty clean way to do it:
myStr = ("firstPartOfMyString"+
"secondPartOfMyString"+
"thirdPartOfMyString")
For those who want to add noise to a multi-dimensional dataset loaded within a pandas dataframe or even a numpy ndarray, here's an example:
import pandas as pd
# create a sample dataset with dimension (2,2)
# in your case you need to replace this with
# clean_signal = pd.read_csv("your_data.csv")
clean_signal = pd.DataFrame([[1,2],[3,4]], columns=list('AB'), dtype=float)
print(clean_signal)
"""
print output:
A B
0 1.0 2.0
1 3.0 4.0
"""
import numpy as np
mu, sigma = 0, 0.1
# creating a noise with the same dimension as the dataset (2,2)
noise = np.random.normal(mu, sigma, [2,2])
print(noise)
"""
print output:
array([[-0.11114313, 0.25927152],
[ 0.06701506, -0.09364186]])
"""
signal = clean_signal + noise
print(signal)
"""
print output:
A B
0 0.888857 2.259272
1 3.067015 3.906358
"""
The kernel space means a memory space can only be touched by kernel. On 32bit linux it is 1G(from 0xC0000000 to 0xffffffff as virtual memory address).Every process created by kernel is also a kernel thread, So for one process, there are two stacks: one stack in user space for this process and another in kernel space for kernel thread.
the kernel stack occupied 2 pages(8k in 32bit linux), include a task_struct(about 1k) and the real stack(about 7k). The latter is used to store some auto variables or function call params or function address in kernel functions. Here is the code(Processor.h (linux\include\asm-i386)):
#define THREAD_SIZE (2*PAGE_SIZE)
#define alloc_task_struct() ((struct task_struct *) __get_free_pages(GFP_KERNEL,1))
#define free_task_struct(p) free_pages((unsigned long) (p), 1)
__get_free_pages(GFP_KERNEL,1)) means alloc memory as 2^1=2 pages.
But the process stack is another thing, its address is just bellow 0xC0000000(32bit linux), the size of it can be quite bigger, used for the user space function calls.
So here is a question come for system call, it is running in kernel space but was called by process in user space, how does it work? Will linux put its params and function address in kernel stack or process stack? Linux's solution: all system call are triggered by software interruption INT 0x80. Defined in entry.S (linux\arch\i386\kernel), here is some lines for example:
ENTRY(sys_call_table)
.long SYMBOL_NAME(sys_ni_syscall) /* 0 - old "setup()" system call*/
.long SYMBOL_NAME(sys_exit)
.long SYMBOL_NAME(sys_fork)
.long SYMBOL_NAME(sys_read)
.long SYMBOL_NAME(sys_write)
.long SYMBOL_NAME(sys_open) /* 5 */
.long SYMBOL_NAME(sys_close)
You can use the function RESHAPE:
B = reshape(A.',1,[]);
smalldatetime
has range up to June 6, 2079 so you can use
ORDER BY ISNULL(Next_Contact_Date, '2079-06-05T23:59:00')
If no legitimate records will have that date.
If this is not an assumption you fancy relying on a more robust option is sorting on two columns.
ORDER BY CASE WHEN Next_Contact_Date IS NULL THEN 1 ELSE 0 END, Next_Contact_Date
Both of the above suggestions are not able to use an index to avoid a sort however and give similar looking plans.
One other possibility if such an index exists is
SELECT 1 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NOT NULL
UNION ALL
SELECT 2 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NULL
ORDER BY Grp, Next_Contact_Date
Quick example:
On Ubuntu, if you are interested, for instance, in Gmail then open the Terminal and type:
nslookup -q=mx gmail.com
I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.
You don't have to use jQuery or Javascript.
Use the name
tag of the select and let the form do it's job.
<select name="agent_id" id="agent_id">
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
nircmd lets you do that by typing
nircmd.exe emptybin
http://www.nirsoft.net/utils/nircmd-x64.zip
http://www.nirsoft.net/utils/nircmd.html
Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:
Thin 100
Extra Light 200
Light 300
Regular 400
Medium 500
Semi-Bold 600
Bold 700
Extra-Bold 800
Black 900
Note that very few fonts come in all 9 weights.
Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.
Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.
In Oracle 12c, You may use OFFSET..FETCH..ROWS
option with ORDER BY
For example, to get the 3rd record from top:
SELECT *
FROM sometable
ORDER BY column_name
OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY;
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
Add a double quotes outside the brackets and replace double quotes inside the {}
with \"
So: "{\"data\":{..... }"
For perfomance:
$('#example').children().last()
or if you want a last children with a certain class as commented above.
$('#example').children('.test').last()
or a specific child element with a specific class
$('#example').children('li.test').last()
All the given answers did not work for me.
I had another node process running in another terminal, i closed that command terminal and everything worked as expected.
.card-img-top {
width: 100%;
height: 30vh;
object-fit: contain;
}
Contain will help in getting Complete Image displayed inside Card.
Adjust height "30vh" according to your need!
Command EXPOSE
in your Dockerfile lets you bind container's port to some port on the host machine but it doesn't do anything else.
When running container, to bind ports specify -p
option.
So let's say you expose port 5000. After building the image when you run the container, run docker run -p 5000:5000 name
. This binds container's port 5000 to your laptop/computers port 5000 and that portforwarding lets container to receive outside requests.
This should do it.
MySQL does allow NULL
values for datetime
fields. I just tested it:
mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)
mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)
mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL |
+------------+
1 row in set (0.00 sec)
I'm using this version:
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45 |
+-----------+
1 row in set (0.03 sec)
EDIT #1: I see in your edit that the error message you are getting in PHP indicates that you are passing an empty string (i.e. ''
), not null
. An empty string is different than null
and is not a valid datetime
value which is why you are getting that error message. You must pass the special sql keyword null
if that's what you mean. Also, don't put any quotes around the word null
. See my insert
statement above for an example of how to insert null
.
EDIT #2: Are you using PDO? If so, when you bind your null param, make sure to use the [PDO::PARAM_NULL][1]
type when binding a null
. See the answer to this stackoverflow question on how to properly insert null
using PDO.
Changing php.ini
for a web application requires restarting Apache.
You should verify that the change took place by running a PHP script that executes the function phpinfo()
. The output of that function will tell you a lot of PHP parameters, including the timeout value.
You might also have changed a copy of php.ini
that is not the same file used by Apache.
You don't mention if this is an anonymous PL/SQL block or a declarative one ie. Package, Procedure or Function. However, in PL/SQL a COMMIT must be explicitly made to save your transaction(s) to the database. The COMMIT actually saves all unsaved transactions to the database from your current user's session.
If an error occurs the transaction implicitly does a ROLLBACK.
This is the default behaviour for PL/SQL.
You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.
Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.
Use this simple plugin.
https://github.com/WebGangster/mongoose-paginate-v2
Installation
npm install mongoose-paginate-v2
_x000D_
const mongoose = require('mongoose');_x000D_
const mongoosePaginate = require('mongoose-paginate-v2');_x000D_
_x000D_
const mySchema = new mongoose.Schema({ _x000D_
/* your schema definition */ _x000D_
});_x000D_
_x000D_
mySchema.plugin(mongoosePaginate);_x000D_
_x000D_
const myModel = mongoose.model('SampleModel', mySchema); _x000D_
_x000D_
myModel.paginate().then({}) // Usage
_x000D_
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
You could do something like this
dict = [{
"id": 1,
"name": "Doom Hammer"
},
{
"id": 2,
"name": "Rings ov Saturn"
}
]
for x in dict:
if x["id"] == 2:
print(x["name"])
Thats what i use to find the objects in a long array of objects.
Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.
Lets take example from java docs to get know how we can declare anonymous functions, classes
The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
englishGreeting.greet();
frenchGreeting.greetSomeone("Fred");
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
Syntax of Anonymous Classes
Consider the instantiation of the frenchGreeting object:
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
The anonymous class expression consists of the following:
new
operatorThe name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
These are bitwise shift operators.
Quoting from the docs:
x << y
Returns x
with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x
by 2**y
.
x >> y
Returns x
with the bits shifted to the right by y places. This is the same as dividing x
by 2**y
.
Just wanted to point out that in the case of having a hidden submit button, you can just use the ngShow directive and set it to false like so:
HTML
<form ng-submit="myFunc()">
<input type="text" name="username">
<input type="submit" value="submit" ng-show="false">
</form>
You wan't to either change the user that the Service runs under from "System" or find a sneaky way to run your mapping as System.
The funny thing is that this is possible by using the "at" command, simply schedule your drive mapping one minute into the future and it will be run under the System account making the drive visible to your service.
Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
From the ISO draft for C++ (ISO/IEC JTC 1/SC 22 N 4411)
So destructors should generally catch exceptions and not let them propagate out of the destructor.
3 The process of calling destructors for automatic objects constructed on the path from a try block to a throw- expression is called “stack unwinding.” [ Note: If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1). So destructors should generally catch exceptions and not let them propagate out of the destructor. — end note ]
You can use
insert into table_name
(date_field)
values
(TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss'));
Hope it helps.
Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-
We are doing AND operation in this example. There are also other masking operators- OR, XOR.
Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-
1 1 1 0 1 1 0 1 [input] (&) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 0 0 1 0 1 1 0 0 [output]
So, only the middle 4 bits (as these bits are 1
in this mask) remain.
Lets see this with XOR-
1 1 1 0 1 1 0 1 [input] (^) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 1 1 0 1 0 0 0 1 [output]
Now, the middle 4 bits are flipped (1
became 0
, 0
became 1
).
So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-
bool isOdd(int i) {
return i%2;
}
This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-
bool isOdd(int i) {
return i&1;
}
Short Explanation: If the least significant bit of a binary number is 1
then it is odd; for 0
it will be even. So, by doing AND with 1
we are removing all other bits except for the least significant bit i.e.:
55 -> 0 0 1 1 0 1 1 1 [input] (&) 1 -> 0 0 0 0 0 0 0 1 [mask] --------------------------------------- 1 <- 0 0 0 0 0 0 0 1 [output]
I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:
from cx_Freeze import setup, Executable
import sys
productName = "ProductName"
if 'bdist_msi' in sys.argv:
sys.argv += ['--initial-target-dir', 'C:\InstallDir\\' + productName]
sys.argv += ['--install-script', 'install.py']
exe = Executable(
script="main.py",
base="Win32GUI",
targetName="Product.exe"
)
setup(
name="Product.exe",
version="1.0",
author="Me",
description="Copyright 2012",
executables=[exe],
scripts=[
'install.py'
]
)
I ran into the same issue. Daniel Nugent's answer helped a bit (after following his advice HttpResponse
was found - but the HttpClient
was still missing).
So here is what fixed it for me:
4.5.1.zip
from the binary sectionhttpcore-4.4.3
& httpclient-4.5.1.jar
in project/libs
folderHope it helps.
So, I would like to explain the scenario where I had to make use of this solution. Basically, I wanted to undo the background-color attribute set by another CSS. The expected end result was to make it look as though the original CSS had never applied the background-color attribute . Setting background-color:transparent;
made that effective.
The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10);
returns the left margin as an Integer.
This is what JSizes use.
It should work fine. Don't use tuple
, list
or other special names as a variable name. It's probably what's causing your problem.
>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)
>>> tuple = 'whoops' # Don't do this
>>> tuple(l)
TypeError: 'tuple' object is not callable
In the W3 wiki page about structuring HTML5, it says:
<section>
: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.
And then displays an image that I cleaned up:
It's also important to know how to use the <article>
tag (from the same W3 link above):
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up.In our example,
<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:
<section id="main">
<article>
<!-- first blog post -->
</article>
<article>
<!-- second blog post -->
</article>
<article>
<!-- third blog post -->
</article>
</section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article>
<section id="introduction">
</section>
<section id="content">
</section>
<section id="summary">
</section>
</article>
For passing both a function, and any arguments to the function:
from typing import Callable
def looper(fn: Callable, n:int, *args, **kwargs):
"""
Call a function `n` times
Parameters
----------
fn: Callable
Function to be called.
n: int
Number of times to call `func`.
*args
Positional arguments to be passed to `func`.
**kwargs
Keyword arguments to be passed to `func`.
Example
-------
>>> def foo(a:Union[float, int], b:Union[float, int]):
... '''The function to pass'''
... print(a+b)
>>> looper(foo, 3, 2, b=4)
6
6
6
"""
for i in range(n):
fn(*args, **kwargs)
Depending on what you are doing, it could make sense to define a decorator
, or perhaps use functools.partial
.
You can set the default like this:
b = models.CharField(max_length=7,default="foobar")
and then you can hide the field with your model's Admin class like this:
class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
In this case oldDTE is null, so when you try to access oldDTE.Value the InvalidOperationException is thrown since there is no value. In your example you can simply do:
this.MyDateTime = newDT.MyDateTime;
just add onclick handler for anchor tag
onclick="this.parentNode.style.display = 'none'"
or change onclick handler for img tag
onclick="this.parentNode.parentNode.style.display = 'none'"
I found a way around this after 3-4 hours of googling. I have added the following
<startup selegacyv2runtimeactivationpolicy="true">
<supportedruntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
</startup>
If this doesn't solve your problem then--> In the Project References Right Click on DLL
where you getting error --> Select Properties
--> Check the Run-time Version
--> If it is v2.0.50727
then we know the problem.
The Problem is :- you are having 2.0 Version of respective DLL.
Solution is:- You can delete the respective DLL
from the Project references and then download the latest version of DLL's
from the corresponding website and add the reference of the latest version DLL reference then it will work.
You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.
I've just done this in a grunt
project of ours. We needed a newer version of connect, since 2.7.3
. was causing trouble for us. So I created a file named npm-shrinkwrap.json
:
{
"dependencies": {
"grunt-contrib-connect": {
"version": "0.3.0",
"from": "[email protected]",
"dependencies": {
"connect": {
"version": "2.8.1",
"from": "connect@~2.7.3"
}
}
}
}
}
npm
should automatically pick it up while doing the install for the project.
(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)
Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".
outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
items = line.split( ',' )
outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
Subclassing dict
is one method, though not efficient. Here if you supply an integer it will return d[list(d)[n]]
, otherwise access the dictionary as expected:
class mydict(dict):
def __getitem__(self, value):
if isinstance(value, int):
return self.get(list(self)[value])
else:
return self.get(value)
d = mydict({'a': 'hello', 'b': 'this', 'c': 'is', 'd': 'a',
'e': 'test', 'f': 'dictionary', 'g': 'testing'})
d[0] # 'hello'
d[1] # 'this'
d['c'] # 'is'
When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.
By default, Web API uses the following rules to bind parameters:
If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
For complex types, Web API tries to read the value from the message body, using a media-type formatter.
So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri]
attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody]
attribute to the parameter.
So, to answer your question, the need of the [FromBody]
and [FromUri]
attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.
There is a lot more information on the web if you google "web api parameter binding".
When you do : f.readlines()
you already read all the file so f.tell()
will show you that you are in the end of the file, and doing f.next()
will result in a StopIteration
error.
Alternative of what you want to do is:
filne = "D:/testtube/testdkanimfilternode.txt"
with open(filne, 'r+') as f:
for line in f:
if line.startswith("anim "):
print f.next()
# Or use next(f, '') to return <empty string> instead of raising a
# StopIteration if the last line is also a match.
break
You just have to make sure that there is a way to make a continuous line of constraints from the top to the bottom of the scrollview. [-X-X-X]
In my case - a horizontally scrolling scroll view - I also needed to add width and height constraints for each child of the scroll view, although Apple's technical note doesn't tell you this.
<View
style={{
flexDirection: 'row',
padding: 10,
}}
>
<Text numberOfLines={5} style={{flex:1}}>
This is a very long text that will overflow on a small device This is a very
long text that will overflow on a small deviceThis is a very long text that
will overflow on a small deviceThis is a very long text that will overflow
on a small device
</Text>
</View>
Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).
Setting a cookie:
def view(request):
response = HttpResponse('blah')
response.set_cookie('cookie_name', 'cookie_value')
Retrieving a cookie:
def view(request):
value = request.COOKIES.get('cookie_name')
if value is None:
# Cookie is not set
# OR
try:
value = request.COOKIES['cookie_name']
except KeyError:
# Cookie is not set
numpy provides a simple function to do the exact same thing: supposing you have a masked array 'a', calling numpy.ma.compress_rows(a) will delete the rows containing a masked value. I guess this is much faster this way...
You might have to be more specific and specify the app name as well (this is the name of the app as you have it in heroku). For example:
heroku ps:scale web=0 --app myAppName
Otherwise you might get the following message:
% heroku ps:scale web=0
Scaling dynos... failed
! No app specified.
! Run this command from an app folder or specify which app to use with --app APP.
if you create a console application, console will stay opened until you close the application.
if you already creat an application and you dont know how to open a console, you can change the subsystem as Console(/Subsystem:Console) in project configurations -> linker -> system.
The number one suggestion of Invalidate Caches/Restart... did not work for me nor did any of the other solutions. It ended up being that my maven repos were incorrectly set up, I fixed this by manually overriding the settings.xml and repository directory:
File -> Settings... -> Build, Execution, Deployment -> Build Tools -> Maven
Then for User settings file and Local repository, check the Override and point it to the correct settings.xml and repository directory.
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
@echo off
setlocal
set "list=a b c d"
(
for %%i in (%list%) do (
echo(%%i
echo(
)
)>file.txt
You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.
Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D"
- including the quotes, to the variable "list "
- NOT including the quotes, but including the space. The syntax set "var=string"
is used to assign the value string
to var
whereas set var=string
will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.
ECHO
echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O
in ECHO
have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis (
is probably the most useful since the command
ECHO.%emptyvalue%
will produce a report of the ECHO
state (ECHO is on/off
) whereas
ECHO(%emptyvalue%
will produce an empty line.
The problem with ECHO(
is that the result "looks" unbalanced.
A different approach could be
<script type="text/javascript">
function CheckData() {
//you may want to check something here and based on that wanna return true and false from the function.
if(MyStuffIsokay)
return true;//will cause form to postback to server.
else
return false;//will cause form Not to postback to server
}
</script>
@using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
{
.........
.........
.........
.........
<input type="submit" value= "Save Employee" onclick="return CheckData();"/>
}
found it under /Users/username/apache-maven-3.3.9/conf
To answer your question, the current method would be to create the object then call the method:
$functions = new Functions();
$var = $functions->filter($_GET['params']);
Another way would be to make the method static
since the class has no private data to rely on:
public static function filter($data){
This can then be called like so:
$var = Functions::filter($_GET['params']);
Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions
and the public
in the method. This can then be called like you tried:
$var = filter($_GET['params']);
I was having difficulty getting the answer by @fernando-aguirre using WindowChrome
to work. It was not working in my case because I was overriding OnSourceInitialized
in the MainWindow
and not calling the base class method.
protected override void OnSourceInitialized(EventArgs e)
{
ViewModel.Initialize(this);
base.OnSourceInitialized(e); // <== Need to call this!
}
This stumped me for a very long time.
Another solution is below way and It was my fault that when happened I put HomeService
in declaration section in app.module.ts
whereas I should put HomeService
in Providers section that as you see below HomeService
in declaration:[]
is not in a correct place and HomeService
is in Providers :[]
section in a correct place that should be.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { HomeService } from './components/home/home.service';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
HomeService // You will get error here
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule
],
providers: [
HomeService // Right place to set HomeService
],
bootstrap: [AppComponent]
})
export class AppModule { }
hope this help you.
You can use Magiq, a batch operation framework for LINQ.
You have forgotten a *
between -3.7
and (prof[x])
.
Thus:
for x in range(len(prof)):
PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))
Also, there seems to be missing an (
as I count 6 times (
and 7 times )
, and I think (math.e, (0/2.25))
is missing a function call (probably math.pow
, but thats just a wild guess).
I realize this is an old question, but the same issue happened to me, but for a completely different reason.
It could be that cvs-dude changed certificates, so it no longer matches the certificate you have cached.
You can go to TortoiseSVN->Settings->Saved Data and click the 'Clear' button next to 'Authentication data' and then try again.
I have just tried this code locally in .Net 4.5 and the service starts and stops correctly for me. I suspect your problem may be around creating the EventLog source.
The method:
EventLog.SourceExists("MySource")
requires that the user running the code must be an administrator, as per the documentation here:
http://msdn.microsoft.com/en-us/library/x7y6sy21(v=vs.110).aspx
Check that the service is running as a user that has administrator privileges.
Certify that your Manifest declaration includes android:theme="@style/AppTheme.NoActionBar" tag, like the following:
<activity
android:name=".PointsScreen"
android:theme="@style/AppTheme.NoActionBar">
</activity>
I was facing the same problem.
See in your github for a particular branch and you will come to know the commit id of the very first commit in that branch. do a rebase to that:
git rebase -i
editor will open up. Do a track of your commits from github UI and opened editor and change the messages.
The first one. Those file paths are relative from where your .gitignore file is.
I solved my own problem when using google distance matrix API by setting my request header with Jquery ajax. take a look below.
var settings = {
'cache': false,
'dataType': "jsonp",
"async": true,
"crossDomain": true,
"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:"+me.originPlaceId+"&destinations=place_id:"+me.destinationPlaceId+"®ion=ng&units=metric&key=mykey",
"method": "GET",
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Note what i added at the settings
**
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
**
I hope this helps.
Swift 5 Extension
This can be used as a Extension and called with: UIApplication.topSafeAreaHeight
extension UIApplication {
static var topSafeAreaHeight: CGFloat {
var topSafeAreaHeight: CGFloat = 0
if #available(iOS 11.0, *) {
let window = UIApplication.shared.windows[0]
let safeFrame = window.safeAreaLayoutGuide.layoutFrame
topSafeAreaHeight = safeFrame.minY
}
return topSafeAreaHeight
}
}
Extension of UIApplication is optional, can be an extension of UIView or whatever is preferred, or probably even better a global function.
Objective-C
NSString *str = @"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
Swift
let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
If you want to do multiple commands, you could use:
for I in `ls *.sql`
do
grep "foo" $I >> foo.log
grep "bar" $I >> bar.log
done
On Ubuntu you should be able to install the necessary PDO parts from apt using sudo apt-get install php5-mysql
There is no limitation between using PDO and mysql_ simultaneously. You will however need to create two connections to your DB, one with mysql_ and one using PDO.
If
git config --global core.filemode false
does not work for you, do it manually:
cd into yourLovelyProject folder
cd into .git folder:
cd .git
edit the config file:
nano config
change true to false
[core]
repositoryformatversion = 0
filemode = true
->
[core]
repositoryformatversion = 0
filemode = false
save, exit, go to upper folder:
cd ..
reinit the git
git init
you are done!
Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:
public static void write (String filename, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
outputWriter.write(Integer.toString(x[i]);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
If you just want to print out the array like [1, 2, 3, ....]
, you can replace the loop with this one liner:
outputWriter.write(Arrays.toString(x));
If you're talking about an HTTP request, you can find the request host in:
request.headers.host
But that relies on an incoming request.
More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest
If you're looking for machine/native information, try the process object.
aws s3 ls s3://bucket-name/folder-prefix-if-any --recursive | wc -l
use app.render
in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.
You can focus on a split window using # ctrl-ww
.
for example, pressing:
1 ctrl-ww
would focus on the first window, usually being NERDTree.
In addition to above, if you need WCF support, you might need to run this:
c:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe -i
Replace v3.0 to whatever your current framework version is.
This is no more .NET Core vs. Mono. It's unified.
Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core
.NET and Mono will be unified under .NET 6 that would be released in November 2021
net6.0-ios
and net6.0-android
.net6.0-ios14
.Check below articles:
sudo -u postgres createuser -s tom
this should help you as this will happen if the administrator has not created a PostgreSQL user account for you. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name, in that case you need to use the -U switch.
In this code, jsondata is our array and in function return we are checking the 'version' present in the jsondata.
var as = $filter('filter')(jsondata, function (n,jsondata){
return n.filter.version==='V.0.3'
});
console.log("name is " + as[0].name+as[0]);
Sometimes you can't see the wood for the trees :)
Your original SQL ..
SELECT contactid
WHERE flag = 'Volunteer'
AND flag = 'Uploaded'...
Should be:
SELECT contactid
WHERE flag = 'Volunteer'
OR flag = 'Uploaded'...
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
Better just create a XLSX file with field names on top row. Create it manually or using Mockaroo. Export it to Excel(or CSV) and then import it to Access using New Data Source -> From File
IMHO it's the best and most performant way to do it in Access.
Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)
Code:
include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf');
$a->decodePDF();
echo $a->output();
class.pdf2text.php
Project Home
pdf2textclass
doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser
If you have the MM/DD/YYYY
format which is default for JavaScript, you can simply pass your string to Date(string)
constructor. It will parse it for you.
var dateString = "10/23/2015"; // Oct 23_x000D_
_x000D_
var dateObject = new Date(dateString);_x000D_
_x000D_
document.body.innerHTML = dateObject.toString();
_x000D_
If you work with this format, then you can split the date in order to get day, month and year separately and then use it in another constructor - Date(year, month, day)
:
var dateString = "23/10/2015"; // Oct 23_x000D_
_x000D_
var dateParts = dateString.split("/");_x000D_
_x000D_
// month is 0-based, that's why we need dataParts[1] - 1_x000D_
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); _x000D_
_x000D_
document.body.innerHTML = dateObject.toString();
_x000D_
For more information, you can read article about Date
at Mozilla Developer Network.
moment.js
libraryAlternatively, you can use moment.js
library, which is probably the most popular library to parse and operate with date and time in JavaScript:
var dateString = "23/10/2015"; // Oct 23_x000D_
_x000D_
var dateMomentObject = moment(dateString, "DD/MM/YYYY"); // 1st argument - string, 2nd argument - format_x000D_
var dateObject = dateMomentObject.toDate(); // convert moment.js object to Date object_x000D_
_x000D_
document.body.innerHTML = dateObject.toString();
_x000D_
<script src="https://momentjs.com/downloads/moment.min.js"></script>
_x000D_
In all three examples dateObject
variable contains an object of type Date
, which represents a moment in time and can be further converted to any string format.
<script type="text/javascript">
$(document).ready(function() {
showWarning('@ViewBag.Message');
});
</script>
You can use ViewBag.PropertyName in javascript like this.
A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.
New run configurations default to using the project directory for the working directory, though this can also be changed.
This code shows the difference between the working directory, and the location of where the class was loaded from:
public class TellMeMyWorkingDirectory {
public static void main(String[] args) {
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
}
}
The output is likely to be something like:
C:\your\project\directory
/C:/your/project/directory/bin/
A POD is a type (including classes) where the C++ compiler guarantees that there will be no "magic" going on in the structure: for example hidden pointers to vtables, offsets that get applied to the address when it is cast to other types (at least if the target's POD too), constructors, or destructors. Roughly speaking, a type is a POD when the only things in it are built-in types and combinations of them. The result is something that "acts like" a C type.
int
, char
, wchar_t
, bool
, float
, double
are PODs, as are long/short
and signed/unsigned
versions of them.enums
are PODsconst
or volatile
POD is a POD.class
, struct
or union
of PODs is a POD provided that all non-static data members are public
, and it has no base class and no constructors, destructors, or virtual methods. Static members don't stop something being a POD under this rule. This rule has changed in C++11 and certain private members are allowed: Can a class with all private members be a POD class?3.9(10): "Arithmetic types (3.9.1), enumeration types, pointer types, and pointer to member types (3.9.2) and cv-qualified versions of these types (3.9.3) are collectively caller scalar types. Scalar types, POD-struct types, POD-union types (clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called POD types"
9(4): "A POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor. Similarly a POD-union is an aggregate union that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-define copy operator and no user-defined destructor.
8.5.1(1): "An aggregate is an array or class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10) and no virtual functions (10.3)."
Set the height for the parent element.
There is a better way to do this. Use the concat Method. Example
declare a global variable. this works good on angular 10, just pass it to Vanilla JavaScript. Example:
HTML
<input id="edValue" type="text" onKeyPress="edValueKeyPress($event)"><br>
<span id="lblValue">The text box contains: </span>
CODE
emptyString = ''
edValueKeyPress ($event){
this.emptyString = this.emptyString.concat($event.key);
console.log(this.emptyString);
}
If You want make json object from yor model do like this :
foreach (var item in Persons)
{
var jsonObj=["FirstName":"@item.FirstName"]
}
Or Use Json.Net to make json from your model :
string json = JsonConvert.SerializeObject(person);
Other way for get a list just local branch is:
git branch -a | grep -v 'remotes'
You need to transform the object you are getting back into an array in the format that jQueryUI expects.
You can use $.map
to transform the dealers
object into that array.
$('#dealerName').autocomplete({
source: function (request, response) {
$.getJSON("/example/location/example.json?term=" + request.term, function (data) {
response($.map(data.dealers, function (value, key) {
return {
label: value,
value: key
};
}));
});
},
minLength: 2,
delay: 100
});
Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label
and value
properties that $.map
's callback function return.
Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:
label
property, a value
property, or both, orIn other words, if you can format the data like this:
[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
or this:
["dealer 5", "dealer 6"]
Then your JavaScript becomes much simpler:
$('#dealerName').autocomplete({
source: "/example/location/example.json"
});
Similar to the previous answer: Just use the 'name' key with your regular add_index line:
def change
add_index :studies, :user_id, name: 'my_index'
end
As it's 2019 I'd like to give an updated answer to this question. It is possible to achieve the same result as nested forms, but without nesting them. HTML5 introduced the form attribute. You can add the form attribute to form controls outside of a form to link them to a specific form element (by id).
https://www.impressivewebs.com/html5-form-attribute/
This way you can structure your html like this:
<form id="main-form" action="/main-action" method="post"></form>
<form id="sub-form" action="/sub-action" method="post"></form>
<div class="main-component">
<input type="text" name="main-property1" form="main-form" />
<input type="text" name="main-property2" form="main-form" />
<div class="sub-component">
<input type="text" name="sub-property1" form="sub-form" />
<input type="text" name="sub-property2" form="sub-form" />
<input type="submit" name="sub-save" value="Save" form="sub-form" />
</div>
<input type="submit" name="main-save" value="Save" form="main-form" />
</div>
The form attribute is supported by all modern browsers. IE does not support this though but IE is not a browser anymore, rather a compatibility tool, as confirmed by Microsoft itself: https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/. It's about time we stop caring about making things work in IE.
https://caniuse.com/#feat=form-attribute
https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form
From the html spec:
This feature allows authors to work around the lack of support for nested form elements.
I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr
), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:
```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```
Then all the images will be written as PDF files, and LaTeX will be happy.
Your second problem is you are mixing up the HTML units with LaTeX units in out.width
/ out.height
. LaTeX and HTML are very different technologies. You should not expect \maxwidth
to work in HTML, or 200px
in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width
/ out.height
(use fig.width
/ fig.height
and let LaTeX use the original size).
Vary the consumer-rate and the producer-rate (using sleep), to better understand the operation of code. The code below is the consumer-producer simulation (over a max-limit on container).
Code for your reference:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t semP, semC;
int stock_count = 0;
const int stock_max_limit=5;
void *producer(void *arg) {
int i, sum=0;
for (i = 0; i < 10; i++) {
while(stock_max_limit == stock_count){
printf("stock overflow, production on wait..\n");
sem_wait(&semC);
printf("production operation continues..\n");
}
sleep(1); //production decided here
stock_count++;
printf("P::stock-count : %d\n",stock_count);
sem_post(&semP);
printf("P::post signal..\n");
}
}
void *consumer(void *arg) {
int i, sum=0;
for (i = 0; i < 10; i++) {
while(0 == stock_count){
printf("stock empty, consumer on wait..\n");
sem_wait(&semP);
printf("consumer operation continues..\n");
}
sleep(2); //consumer rate decided here
stock_count--;
printf("C::stock-count : %d\n", stock_count);
sem_post(&semC);
printf("C::post signal..\n");
}
}
int main(void) {
pthread_t tid0,tid1;
sem_init(&semP, 0, 0);
sem_init(&semC, 0, 0);
pthread_create(&tid0, NULL, consumer, NULL);
pthread_create(&tid1, NULL, producer, NULL);
pthread_join(tid0, NULL);
pthread_join(tid1, NULL);
sem_destroy(&semC);
sem_destroy(&semP);
return 0;
}
I was debugging an SSL issue today which resulted in the same write:errno=104
error. Eventually I found out that the reason for this behaviour was that the server required SNI (servername
TLS extensions) to work correctly. Supplying the -servername
option to openssl made it connect successfully:
openssl s_client -connect domain.tld:443 -servername domain.tld
Hope this helps.
You must remove alpha channels when uploading a photo to iTunes Connect.
You can do this by Preview, Photos App (old iPhoto), Pixelmator, Adobe Photoshop and GIMP.
Preview
Open the photo in Preview (if the photo is in your photo album in Photos app (the old iPhoto), then simply drag it from the album to desktop. Then control-click (right-click when mouse) the duplicated photo and select Preview.app under Open With menu).
Select Export… under File menu, and after selecting the destination, uncheck Alpha at the bottom, and click Export.
Pixelmator
Open the image in Pixelmator, without creating a new Pixelmator file. Just drag the photo to the Pixelmator window.
From Share menu, click Export for Web…
In the top bar, deselect Transparency.
Click Next and then save the new file somewhere.
Finally, upload the new photo to iTunes Connect.
GIMP
Open the photo in GIMP.
Open the Layer menu.
Under Transparency, click Remove Alpha Channel.
Save the photo.
Adobe Photoshop
Open the photo in Adobe Photoshop.
Under Layer menu, click Layer Mask and then From Transparency.
Delete the layer mask by right-clicking on the mask in the Layer panel and selecting Delete Layer Mask.
Look for this:
ANY page in your project that has a missing, or different Namespace...
If you have ANY page in your project with <NO Namespace
> , OR a
DIFFERENT Namespace than Default.aspx, you will get this
"Cannot load Default.aspx", or this: "Default.aspx does not belong here".
ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...
BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??
DGK
If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &
-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:
void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference
You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)
), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.
Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.
I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:
void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }
int main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
foo1(arr);
foo2(arr);
foo3(arr);
foo4(arr);
}
way of getting home directory of current user is
String currentUsersHomeDir = System.getProperty("user.home");
and to append path separator
String otherFolder = currentUsersHomeDir + File.separator + "other";
The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.
Using regex:
if re.match(r'^\s*$', line):
# line is empty (has only the following: \t\n\r and whitespace)
Using regex + filter()
:
filtered = filter(lambda x: not re.match(r'^\s*$', x), original)
As seen on codepad.
I've been using IE Tester (good) but didn't know I could simply switch versions in IE. It's nice to know the browser voted "Most likely to be the bain of your existence" has the tool built in to look at previous versions.
The down side to IE Tester is it does not support javascript well, and also doesn't always do a great job with iframes. (Yes, I still use them.)
I decided that since Google and Facebook no longer support IE7, I won't either. I have a lot less funding than they do.
I know this doesn't fix the need to use VM for MAC users, but there should be ways around that too. With an 8 core processor PC computer, you can VM MAC with 4 cores, same for PC, and run 4 displays, two for each OS. Expensive, but this is our business. In most business models, it is not uncommon to spend tens of thousands of dollars on equipment. We shouldn't think of ourselves any differently. Invest in your success.
in php.ini file,uncomment this one
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
;sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"
and in sendmail.ini
smtp_server=smtp.gmail.com
smtp_port=465
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=yourpassword
[email protected]
hostname=localhost
configure this one..it will works...it working fine for me.
thanks.
Obviously, of the two methods you mention number 1 is more efficient, since it only needs to go through the list once, while with method number 2 the list has to be traversed two times (first to find the elements to remove, and them to remove them).
Actually, removing a list of elements from another list is likely an algorithm that's worse than O(n) so method 2 is even worse.
The iterator method:
List data = ...;
for (Iterator i = data.iterator(); i.hasNext(); ) {
Object element = i.next();
if (!(...)) {
i.remove();
}
}
You have a variable that is equal to None and you're attempting to access an attribute of it called 'something'.
foo = None
foo.something = 1
or
foo = None
print(foo.something)
Both will yield an AttributeError: 'NoneType'
Adding to Eric's answer, you can also configure this in the csproj
file:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>MyTests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
Or if you have one test project per project to be tested, you could do something like this in your Directory.Build.props
file:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>$(MSBuildProjectName).Test</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
See: https://stackoverflow.com/a/49978185/1678053
Example: https://github.com/gldraphael/evlog/blob/master/Directory.Build.props#L5-L12
You can just concatenate the strings and build a command line.
std::string command = a + ' ' + b + " > " + c;
system(command.c_str());
You don't need any extra libraries for this.
As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.
Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!
More details on their SourceForge page here:
"NTFS can actually support pathnames up to 32,000 characters in length."
7-zip also support such long names.
But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.
and release notes:
9.32 alpha 2013-12-01
- Improved support for file pathnames longer than 260 characters.
4.44 beta 2007-01-20
- 7-Zip now supports file pathnames longer than 260 characters.
IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.
I'd recomment using good old javascript:
document.getElementById("addRunner").reset();
A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true
or false
.
.attr("hidden", false)
will remove the attribute the same as using .removeAttr("hidden")
.
.attr("hidden", "false")
is incorrect and the tag remains hidden.
You should not be setting hidden
, checked
, selected
, or several others to any string value to toggle it.
It looks like your $pdo
variable is not initialized.
I can't see in the code you've uploaded where you are initializing it.
Make sure you create a new PDO object in the global scope
before calling the class methods. (You should declare it in the global scope because of how you implemented the methods inside the Category class).
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
string1.equals(string2)
is right way to do it.
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually results WRONG.
if (s.equals(t)) // RIGHT way to check the two strings
/* == will fail in following case:*/
String s1 = new String("abc");
String s2 = new String("abc");
if(s1==s2) //it will return false
EDIT:
Indeed there was a patch which included sign()
in math, but it wasn't accepted, because they didn't agree on what it should return in all the edge cases (+/-0, +/-nan, etc)
So they decided to implement only copysign, which (although more verbose) can be used to delegate to the end user the desired behavior for edge cases - which sometimes might require the call to cmp(x,0)
.
I don't know why it's not a built-in, but I have some thoughts.
copysign(x,y):
Return x with the sign of y.
Most importantly, copysign
is a superset of sign
! Calling copysign
with x=1 is the same as a sign
function. So you could just use copysign
and forget about it.
>>> math.copysign(1, -4)
-1.0
>>> math.copysign(1, 3)
1.0
If you get sick of passing two whole arguments, you can implement sign
this way, and it will still be compatible with the IEEE stuff mentioned by others:
>>> sign = functools.partial(math.copysign, 1) # either of these
>>> sign = lambda x: math.copysign(1, x) # two will work
>>> sign(-4)
-1.0
>>> sign(3)
1.0
>>> sign(0)
1.0
>>> sign(-0.0)
-1.0
>>> sign(float('nan'))
-1.0
Secondly, usually when you want the sign of something, you just end up multiplying it with another value. And of course that's basically what copysign
does.
So, instead of:
s = sign(a)
b = b * s
You can just do:
b = copysign(b, a)
And yes, I'm surprised you've been using Python for 7 years and think cmp
could be so easily removed and replaced by sign
! Have you never implemented a class with a __cmp__
method? Have you never called cmp
and specified a custom comparator function?
In summary, I've found myself wanting a sign
function too, but copysign
with the first argument being 1 will work just fine. I disagree that sign
would be more useful than copysign
, as I've shown that it's merely a subset of the same functionality.
Edit: This has since been fixed in the latest TS versions. Quoting @Simon_Weaver's comment on the OP's post:
Note: this has since been fixed (not sure which exact TS version). I get these errors in VS, as you would expect:
Index signatures are incompatible. Type '{ firstName: string; }' is not assignable to type 'IPerson'. Property 'lastName' is missing in type '{ firstName: string; }'.
You can make use of the typed dictionary by splitting your example up in declaration and initialization, like:
var persons: { [id: string] : IPerson; } = {};
persons["p1"] = { firstName: "F1", lastName: "L1" };
persons["p2"] = { firstName: "F2" }; // will result in an error
You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right.
I'm not busting your balls, I mean that with all the best intention.
There are a couple of ways to do that. I normally fall back to just using something like this:
long start = System.currentTimeMillis();
// ... do something ...
long end = System.currentTimeMillis();
or the same thing with System.nanoTime();
For something more on the benchmarking side of things there seems also to be this one: http://jetm.void.fm/ Never tried it though.
It is no use putting the .fn, it will reffers to the prototype.
What you need to do is $.fancybox.close();
The thing is that you are maybe experiencing another error from js.
There are any errors on screen?
Is your fancybox and jquery the latest releases?
jquery is currently in 1.4.1 and fb in 1.3 something
Experiment putting a link inside the fancybox and put that function in it.
You probably had read that, but in any case, http://fancybox.net/api
One thing that you probably might need to do is isolate each part in order to realize what it is.
Just add
style="white-space:nowrap;"
Example:
<table class="blueTable" style="white-space:nowrap;">
<tr>
<td>My name is good</td>
</tr>
</table>
If you're using .NET 3.5 you can do this in a one-liner with LINQ:
int count = source.Count(f => f == '/');
If you don't want to use LINQ you can do it with:
int count = source.Split('/').Length - 1;
You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:
Your original = 12s
source.Count = 19s
source.Split = 17s
foreach (from bobwienholt's answer) = 10s
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.)
you can do like this
<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>
find this page
http://www.corelangs.com/html/links/new-window.html
goreb