From comments:
But, this code never stops (because of integer overflow) !?! Yves Daoust
For many numbers it will not overflow.
If it will overflow - for one of those unlucky initial seeds, the overflown number will very likely converge toward 1 without another overflow.
Still this poses interesting question, is there some overflow-cyclic seed number?
Any simple final converging series starts with power of two value (obvious enough?).
2^64 will overflow to zero, which is undefined infinite loop according to algorithm (ends only with 1), but the most optimal solution in answer will finish due to shr rax
producing ZF=1.
Can we produce 2^64? If the starting number is 0x5555555555555555
, it's odd number, next number is then 3n+1, which is 0xFFFFFFFFFFFFFFFF + 1
= 0
. Theoretically in undefined state of algorithm, but the optimized answer of johnfound will recover by exiting on ZF=1. The cmp rax,1
of Peter Cordes will end in infinite loop (QED variant 1, "cheapo" through undefined 0
number).
How about some more complex number, which will create cycle without 0
?
Frankly, I'm not sure, my Math theory is too hazy to get any serious idea, how to deal with it in serious way. But intuitively I would say the series will converge to 1 for every number : 0 < number, as the 3n+1 formula will slowly turn every non-2 prime factor of original number (or intermediate) into some power of 2, sooner or later. So we don't need to worry about infinite loop for original series, only overflow can hamper us.
So I just put few numbers into sheet and took a look on 8 bit truncated numbers.
There are three values overflowing to 0
: 227
, 170
and 85
(85
going directly to 0
, other two progressing toward 85
).
But there's no value creating cyclic overflow seed.
Funnily enough I did a check, which is the first number to suffer from 8 bit truncation, and already 27
is affected! It does reach value 9232
in proper non-truncated series (first truncated value is 322
in 12th step), and the maximum value reached for any of the 2-255 input numbers in non-truncated way is 13120
(for the 255
itself), maximum number of steps to converge to 1
is about 128
(+-2, not sure if "1" is to count, etc...).
Interestingly enough (for me) the number 9232
is maximum for many other source numbers, what's so special about it? :-O 9232
= 0x2410
... hmmm.. no idea.
Unfortunately I can't get any deep grasp of this series, why does it converge and what are the implications of truncating them to k bits, but with cmp number,1
terminating condition it's certainly possible to put the algorithm into infinite loop with particular input value ending as 0
after truncation.
But the value 27
overflowing for 8 bit case is sort of alerting, this looks like if you count the number of steps to reach value 1
, you will get wrong result for majority of numbers from the total k-bit set of integers. For the 8 bit integers the 146 numbers out of 256 have affected series by truncation (some of them may still hit the correct number of steps by accident maybe, I'm too lazy to check).
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
If you don't want to leave base R, here's a fairly succinct and expressive possibility:
x <- q.data$string
lengths(regmatches(x, gregexpr("a", x)))
# [1] 2 1 0
Maybe the most intuitive solution is probably to use the stringr
function str_remove
which is even easier than str_replace
as it has only 1 argument instead of 2.
The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern)
.
See example:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
I don't think you can do this with CSS. Instead, at regular 'word lengths' along the string, insert an HTML soft-hyphen:
ACTGATCG­AGCTGAAG­CGCAGTGC­GATGCTTC­GATGATGC­TGACGATG
This will display a hyphen at the end of the line, where it wraps, which may or may not be what you want.
Note Safari seems to wrap the long string in a <textarea>
anyway, unlike Firefox.
Use the psutil library. On Ubuntu 18.04, pip installed 5.5.0 (latest version) as of 1-30-2019. Older versions may behave somewhat differently. You can check your version of psutil by doing this in Python:
from __future__ import print_function # for Python2
import psutil
print(psutil.__versi??on__)
To get some memory and CPU stats:
from __future__ import print_function
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory()) # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])
The virtual_memory
(tuple) will have the percent memory used system-wide. This seemed to be overestimated by a few percent for me on Ubuntu 18.04.
You can also get the memory used by the current Python instance:
import os
import psutil
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0]/2.**30 # memory use in GB...I think
print('memory use:', memoryUse)
which gives the current memory use of your Python script.
There are some more in-depth examples on the pypi page for psutil.
Using onunload
allows you to display messages, but will not interrupt the navigation (because it is too late). However, using onbeforeunload
will interrupt navigation:
window.onbeforeunload = function() {
return "";
}
Note: An empty string is returned because newer browsers provide a message such as "Any unsaved changes will be lost" that cannot be overridden.
In older browsers you could specify the message to display in the prompt:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
For me follwing steps helped.
It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:
File ? Settings ? Experimental ? Gradle ? Only sync the active variant
Visual Studio 2008 Express Editions with SP1 (english):
http://download.microsoft.com/download/E/8/E/E8EEB394-7F42-4963-A2D8-29559B738298/VS2008ExpressWithSP1ENUX1504728.iso
Visual Studio 2008 Express Editions (english):
http://download.microsoft.com/download/8/B/5/8B5804AD-4990-40D0-A6AA-CE894CBBB3DC/VS2008ExpressENUX1397868.iso
Using array_column to re-index will save time if you need to find multiple times:
$lookup = array_column($arr, NULL, 'id'); // re-index by 'id'
Then you can simply $lookup[$id]
at will.
I googled it for like half an hour and the only useful thing I came up with was invoking the find
utility:
# Find and then delete all files under current directory (.) that:
# 1. contains "cmake" (case-&insensitive) in its path (wholename)
# 2. name is not CMakeLists.txt
find . -iwholename '*cmake*' -not -name CMakeLists.txt -delete
Also, be sure to invoke make clean
(or whatever CMake generator you're using) before that.
:)
Look at the const
and static
section of the Rust book.
You can use something as follows:
const N: i32 = 5;
or
static N: i32 = 5;
in global space.
But these are not mutable. For mutability, you could use something like:
static mut N: i32 = 5;
Then reference them like:
unsafe {
N += 1;
println!("N: {}", N);
}
To obtain the current stable version of the NuGet package use:
https://www.nuget.org/api/v2/package/{packageID}
There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here
You need the oracle client driver installed for those classes to work.
There might be 3rd party connection frameworks out there that can handle Oracle, perhaps someone else might know of some specific ones.
This is a very simple example of factorial with Recursion:
Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.
function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * factorial($number-1));
}
}
hope this is usefull for you. :)
SWIFT 5
With the latest release of Swift 3 we can get pretty descriptions of type names through the String
initializer. Like, for example print(String(describing: type(of: object)))
. Where object
can be an instance variable like array, a dictionary, an Int
, a NSDate
, an instance of a custom class, etc.
Here is my complete answer: Get class name of object as string in Swift
That question is looking for a way to getting the class name of an object as string but, also i proposed another way to getting the class name of a variable that isn't subclass of NSObject
. Here it is:
class Utility{
class func classNameAsString(obj: Any) -> String {
//prints more readable results for dictionaries, arrays, Int, etc
return String(describing: type(of: obj))
}
}
I made a static function which takes as parameter an object of type Any
and returns its class name as String
:) .
I tested this function with some variables like:
let diccionary: [String: CGFloat] = [:]
let array: [Int] = []
let numInt = 9
let numFloat: CGFloat = 3.0
let numDouble: Double = 1.0
let classOne = ClassOne()
let classTwo: ClassTwo? = ClassTwo()
let now = NSDate()
let lbl = UILabel()
and the output was:
Although it may sound overkill, this is just another "possible" solution to keep Observable type and reduce boilerplate...
You could always create an extension getter to get the current value of an Observable.
To do this you would need to extend the Observable<T>
interface in a global.d.ts
typings declaration file. Then implement the extension getter in a observable.extension.ts
file and finally include both typings and extension file to your application.
You can refer to this StackOverflow Answer to know how to include the extensions into your Angular application.
// global.d.ts
declare module 'rxjs' {
interface Observable<T> {
/**
* _Extension Method_ - Returns current value of an Observable.
* Value is retrieved using _first()_ operator to avoid the need to unsubscribe.
*/
value: Observable<T>;
}
}
// observable.extension.ts
Object.defineProperty(Observable.prototype, 'value', {
get <T>(this: Observable<T>): Observable<T> {
return this.pipe(
filter(value => value !== null && value !== undefined),
first());
},
});
// using the extension getter example
this.myObservable$.value
.subscribe(value => {
// whatever code you need...
});
did you check boostrap website? search for "forms"
<div class="form-row">
<div class="col">
<input type="text" class="form-control" placeholder="First name">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Last name">
</div>
You can get accurate Carousel effect using iCarousel SDK.
You can get an instant Cover Flow effect on iOS by using the marvelous and free iCarousel library. You can download it from https://github.com/nicklockwood/iCarousel and drop it into your Xcode project fairly easily by adding a bridging header (it's written in Objective-C).
If you haven't added Objective-C code to a Swift project before, follow these steps:
Swift 3 Sample Code:
override func viewDidLoad() {
super.viewDidLoad()
let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
carousel.dataSource = self
carousel.type = .coverFlow
view.addSubview(carousel)
}
func numberOfItems(in carousel: iCarousel) -> Int {
return 10
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let imageView: UIImageView
if view != nil {
imageView = view as! UIImageView
} else {
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))
}
imageView.image = UIImage(named: "example")
return imageView
}
I had a similar problem - authenticate device and user at device. I used a Cookie
header alongside an Authorization: Bearer...
header. One header authenticated the device, the other authenticated the user. I used a Cookie
header because these are commonly used for authentication.
Matthias Bynens has a library for this: https://github.com/mathiasbynens/he
Example:
console.log(
he.decode("Jörg & Jürgen rocked to & fro ")
);
// Logs "Jörg & Jürgen rocked to & fro"
I suggest favouring it over hacks involving setting an element's HTML content and then reading back its text content. Such approaches can work, but are deceptively dangerous and present XSS opportunities if used on untrusted user input.
If you really can't bear to load in a library, you can use the textarea
hack described in this answer to a near-duplicate question, which, unlike various similar approaches that have been suggested, has no security holes that I know of:
function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
console.log(decodeEntities('1 & 2')); // '1 & 2'
But take note of the security issues, affecting similar approaches to this one, that I list in the linked answer! This approach is a hack, and future changes to the permissible content of a textarea
(or bugs in particular browsers) could lead to code that relies upon it suddenly having an XSS hole one day.
VerifyError means that the class file contains bytecode that is syntactically correct but violates some semantic restriction e.g. a jump target that crosses method boundaries.
Basically, a VerifyError can only occur when there is a compiler bug, or when the class file gets corrupted in some other way (e.g. through faulty RAM or a failing HD).
Try compiling with a different JDK version and on a different machine.
If you want or need to work with a Java array then you can always use the java.util.Arrays
utility classes' static asList()
method to convert your array to a List
.
Something along those lines should work.
String mStringArray[] = { "String1", "String2" };
JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
Beware that code is written offhand so consider it pseudo-code.
If you're using jQuery, you have .trim()
.
if ($("#siren").val().trim() == "") {
// it's empty
}
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
A colleague told me to use scm.branches[0].name
and it worked. I wrapped it to a function in my Jenkinsfile:
def getGitBranchName() {
return scm.branches[0].name
}
You can create new object based on the old object using the spread operator
interface MyObject {
prop1: string;
}
const myObj: MyObject = {
prop1: 'foo',
}
const newObj = {
...myObj,
prop2: 'bar',
}
console.log(newObj.prop2); // 'bar'
TypeScript will infer all the fields of the original object and VSCode will do autocompletion, etc.
A more to-the-point CHANGELOG.
git log --since=1/11/2011 --until=28/11/2011 --no-merges --format=%B
One solution to this was posted in the PHP documentation comments: http://www.php.net/manual/en/function.curl-exec.php#80442
Code example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
// ...
$response = curl_exec($ch);
// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
Warning: As noted in the comments below, this may not be reliable when used with proxy servers or when handling certain types of redirects. @Geoffrey's answer may handle these more reliably.
For Windows 10 the event ID for lock=4800 and unlock=4801.
As it says in the answer provided by Mario and User 00000, you will need to enable logging of lock and unlock events by using their method described above by running gpedit.msc and navigating to the branch they indicated:
Computer Configuration -> Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> System Audit Policies - Local Group Policy Object -> Logon/Logoff -> Audit Other Login/Logoff
Enable for both success and failure events.
After enabling logging of those events you can filter for Event ID 4800 and 4801 directly.
This method works for Windows 10 as I just used it to filter my security logs after locking and unlocking my computer.
I assume X
and Y
are arrays? If so, there's a very simple way to do this:
x = [1, 1, 2, 4]
y = [1, 2, 2, 2]
# intersection
x & y # => [1, 2]
# union
x | y # => [1, 2, 4]
# difference
x - y # => [4]
Your initial problem was:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
previous posts correctly point out, if you want a computed property, the =
sign is errant.
Additional possibility for error:
If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }()
}
Instead of removing the =
, we add ()
to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)
However, the exact same error occurs:
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy
. It will not be executed until the value is accessed.
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
lazy var numPages: Int = { return categoriesPerPage.count }()
}
now the compiler is happy!
Taken from: http://www.w3.org/Style/Examples/007/units:
The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.
em
is basically CSS property for font sizes.
According to caniuse.com:
You can use a client-only polyfill to extend support of SSE to many other browsers. This is less likely with WebSockets. Some EventSource polyfills:
If you need to support all the browsers, consider using a library like web-socket-js, SignalR or socket.io which support multiple transports such as WebSockets, SSE, Forever Frame and AJAX long polling. These often require modifications to the server side as well.
Learn more about SSE from:
Learn more about WebSockets from:
Other differences:
I've found this page on their github repo, I'll just paste the content here.
There are two main approaches for serializing and restoring a model.
The first (recommended) saves and loads only the model parameters:
torch.save(the_model.state_dict(), PATH)
Then later:
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
The second saves and loads the entire model:
torch.save(the_model, PATH)
Then later:
the_model = torch.load(PATH)
However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.
You can do what I did to inspect such problem:
Study Android source code, Paint.java source, see both measureText and getTextBounds methods. You'd learn that measureText calls native_measureText, and getTextBounds calls nativeGetStringBounds, which are native methods implemented in C++.
So you'd continue to study Paint.cpp, which implements both.
native_measureText -> SkPaintGlue::measureText_CII
nativeGetStringBounds -> SkPaintGlue::getStringBounds
Now your study checks where these methods differ. After some param checks, both call function SkPaint::measureText in Skia Lib (part of Android), but they both call different overloaded form.
Digging further into Skia, I see that both calls result into same computation in same function, only return result differently.
To answer your question: Both your calls do same computation. Possible difference of result lies in fact that getTextBounds returns bounds as integer, while measureText returns float value.
So what you get is rounding error during conversion of float to int, and this happens in Paint.cpp in SkPaintGlue::doTextBounds in call to function SkRect::roundOut.
The difference between computed width of those two calls may be maximally 1.
EDIT 4 Oct 2011
What may be better than visualization. I took the effort, for own exploring, and for deserving bounty :)
This is font size 60, in red is bounds rectangle, in purple is result of measureText.
It's seen that bounds left part starts some pixels from left, and value of measureText is incremented by this value on both left and right. This is something called Glyph's AdvanceX value. (I've discovered this in Skia sources in SkPaint.cpp)
So the outcome of the test is that measureText adds some advance value to the text on both sides, while getTextBounds computes minimal bounds where given text will fit.
Hope this result is useful to you.
Testing code:
protected void onDraw(Canvas canvas){
final String s = "Hello. I'm some text!";
Paint p = new Paint();
Rect bounds = new Rect();
p.setTextSize(60);
p.getTextBounds(s, 0, s.length(), bounds);
float mt = p.measureText(s);
int bw = bounds.width();
Log.i("LCG", String.format(
"measureText %f, getTextBounds %d (%s)",
mt,
bw, bounds.toShortString())
);
bounds.offset(0, -bounds.top);
p.setStyle(Style.STROKE);
canvas.drawColor(0xff000080);
p.setColor(0xffff0000);
canvas.drawRect(bounds, p);
p.setColor(0xff00ff00);
canvas.drawText(s, 0, bounds.bottom, p);
}
Server 2008:
When in SSMS connected to server1.DB1 and try:
SELECT * FROM
[server2].[DB2].[dbo].[table1]
as others noted, if it doesn't work it's because the server isn't linked.
I get the error:
Could not find server DB2 in sys.servers. Verify that the correct server name was specified. If necessary, execute stored procedure sp_addlinkedserver to add the server to sys.servers.
To add the server:
reference: To add server using sp_addlinkedserver Link: [1]: To add server using sp_addlinkedserver
To see what is in your sys.servers just query it:
SELECT * FROM [sys].[servers]
In C char
gets promoted to int
in expressions. That pretty much explains every question, if you think about it.
Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie
A must read if you want to learn C.
Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.
Looking at http.Request you can find the following member variables:
// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
You can use RemoteAddr
to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).
This is all you have for sure.
Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:
req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter
This is because internally http.Header.Get
will normalise the key for you. (If you want to access header map directly, and not through Get
, you would need to use http.CanonicalHeaderKey first.)
Finally, "X-Forwarded-For"
is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:
// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
fmt.Println(ip)
}
will produce:
10.0.0.1
10.0.0.2
10.0.0.3
A pure virtual function is usually not (but can be) implemented in a base class and must be implemented in a leaf subclass.
You denote that fact by appending the "= 0" to the declaration, like this:
class AbstractBase
{
virtual void PureVirtualFunction() = 0;
}
Then you cannot declare and instantiate a subclass without it implementing the pure virtual function:
class Derived : public AbstractBase
{
virtual void PureVirtualFunction() override { }
}
By adding the override
keyword, the compiler will ensure that there is a base class virtual function with the same signature.
For editing use
vi galfit.feedme //if user has file editing permissions
or
sudo vi galfit.feedme //if user doesn't have file editing permissions
For inserting
Press i //Do required editing
For exiting
Press Esc
:wq //for exiting and saving
:q! //for exiting without saving
In my case I needed to install "JST Server Adapters". I am running Eclipse 3.6 Helios RCP Edition.
Here are the steps I followed:
After that I could define new Server Runtime Environments.
EDIT: With Eclipse 3.7 Indigo Classic, Eclipse Kepler and Luna, the steps are the same (with appropriate update site) but you need both JST Server Adapters and JST Server Adapters Extentions to get the Server Runtime Environment options.
CHAR
is a fixed-length data type that uses as much space as possible. So a:= a||'one ';
will require more space than is available. Your problem can be reduced to the following example:
declare
v_foo char(50);
begin
v_foo := 'A';
dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
-- next line will raise:
-- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
v_foo := v_foo || 'B';
dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));
end;
/
Never use char
. For rationale check the following question (read also the links):
Path.GetFileNameWithoutExtension
The Path class is wonderful.
I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.
I guess there mmust be some kind of dependency with this app.
This thing is empty nested list from which ne will append data to empty dict
ls = [['a','a1','a2','a3'],['b','b1','b2','b3'],['c','c1','c2','c3'],
['d','d1','d2','d3']]
this means to create four empty dict inside data_dict
data_dict = {f'dict{i}':{} for i in range(4)}
for i in range(4):
upd_dict = {'val' : ls[i][0], 'val1' : ls[i][1],'val2' : ls[i][2],'val3' : ls[i][3]}
data_dict[f'dict{i}'].update(upd_dict)
print(data_dict)
The output
{'dict0': {'val': 'a', 'val1': 'a1', 'val2': 'a2', 'val3': 'a3'}, 'dict1': {'val': 'b', 'val1': 'b1', 'val2': 'b2', 'val3': 'b3'},'dict2': {'val': 'c', 'val1': 'c1', 'val2': 'c2', 'val3': 'c3'}, 'dict3': {'val': 'd', 'val1': 'd1', 'val2': 'd2', 'val3': 'd3'}}
If you are trying to reference an android style, you need to put "android:" in there
android:theme="@android:style/Theme.Black"
If that doesn't solve it, you may need to edit your question with the full manifest file, so we can see more details
You can leverage the streams API of Java 8.
public class ListToMap {
public static void main(String[] args) {
List<User> items = Arrays.asList(new User("One"), new User("Two"), new User("Three"));
Map<String, User> map = createHashMap(items);
for(String key : map.keySet()) {
System.out.println(key +" : "+map.get(key));
}
}
public static Map<String, User> createHashMap(List<User> items) {
Map<String, User> map = items.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return map;
}
}
For more details visit: http://codecramp.com/java-8-streams-api-convert-list-map/
Similar to @Rhusfer answer I wrote this. In case you have a group of EditText
s and want to concatenate their values, you can write:
listOf(edit_1, edit_2, edit_3, edit_4).joinToString(separator = "") { it.text.toString() }
If you want to concatenate Map
, use this:
map.entries.joinToString(separator = ", ")
To concatenate Bundle
, use
bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }
It sorts keys in alphabetical order.
Example:
val map: MutableMap<String, Any> = mutableMapOf("price" to 20.5)
map += "arrange" to 0
map += "title" to "Night cream"
println(map.entries.joinToString(separator = ", "))
// price=20.5, arrange=0, title=Night cream
val bundle = bundleOf("price" to 20.5)
bundle.putAll(bundleOf("arrange" to 0))
bundle.putAll(bundleOf("title" to "Night cream"))
val bundleString =
bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }
println(bundleString)
// arrange=0, price=20.5, title=Night cream
Note: This code is untested
Define a record for your refCursor return type, call it rec. For example:
TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...); --define the record
rec MyRec; -- instantiate the record
Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:
LOOP
FETCH refCursor INTO rec;
EXIT WHEN refCursor%NOTFOUND;
dbms_output.put_line(rec.col1||','||rec.col2||','||...);
END LOOP;
I use a jQuery plugin called ColorBox, it is
Use String.Format
:
string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";
string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);
In the format {0,-20}
means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.
Perhaps this fiddle would help ThumbGen - jsFiddle It uses File API and Canvas to dynamically generate thumbnails of images.
(function (doc) {
var oError = null;
var oFileIn = doc.getElementById('fileIn');
var oFileReader = new FileReader();
var oImage = new Image();
oFileIn.addEventListener('change', function () {
var oFile = this.files[0];
var oLogInfo = doc.getElementById('logInfo');
var rFltr = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i
try {
if (rFltr.test(oFile.type)) {
oFileReader.readAsDataURL(oFile);
oLogInfo.setAttribute('class', 'message info');
throw 'Preview for ' + oFile.name;
} else {
oLogInfo.setAttribute('class', 'message error');
throw oFile.name + ' is not a valid image';
}
} catch (err) {
if (oError) {
oLogInfo.removeChild(oError);
oError = null;
$('#logInfo').fadeOut();
$('#imgThumb').fadeOut();
}
oError = doc.createTextNode(err);
oLogInfo.appendChild(oError);
$('#logInfo').fadeIn();
}
}, false);
oFileReader.addEventListener('load', function (e) {
oImage.src = e.target.result;
}, false);
oImage.addEventListener('load', function () {
if (oCanvas) {
oCanvas = null;
oContext = null;
$('#imgThumb').fadeOut();
}
var oCanvas = doc.getElementById('imgThumb');
var oContext = oCanvas.getContext('2d');
var nWidth = (this.width > 500) ? this.width / 4 : this.width;
var nHeight = (this.height > 500) ? this.height / 4 : this.height;
oCanvas.setAttribute('width', nWidth);
oCanvas.setAttribute('height', nHeight);
oContext.drawImage(this, 0, 0, nWidth, nHeight);
$('#imgThumb').fadeIn();
}, false);
})(document);
An easy answer is, your YouTube Channel ID is UC + {YOUR_ACCOUNT_ID}. To be sure of your YouTube Channel ID or your YouTube account ID, access the advanced settings at your settings page
And if you want to know the YouTube Channel ID for any channel, you could use the solution @mjlescano gave.
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername={USER_NAME}&part=id
If this could be of any help, some user marked it was solved in another topic right here.
This worked for me :
npm install -g local-cors-proxy
API endpoint that we want to request that has CORS issues:
https://www.yourdomain.com/test/list
Start Proxy:
lcp --proxyUrl https://www.yourdomain.com
Proxy Active
Proxy Url: http://www.yourdomain.com:28080
Proxy Partial: proxy
PORT: 8010
Then in your client code, new API endpoint:
http://localhost:8010/proxy/test/list
End result will be a request to https://www.yourdomain.ie/test/list without the CORS issues!
Definitely use Pyglet for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.
import pyglet
music = pyglet.resource.media('music.mp3')
music.play()
pyglet.app.run()
If DAO
use
RS.Move 0, RS.LastModified
lngID = RS!AutoNumberFieldName
If ADO
use
cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value
cn
being a valid ADO connection, @@Identity
will return the last
Identity
(Autonumber) inserted on this connection.
Note that @@Identity
might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider a VIEW
that joins two tables, both of which have the IDENTITY
property, and you INSERT INTO
the VIEW
. For SQL Server, consider if there are triggers that in turn insert records into another table that also has the IDENTITY
property.
BTW DMax
would not work as if someone else inserts a record just after you've inserted one but before your Dmax
function finishes excecuting, then you would get their record.
you can check installed c# compilers and the printed version of the .net:
@echo off
for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do (
set "l="
for /f "skip=1 tokens=2 delims=k" %%$ in ('"%%# #"') do (
if not defined l (
echo Installed: %%$
set l=%%$
)
)
)
echo latest installed .NET %l%
the csc.exe
does not have a -version
switch but it prints the .net version in its logo. You can also try with msbuild.exe but .net framework 1.* does not have msbuild.
Try data = new int[] {10,20,30,40,50,60,71,80,90,91 };
For example: conda install -c conda-forge spacy
You can do the following:
Example using PHP (you can do this in any language of your choice):
Server:
<?php $years = range(1900, strftime("%Y", time())); ?>
HTML
<select>
<option>Select Year</option>
<?php foreach($years as $year) : ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
As an added benefit, this works has a browser compatibility of a 100% ;-)
Alternatively, if you are using ui-router:
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title ng-bind="$state.current.data.title || 'App'">App</title>
Routing
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home.html',
data: {
title: 'Welcome Home.'
}
}
mysql : < (for import) > (for export)
in windows, you want to take backup or import the sql file, then goto cmd prompt type the address were the mysql is installed eg:C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> after this
C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> mysql -u UserName -p Password DatabaseName < FileName.sql (import)
C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin> mysql -u UserName -p Password DatabaseName > FileName.sql (export)
CONTROL + SHIFT + P and execute command "Tree View: Show"
I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.
There are a few listed (at the end of the post) in on this java learning resources article too
For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.
mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/
And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent
And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)
/**
*
* @param delim : String that should be kept in between the parts
* @param parts : parts that needs to be joined
* @return a String that's formed by joining the parts
*/
private static final String join(String delim, String... parts) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
builder.append(parts[i]).append(delim);
}
if(parts.length > 0){
builder.append(parts[parts.length - 1]);
}
return builder.toString();
}
There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.
Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.
Copy the PEM file to your Mac and set it to be read-only by your user:
chmod 400 <private-key-filename>.pem
Then you should be able to use ssh to connect to your remote server
ssh -i <private-key-filename>.pem username@hostname
go to your project directory in CMD, and run the following commands. You can use the visual studio code terminal also.
ng generate component "component_name"
OR
ng g c "component_name"
a new folder with "component_name"
will be created
component_name/component_name.component.html component_name/component_name.component.spec.ts component_name/component_name.component.ts component_name/component_name.component.css
new component will be Automatically added module.
you can avoid creating spec file by following command
ng g c "component_name" --nospec
Step 1: Go to Tools-->Option-->Debugging
Step 2: Uncheck Enable Just My Code
Step 3: Uncheck Require source file exactly match with original Version
Step 4: Uncheck Step over Properties and Operators
Step 5: Go to Project properties-->Debug
Step 6: Check Enable native code debugging
- name: Move the src file to dest
command: mv /path/to/src /path/to/dest
args:
removes: /path/to/src
creates: /path/to/dest
This runs the mv
command only when /path/to/src
exists and /path/to/dest
does not, so it runs once per host, moves the file, then doesn't run again.
I use this method when I need to move a file or directory on several hundred hosts, many of which may be powered off at any given time. It's idempotent and safe to leave in a playbook.
with php you can use two redirections. It works same as refresh in some issues.
you can use a page redirect.php and post your last url to it by GET method (for example). then in redirect.php you can change header to location you`ve sent to it by GET method.
like this: your page:
<?php
header("location:redirec.php?ref=".$your_url);
?>
redirect.php:
<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>
that worked for me good.
Place any view on your desire X & Y point
layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.test.MainActivity" >
<AbsoluteLayout
android:id="@+id/absolute"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/rlParent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/btn_blue_matte" />
</RelativeLayout>
</AbsoluteLayout>
</RelativeLayout>
Java Class
public class MainActivity extends Activity {
private RelativeLayout rlParent;
private int width = 100, height = 150, x = 20, y= 50;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AbsoluteLayout.LayoutParams param = new AbsoluteLayout.LayoutParams(width, height, x, y);
rlParent = (RelativeLayout)findViewById(R.id.rlParent);
rlParent.setLayoutParams(param);
}
}
Done
To apply to an entire list, use
ul.space_list li { margin-bottom: 1em; }
Then, in the html:
<ul class=space_list>
<li>A</li>
<li>B</li>
</ul>
View more detail from my previous answer I have created an nuget package Nuget
Code on Github
sample : you can use :
string login = "";
string domain = "";
string password = "";
using (UserImpersonation user = new UserImpersonation(login, domain, password))
{
if (user.ImpersonateValidUser())
{
File.WriteAllText("test.txt", "your text");
Console.WriteLine("File writed");
}
else
{
Console.WriteLine("User not connected");
}
}
Vieuw the full code :
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
/// <summary>
/// Logon method (check athetification) from advapi32.dll
/// </summary>
/// <param name="lpszUserName"></param>
/// <param name="lpszDomain"></param>
/// <param name="lpszPassword"></param>
/// <param name="dwLogonType"></param>
/// <param name="dwLogonProvider"></param>
/// <param name="phToken"></param>
/// <returns></returns>
[DllImport("advapi32.dll")]
private static extern bool LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
/// <summary>
/// Close
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private WindowsImpersonationContext _windowsImpersonationContext;
private IntPtr _tokenHandle;
private string _userName;
private string _domain;
private string _passWord;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
/// <summary>
/// Initialize a UserImpersonation
/// </summary>
/// <param name="userName"></param>
/// <param name="domain"></param>
/// <param name="passWord"></param>
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
/// <summary>
/// Valiate the user inforamtion
/// </summary>
/// <returns></returns>
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref _tokenHandle);
if (false == returnValue)
{
return false;
}
WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
_windowsImpersonationContext = newId.Impersonate();
return true;
}
#region IDisposable Members
/// <summary>
/// Dispose the UserImpersonation connection
/// </summary>
public void Dispose()
{
if (_windowsImpersonationContext != null)
_windowsImpersonationContext.Undo();
if (_tokenHandle != IntPtr.Zero)
CloseHandle(_tokenHandle);
}
#endregion
}
In Python 3, the default encoding is "utf-8"
, so you can directly use:
b'hello'.decode()
which is equivalent to
b'hello'.decode(encoding="utf-8")
On the other hand, in Python 2, encoding defaults to the default string encoding. Thus, you should use:
b'hello'.decode(encoding)
where encoding
is the encoding you want.
Note: support for keyword arguments was added in Python 2.7.
This is the better solution:
verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));
Those two queries are performing OUTER JOIN
. See below
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions, which do not apply to the FROM clause OUTER JOIN syntax:
You cannot specify the (+) operator in a query block that also contains FROM clause join syntax.
The (+) operator can appear only in the WHERE clause or, in the context of left- correlation (when specifying the TABLE clause) in the FROM clause, and can be applied only to a column of a table or view.
If A and B are joined by multiple join conditions, then you must use the (+) operator in all of these conditions. If you do not, then Oracle Database will return only the rows resulting from a simple join, but without a warning or error to advise you that you do not have the results of an outer join.
The (+) operator does not produce an outer join if you specify one table in the outer query and the other table in an inner query.
You cannot use the (+) operator to outer-join a table to itself, although self joins are valid. For example, the following statement is not valid:
-- The following statement is not valid: SELECT employee_id, manager_id FROM employees WHERE employees.manager_id(+) = employees.employee_id;
However, the following self join is valid:
SELECT e1.employee_id, e1.manager_id, e2.employee_id FROM employees e1, employees e2 WHERE e1.manager_id(+) = e2.employee_id ORDER BY e1.employee_id, e1.manager_id, e2.employee_id;
The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression can contain one or more columns marked with the (+) operator.
A WHERE condition containing the (+) operator cannot be combined with another condition using the OR logical operator.
A WHERE condition cannot use the IN comparison condition to compare a column marked with the (+) operator with an expression.
If the WHERE clause contains a condition that compares a column from table B with a constant, then the (+) operator must be applied to the column so that Oracle returns the rows from table A for which it has generated nulls for this column. Otherwise Oracle returns only the results of a simple join.
In a query that performs outer joins of more than two pairs of tables, a single table can be the null-generated table for only one other table. For this reason, you cannot apply the (+) operator to columns of B in the join condition for A and B and the join condition for B and C. Refer to SELECT for the syntax for an outer join.
Taken from http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/queries006.htm
I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.
For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:
http://www.quirksmode.org/dom/events/contextmenu.html
<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
On OS X, I like my date to be in the format of YYYY-MM-DD HH:MM
in the output for the file.
So to specify a file I would use:
stat -f "%Sm" -t "%Y-%m-%d %H:%M" [filename]
If I want to run it on a range of files, I can do something like this:
#!/usr/bin/env bash
for i in /var/log/*.out; do
stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
done
This example will print out the last time I ran the sudo periodic daily weekly monthly
command as it references the log files.
To add the filenames under each date, I would run the following instead:
#!/usr/bin/env bash
for i in /var/log/*.out; do
stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
echo "$i"
done
The output would was the following:
2016-40-01 16:40
/var/log/daily.out
2016-40-01 16:40
/var/log/monthly.out
2016-40-01 16:40
/var/log/weekly.out
Unfortunately I'm not sure how to prevent the line break and keep the file name appended to the end of the date without adding more lines to the script.
PS - I use #!/usr/bin/env bash
as I'm a Python user by day, and have different versions of bash
installed on my system instead of #!/bin/bash
I was using below technology:
Let do below:
npm i -g @vercel/ncc
ncc build app.ts -o dist (my entry file is app.ts, output is in dist folder, make sure you run in folder where package.json and app.ts reside, after run above you may see the index.js file in the folder dist)
npm install -g pkg (installing pkg)
pkg index.js (make sure you are in the dist folder above)
I think you can try this for calling in from a class
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
*----------------Sorry I oversight, for static function already answered the question by adrift*
System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Update
I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()
Solution (tested in static webmethod)
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
Worked
From Mac OS Catalina .bash_profile is replaced with .zprofile
Step 1: Create a .zprofile
touch .zprofile
Step 2:
nano .zprofile
type below line in this
source ~/.bash_profile
and save(ctrl+o return ctrl+x)
Step 3: Restart your terminal
To Add Git Branch Name Now you can add below lines in .bash_profile
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Restart your terminal this will work.
Note: Even you can rename .bash_profile to .zprofile that also works.
It's easier to use jquery $(parent).html(code)
instead of parent.innerHTML = code
:
var oldDocumentWrite = document.write;
var oldDocumentWriteln = document.writeln;
try {
document.write = function(code) {
$(parent).append(code);
}
document.writeln = function(code) {
document.write(code + "<br/>");
}
$(parent).html(html);
} finally {
$(window).load(function() {
document.write = oldDocumentWrite
document.writeln = oldDocumentWriteln
})
}
This also works with scripts that use document.write
and scripts loaded via src
attribute. Unfortunately even this doesn't work with Google AdSense scripts.
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string>V;
int num;
cin>>num;
string input;
while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
//cin>>input;
V.push_back(input);
num--;
if(num==0)
{
vector<string>::iterator it;
for(it=V.begin();it!=V.end();it++)
cout<<*it<<endl;
};
}
return 0;
};
Same solutions as Python urllib2 Basic Auth Problem apply.
see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler
to add the Authorization
header to each request that matches the known url.
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.
Check out: http://docs.python.org/library/decimal.html
$_POST is already an array. Try this:
foreach ($_POST as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
I faced this problem for one month,Putting context tag inside server.xml is not safe it affect context elements deploying for all other host ,for big apps it take connection errors also not good isolation for example you may access other sites by folder name domain2.com/domain1Folder !! also database session connections loaded twice ! the other way is put ROOT.xml file that has context tag with full path such :
<Context path="" docBase="/var/lib/tomcat7/webapps/ROOT" />
in conf/catalina/webappsfoldername and deploy war file as ROOT.war inside webappsfoldername and also specify host such
<Host name="domianname" appBase="webapps2" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false" >
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>
</Host>
In this approach also for same type apps user sessions has not good isolation ! you may inside app1 if app1 same as app2 you may after login by server side session automatically can login to app2 ?! So you have to keep users session in client side cache and not with jsessionid ! we may change engine name from localhost to solve it. but let say playing with tomcat need more time than play with other cats!
So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.
The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.
Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').
But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.
Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)
But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.
Under Ubuntu I had the problem and solved it with
$ sudo apt-get install php5-mcrypt
$ sudo service apache2 reload
When you say "a matrix of random numbers", you can use numpy as Pavel https://stackoverflow.com/a/15451997/6169225 mentioned above, in this case I'm assuming to you it is irrelevant what distribution these (pseudo) random numbers adhere to.
However, if you require a particular distribution (I imagine you are interested in the uniform distribution), numpy.random
has very useful methods for you. For example, let's say you want a 3x2 matrix with a pseudo random uniform distribution bounded by [low,high]. You can do this like so:
numpy.random.uniform(low,high,(3,2))
Note, you can replace uniform
by any number of distributions supported by this library.
Further reading: https://docs.scipy.org/doc/numpy/reference/routines.random.html
Its been updated so
root.configure(background="red")
is now:
root.configure(bg="red")
What about this ? :
Data.indexOf(_.find(Data, function(element) {
return element.name === 'John';
}));
Assuming you are using lodash or underscorejs.
To avoid the "however" in Erandac's answer in combination of Daniel's and Salman's answers, one may use one of the following "partition workarounds"
SELECT customerID, myDate
-- partition ranking works only with CTE / from MySQL 8.0 on
, RANK() OVER (PARTITION BY customerID ORDER BY dateFrom) AS rank,
-- Erandac's method in combination of Daniel's and Salman's
-- count all items in sequence, maximum reaches row count.
, IF(customerID=@_lastRank, @_curRank:=@_curRank, @_curRank:=@_sequence+1) AS sequenceRank
, @_sequence:=@_sequence+1 as sequenceOverAll
-- Dense partition ranking, works also with MySQL 5.7
-- remember to set offset values in from clause
, IF(customerID=@_lastRank, @_nxtRank:=@_nxtRank, @_nxtRank:=@_nxtRank+1 ) AS partitionRank
, IF(customerID=@_lastRank, @_overPart:=@_overPart+1, @_overPart:=1 ) AS partitionSequence
, @_lastRank:=customerID
FROM myCustomers,
(SELECT @_curRank:=0, @_sequence:=0, @_lastRank:=0, @_nxtRank:=0, @_overPart:=0 ) r
ORDER BY customerID, myDate
The partition ranking in the 3rd variant in this code snippet will return continous ranking numbers. this will lead to a data structur similar to the rank() over partition by
result. As an example, see below. In particular, the partitionSequence will always start with 1 for each new partitionRank, using this method:
customerID myDate sequenceRank (Erandac)
| sequenceOverAll
| | partitionRank
| | | partitionSequence
| | | | lastRank
... lines ommitted for clarity
40 09.11.2016 11:19 1 44 1 44 40
40 09.12.2016 12:08 1 45 1 45 40
40 09.12.2016 12:08 1 46 1 46 40
40 09.12.2016 12:11 1 47 1 47 40
40 09.12.2016 12:12 1 48 1 48 40
40 13.10.2017 16:31 1 49 1 49 40
40 15.10.2017 11:00 1 50 1 50 40
76 01.07.2015 00:24 51 51 2 1 76
77 04.08.2014 13:35 52 52 3 1 77
79 15.04.2015 20:25 53 53 4 1 79
79 24.04.2018 11:44 53 54 4 2 79
79 08.10.2018 17:37 53 55 4 3 79
117 09.07.2014 18:21 56 56 5 1 117
119 26.06.2014 13:55 57 57 6 1 119
119 02.03.2015 10:23 57 58 6 2 119
119 12.10.2015 10:16 57 59 6 3 119
119 08.04.2016 09:32 57 60 6 4 119
119 05.10.2016 12:41 57 61 6 5 119
119 05.10.2016 12:42 57 62 6 6 119
...
You can use bootstrap 3 classes and build a table using the ng-repeat directive
Example:
angular.module('App', []);_x000D_
_x000D_
function ctrl($scope) {_x000D_
$scope.items = [_x000D_
['A', 'B', 'C'],_x000D_
['item1', 'item2', 'item3'],_x000D_
['item4', 'item5', 'item6']_x000D_
];_x000D_
}
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="App">_x000D_
<div ng-controller="ctrl">_x000D_
_x000D_
_x000D_
<table class="table table-bordered">_x000D_
<thead>_x000D_
<tr>_x000D_
<th ng-repeat="itemA in items[0]">{{itemA}}</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td ng-repeat="itemB in items[1]">{{itemB}}</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td ng-repeat="itemC in items[2]">{{itemC}}</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
live example: http://jsfiddle.net/choroshin/5YDJW/5/
Update:
or you can always try the popular ng-grid , ng-grid is good for sorting, searching, grouping etc, but I haven't tested it yet on a large scale data.
To make things even more clearer,
The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text
. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt
:
$2a$COST$BASE64
This value is stored eventually.
In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random.
Then he will need to decrypt the cipher text
.
What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.
Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)
"Select destination and Press Enter or Choose Paste"
Then you press whether Enter or choose paste to paste the value of the cell.
If you didn't press Esc afterwards you will be able to paste the value of the cell several times
Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.
And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'
SELECT DISTINCT
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)
FROM
CONSOLIDATED_LIST AS A
WHERE
CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'
I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0 and using
std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;
for (int i = 0; i < 5000000; i++)
{
double r1 = ((double)rand() / double(RAND_MAX)) * 5;
double r2 = ((double)rand() / double(RAND_MAX)) * 5;
x.push_back(r1);
y.push_back(r2);
}
int sz = x.size();
#pragma omp parallel for
for (int i = 0; i< sz; i++)
prod[i] = x[i] * y[i];
the serial code (no openmp
) runs in 79 ms.
the "parallel for" code runs in 29 ms.
If I omit the for
and use #pragma omp parallel
, the runtime shoots up to 179ms,
which is slower than serial code. (the machine has hw concurrency of 8)
the code links to libgomp
This question is old, but I wanted to add my two-cents. I read the question as " I want to run a query to my [my]SQL database and store the returned data as Pandas data structure [DataFrame]."
From the code it looks like you mean mysql database and assume you mean pandas DataFrame.
import MySQLdb as mdb
import pandas.io.sql as sql
from pandas import *
conn = mdb.connect('<server>','<user>','<pass>','<db>');
df = sql.read_frame('<query>', conn)
For example,
conn = mdb.connect('localhost','myname','mypass','testdb');
df = sql.read_frame('select * from testTable', conn)
This will import all rows of testTable into a DataFrame.
I found that the user control must have a parameterless constructor or it won't show up in the list. at least that was true in vs2005.
I'm using this https://github.com/biggora/bootstrap-ajax-typeahead
The result of code using Codeigniter/PHP
<pre>
$("#produto").typeahead({
onSelect: function(item) {
console.log(item);
getProductInfs(item);
},
ajax: {
url: path + 'produto/getProdName/',
timeout: 500,
displayField: "concat",
valueField: "idproduto",
triggerLength: 1,
method: "post",
dataType: "JSON",
preDispatch: function (query) {
showLoadingMask(true);
return {
search: query
}
},
preProcess: function (data) {
if (data.success === false) {
return false;
}else{
return data;
}
}
}
});
</pre>
C:\>help if
Performs conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
spring data save()
method will help you to perform both: adding new item and updating an existed item.
Just call the save()
and enjoy the life :))
There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:
In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).
It e.g. fits nicely with standard library-types like std::vector
:
vector<int> a{10,20}; //Curly braces -> fills the vector with the arguments
vector<int> b(10,20); //Parentheses -> uses arguments to parametrize some functionality,
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.
vector<int> d{}; //empty braces -> default constructs vector, which is equivalent
//to a vector that is filled with zero elements
Install tk-devel
(or a similarly-named package) before building Python.
In PL/SQL you can't use operators such as '=' or '<>' to test for NULL
because all comparisons to NULL
return NULL
. To compare something against NULL
you need to use the special operators IS NULL
or IS NOT NULL
which are there for precisely this purpose. Thus, instead of writing
IF var = NULL THEN...
you should write
IF VAR IS NULL THEN...
In the case you've given you also have the option of using the NVL
built-in function. NVL
takes two arguments, the first being a variable and the second being a value (constant or computed). NVL
looks at its first argument and, if it finds that the first argument is NULL
, returns the second argument. If the first argument to NVL
is not NULL
, the first argument is returned. So you could rewrite
IF var IS NULL THEN
var := 5;
END IF;
as
var := NVL(var, 5);
I hope this helps.
And because it's nearly ten years since I wrote this answer, let's celebrate by expanding it just a bit.
The COALESCE
function is the ANSI equivalent of Oracle's NVL
. It differs from NVL
in a couple of IMO good ways:
It takes any number of arguments, and returns the first one which is not NULL. If all the arguments passed to COALESCE
are NULL, it returns NULL.
In contrast to NVL
, COALESCE
only evaluates arguments if it must, while NVL
evaluates both of its arguments and then determines if the first one is NULL, etc. So COALESCE
can be more efficient, because it doesn't spend time evaluating things which won't be used (and which can potentially cause unwanted side effects), but it also means that COALESCE
is not a 100% straightforward drop-in replacement for NVL
.
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right()
refer to? The this
adds a bit of a clarifier.
Another answer to the OP's exact question is to set the consumes
content type to "text/plain"
and then declare a @RequestBody String
input parameter. This will pass the text of the POST data in as the declared String
variable (postPayload
in the following example).
Of course, this presumes your POST payload is text data (as the OP stated was the case).
Example:
@RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
For Ubuntu/Debian OS,
apt-get install -y pkg-config
For Redhat/Yum OS,
yum install -y pkgconfig
For Archlinux OS,
pacman -S pkgconf
Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.
C:\Windows\SysWOW64>regsvr32 "c:\dll.name"
I prefer to use ***_join
in dplyr
whenever I need to match data. One possible try for this
left_join(data.frame(name=target),df,by="name")
Note that the input for ***_join
require tbls or data.frame
http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
Hi All posting quite late hope it helps others, Thanking in advance to @GMK for this post Hibernate.initialize(object)
when Lazy="true"
Set<myObject> set=null;
hibernateSession.open
set=hibernateSession.getMyObjects();
hibernateSession.close();
now if i access 'set' after closing session it throws exception.
My solution :
Set<myObject> set=new HashSet<myObject>();
hibernateSession.open
set.addAll(hibernateSession.getMyObjects());
hibernateSession.close();
now i can access 'set' even after closing Hibernate Session.
There is a way more convenient 'percent'-formatting option for the .format()
format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
None of these answers mention the colClasses
argument which is another way to specify the variable classes in read.csv
.
stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "numeric") # all variables to numeric
or you can specify which columns to convert:
stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = c("PTS" = "numeric", "MP" = "numeric") # specific columns to numeric
Note that if a variable can't be converted to numeric then it will be converted to factor as default which makes it more difficult to convert to number. Therefore, it can be advisable just to read all variables in as 'character' colClasses = "character"
and then convert the specific columns to numeric once the csv is read in:
stuckey <- read.csv("C:/kalle/R/stuckey.csv", colClasses = "character")
point <- as.numeric(stuckey$PTS)
time <- as.numeric(stuckey$MP)
Another option is to use JSON.stringify(obj)
For example:
exampleObj = {'a':1,'b':2,'c':3};
alert(JSON.stringify(exampleObj))
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
Executing the following two commands solves the problem for me:
npm install -g @angular/cli
ng update --all --force
I use the tail
function:
tail(vector, n=1)
The nice thing with tail
is that it works on dataframes too, unlike the x[length(x)]
idiom.
If you have scp then:
To move your file from local to remote:
$scp /home/user/file.gz user@ipaddress:path/to/file.gz
To move your file from remote to local:
$scp user@ipaddress:path/to/file.gz /home/user/file.gz
To export your mysql file without login in to remote system:
$mysqldump -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p databasename | gzip -9 > databasename.sql.gz
To import your mysql file withoug login in to remote system:
$gunzip < databasename.sql.gz | mysql -h ipaddressofremotehost -Pportnumber -u usernameofmysql -p
Note: Make sure you have network access to the ipaddress of remote host
To check network access:
$ping ipaddressofremotehost
To restore a file from another branch, simply use the following command from your working branch:
git restore -s my-other-branch -- ./path/to/file
The -s
flag is short for source
i.e. the branch from where you want to pull the file.
(The chosen answer is very informative but also a bit overwhelming.)
Check your local hosts file (C:\Windows\System32\drivers\etc\hosts for example). In my case I had previously used this to point a URL to a dev box and then forgotten about it. When I then reused the same URL I kept getting Bad Request (Invalid Hostname) because the traffic was going to the wrong server.
You can use this:
<Button
android:id="@+id/reset_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="@drawable/btn_med"
android:text="Reset all"
android:textColor="#ffffff" />
<Button
android:id="@+id/undo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="@drawable/btn_med"
android:text="Undo"
android:textColor="#ffffff" />
in that i have put an image as background
and also added text..!
Very Simple answer
$("#table_name").DataTable().ajax.reload(null, false);
Do not put a space after the Driver
keyword in the connection string.
This fails on Windows ...
conn_str = (
r'DRIVER = {SQL Server};'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
... but this works:
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
You can simply try it with a jenkinsfile. Create a Jenkins job with following pipeline script.
pipeline {
agent any
parameters {
booleanParam(defaultValue: true, description: '', name: 'userFlag')
}
stages {
stage('Trigger') {
steps {
script {
println("triggering the pipeline from a rest call...")
}
}
}
stage("foo") {
steps {
echo "flag: ${params.userFlag}"
}
}
}
}
Build the job once manually to get it configured & just create a http POST request to the Jenkins job as follows.
The format is http://server/job/myjob/buildWithParameters?PARAMETER=Value
curl http://admin:test123@localhost:30637/job/apd-test/buildWithParameters?userFlag=false --request POST
The essential difference between /*
and /
is that a servlet with mapping /*
will be selected before any servlet with an extension mapping (like *.html
), while a servlet with mapping /
will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /*
mapping will always be selected before a /
mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar
) and those which are path mappings longer than /*
(like /foo/*
). Note that the empty string mapping is an exact match for the context root (http://host:port/context/
).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
Round has an optional parameter
Select round(123.456, 2, 1) will = 123.45
Select round(123.456, 2, 0) will = 123.46
Use is_same
:
#include <type_traits>
template <typename T>
void foo()
{
if (std::is_same<T, animal>::value) { /* ... */ } // optimizable...
}
Usually, that's a totally unworkable design, though, and you really want to specialize:
template <typename T> void foo() { /* generic implementation */ }
template <> void foo<animal>() { /* specific for T = animal */ }
Note also that it's unusual to have function templates with explicit (non-deduced) arguments. It's not unheard of, but often there are better approaches.
you can work following command to be specific in localserver kill(here: 8000)
http://localhost:8000/ kill PID(processId):
$:lsof -i tcp:8000
It will give you following groups of TCPs:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 21521 ubuntu 12u IPv6 345668 0t0 TCP *:8000 (LISTEN)
$:kill -9 21521
It will kill processId corresponding to TCP*:8000
$(document).ready(function () {
$("#txt1").attr("onfocus", "blur()");
});
$(document).ready(function () {_x000D_
$("#txt1").attr("onfocus", "blur()");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="txt1">
_x000D_
To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.
Tell me which backend technology are you using? I can give more suggestions based on that.
if echo $var | egrep -q '^[0-9]+$'; then
# $var is a number
else
# $var is not a number
fi
setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation
$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);
The easiest method is to use sys.path.append().
However, you may be also interested in the imp module. It provides access to internal import functions.
# mod_name is the filename without the .py/.pyc extention
py_mod = imp.load_source(mod_name,filename_path) # Loads .py file
py_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file
This can be used to load modules dynamically when you don't know a module's name.
I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.
Also, these functions may be useful:
imp.find_module(name[, path])
imp.load_module(name, file, pathname, description)
The way to set JFrame to full-screen, is to set MAXIMIZED_BOTH
option which stands for MAXIMIZED_VERT | MAXIMIZED_HORIZ
, which respectively set the frame to maximize vertically and horizontally
package Example;
import java.awt.GraphicsConfiguration;
import javax.swing.JFrame;
import javax.swing.JButton;
public class JFrameExample
{
static JFrame frame;
static GraphicsConfiguration gc;
public static void main(String[] args)
{
frame = new JFrame(gc);
frame.setTitle("Full Screen Example");
frame.setExtendedState(MAXIMIZED_BOTH);
JButton button = new JButton("exit");
b.addActionListener(new ActionListener(){@Override
public void actionPerformed(ActionEvent arg0){
JFrameExample.frame.dispose();
System.exit(0);
}});
frame.add(button);
frame.setVisible(true);
}
}
Try this
data to load:
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>
get a utf8 to base64 convertor and convert the "svg" string to:
PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=
and the CSP is
img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=
best way and more simple to center an iframe on your webpage is :
<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>
where width and height will be the size of your iframe in your html page.
TagLib Sharp has support for reading ID3 tags.
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Update: MixEdit extension now provides this ability.
MultiEdit extension for VS allows for something similar (doesn't support multiple selections as of this writing, just multiple carets)
Head over to Hanselman's for a quick animated gif of this in action: Simultaneous Editing for Visual Studio with the free MultiEdit extension
Below is a sample linkedlist
#include <string>
#include <iostream>
using namespace std;
template<class T>
class Node
{
public:
Node();
Node(const T& item, Node<T>* ptrnext = NULL);
T value;
Node<T> * next;
};
template<class T>
Node<T>::Node()
{
value = NULL;
next = NULL;
}
template<class T>
Node<T>::Node(const T& item, Node<T>* ptrnext = NULL)
{
this->value = item;
this->next = ptrnext;
}
template<class T>
class LinkedListClass
{
private:
Node<T> * Front;
Node<T> * Rear;
int Count;
public:
LinkedListClass();
~LinkedListClass();
void InsertFront(const T Item);
void InsertRear(const T Item);
void PrintList();
};
template<class T>
LinkedListClass<T>::LinkedListClass()
{
Front = NULL;
Rear = NULL;
}
template<class T>
void LinkedListClass<T>::InsertFront(const T Item)
{
if (Front == NULL)
{
Front = new Node<T>();
Front->value = Item;
Front->next = NULL;
Rear = new Node<T>();
Rear = Front;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
newNode->next = Front;
Front = newNode;
}
}
template<class T>
void LinkedListClass<T>::InsertRear(const T Item)
{
if (Rear == NULL)
{
Rear = new Node<T>();
Rear->value = Item;
Rear->next = NULL;
Front = new Node<T>();
Front = Rear;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
Rear->next = newNode;
Rear = newNode;
}
}
template<class T>
void LinkedListClass<T>::PrintList()
{
Node<T> * temp = Front;
while (temp->next != NULL)
{
cout << " " << temp->value << "";
if (temp != NULL)
{
temp = (temp->next);
}
else
{
break;
}
}
}
int main()
{
LinkedListClass<int> * LList = new LinkedListClass<int>();
LList->InsertFront(40);
LList->InsertFront(30);
LList->InsertFront(20);
LList->InsertFront(10);
LList->InsertRear(50);
LList->InsertRear(60);
LList->InsertRear(70);
LList->PrintList();
}
String str = "Your string";
byte[] array = str.getBytes();
Have you tried disabling buffering?
setvbuf(fd, NULL, _IONBF, 0);
Vector has some handy features:
Vector<String> siteIdVector = new Vector<>(siteIdSet);
String first = siteIdVector.firstElement();
String last = siteIdVector.lastElement();
But I do agree - this may have unintended consequences, since the underling set is not guaranteed to be ordered.
Use insertAdjacentHTML
if it's available, otherwise use some sort of fallback. insertAdjacentHTML is supported in all current browsers.
div.insertAdjacentHTML( 'beforeend', str );
Live demo: http://jsfiddle.net/euQ5n/
I think you shouldn't prepend themesDir
. You only pass the filename of the template to flask, it will then look in a folder called templates
relative to your python file.
Boilerplate code means a piece of code which can be used over and over again. On the other hand, anyone can say that it's a piece of reusable code.
The term actually came from the steel industries.
For a little bit of history, according to Wikipedia:
In the 1890s, boilerplate was actually cast or stamped in metal ready for the printing press and distributed to newspapers around the United States. Until the 1950s, thousands of newspapers received and used this kind of boilerplate from the nation's largest supplier, the Western Newspaper Union. Some companies also sent out press releases as boilerplate so that they had to be printed as written.
Now according to Wikipedia:
In object-oriented programs, classes are often provided with methods for getting and setting instance variables. The definitions of these methods can frequently be regarded as boilerplate. Although the code will vary from one class to another, it is sufficiently stereotypical in structure that it would be better generated automatically than written by hand. For example, in the following Java class representing a pet, almost all the code is boilerplate except for the declarations of Pet, name and owner:
public class Pet { private PetName name; private Person owner; public Pet(PetName name, Person owner) { this.name = name; this.owner = owner; } public PetName getName() { return name; } public void setName(PetName name) { this.name = name; } public Person getOwner() { return owner; } public void setOwner(Person owner) { this.owner = owner; } }
current package : com.company.name
New package : com.mycomapny.name
Steps: 1) Suppose you are at this screen which is shown below.
2) Open project pane and click on settings icon.
3) Deselect Compact Empty Middle Packages.
4) Then your package is now broken into individual parts as shown below .
5) right click on "company" select Refactor -> select rename ->rename directory.
6) Now your "company" has been changed to new "mycomapny" and changes were reflected as shown in below figure.
7) Now change the package name in AndroidManifest.xml file .
8) Open app level build.gradle and change package name .
9) you will get errors as Cannot resolve symbol "R" .
10) Remove line which gives this error and studio will import new R file automatically.
11) If you have multiple files then use find and replace option by pressing " Cntrl+Shift+R "
Or " Select Edit->Find->Replace in path.."
12) select Replace All.
A selector to get the middle option-element by value is
$('.selDiv option[value="SEL1"]')
For an index:
$('.selDiv option:eq(1)')
For a known text:
$('.selDiv option:contains("Selection 1")')
EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:
$('.selDiv option:eq(1)').prop('selected', true)
In older versions:
$('.selDiv option:eq(1)').attr('selected', 'selected')
EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:
$('.selDiv option')
.filter(function(i, e) { return $(e).text() == "Selection 1"})
EDIT3: Use caution with $(e).text()
as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option>
tag):
<select ...>
<option value="1">Selection 1
<option value="2">Selection 2
:
</select>
If you simply use e.text
any extra whitespace like the trailing newline will be removed, making the comparison more robust.
Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)
In php.ini file
change this
;extension=php_mysql.dll
into
extension=php_mysql.dll
I use the GetSchemaTable method, which is exposed via the IDataReader interface.
ssh [email protected]
. This should provide you with shell access to the Ubuntu server.sudo service mysql restart
should do the job.If your mySQL service is named something else like mysqld
you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
Use this..
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
Added a method replace_in_javascript
which will satisfy your requirement. Also found that you are writing a string "new_text"
in document.write()
which is supposed to refer to a variable new_text
.
let replace_in_javascript= (replaceble, replaceTo, text) => {_x000D_
return text.replace(replaceble, replaceTo)_x000D_
}_x000D_
_x000D_
var text = "this is some sample text that i want to replace";_x000D_
var new_text = replace_in_javascript("want", "dont want", text);_x000D_
document.write(new_text);
_x000D_
it's not a login issue most times. The database might not have been created. To create the database, Go to db context file and add this.Database.EnsureCreated();
▲
▼
I usually use the excellent Gucharmap to look up Unicode characters. It's installed on all recent Linux installations with Gnome under the name "Character Map". I don't know of any equivalent tools for Windows or Mac OS X, but its homepage lists a few.
You can even use brace extensions:
mkdir -p directory{1..3}/subdirectory{1..3}/subsubdirectory{1..2}
You have to use bash 3.0 or newer.
Use to_number
to convert budgpost
to a number:
when to_number(budgpost,99999) in (1001,1012,50055) THEN 'BP_GR_A'
EDIT: Make sure there are enough 9
's in to_number
to match to largest budget post.
If there are non-numeric budget posts, you could filter them out with a where
clause at then end of the query:
where regexp_like(budgpost, '^-?[[:digit:],.]+$')
Use references all the time and pointers only when you have to refer to NULL
which reference cannot refer.
See this FAQ : http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
As others have said, you're not using the right function name and it doesn't exist univerally in all browsers.
If you need to do cross-browser fetching of anything other than an element with an id with document.getElementById()
, then I would strongly suggest you get a library that supports CSS3 selectors across all browsers. It will save you a massive amount of development time, testing and bug fixing. The easiest thing to do is to just use jQuery because it's so widely available, has excellent documentation, has free CDN access and has an excellent community of people behind it to answer questions. If that seems like more than you need, then you can get Sizzle which is just a selector library (it's actually the selector engine inside of jQuery and others). I've used it by itself in other projects and it's easy, productive and small.
If you want to select multiple nodes at once, you can do that many different ways. If you give them all the same class, you can do that with:
var list = document.getElementsByClassName("myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
and it will return a list of nodes that have that class name.
In Sizzle, it would be this:
var list = Sizzle(".myButton");
for (var i = 0; i < list.length; i++) {
// list[i] is a node with the desired class name
}
In jQuery, it would be this:
$(".myButton").each(function(index, element) {
// element is a node with the desired class name
});
In both Sizzle and jQuery, you can put multiple class names into the selector like this and use much more complicated and powerful selectors:
$(".myButton, .myInput, .homepage.gallery, #submitButton").each(function(index, element) {
// element is a node that matches the selector
});
Here's a nice little global function you can add for a nicer syntax:
func dispatch_on_main(block: dispatch_block_t) {
dispatch_async(dispatch_get_main_queue(), block)
}
And usage
dispatch_on_main {
// Do some UI stuff
}
yet another solution which uses the fact that np.nan != np.nan
:
In [149]: df.query("EPS == EPS")
Out[149]:
STK_ID EPS cash
STK_ID RPT_Date
600016 20111231 600016 4.3 NaN
601939 20111231 601939 2.5 NaN
Another intuitive solution could be:
class Post
{
public $title;
public $date;
}
$posts = array();
$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';
$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';
foreach ($posts as $post) {
echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}
<style type="text/css">
#warning-message { display: none; }
@media only screen and (orientation:portrait){
#wrapper { display:none; }
#warning-message { display:block; }
}
@media only screen and (orientation:landscape){
#warning-message { display:none; }
}
</style>
....
<div id="wrapper">
<!-- your html for your website -->
</div>
<div id="warning-message">
this website is only viewable in landscape mode
</div>
You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.
I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.
Update
I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.
Another Update
So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.
Simply call the ordinal()
method on an enum value, to retrieve its corresponding number. There's no need to declare an addition attribute with its value, each enumerated value gets its own number by default, assigned starting from zero, incrementing by one for each value in the same order they were declared.
You shouldn't depend on the int
value of an enum
, only on its actual value. Enums in Java are a different kind of monster and are not like enums in C, where you depend on their integer code.
Regarding the example you provided in the question, Font.PLAIN
works because that's just an integer constant of the Font class. If you absolutely need a (possibly changing) numeric code, then an enum
is not the right tool for the job, better stick to numeric constants.
You can use:
skopeo inspect docker://<REMOTE_REGISTRY> --authfile <PULL_SECRET> | jq .RepoTags
For me the following worked:
Kill adb.exe from Task Manager
Restart Eclipse as administrator
For my app, the target was Google APIs level 10.. I went to Window-> AVD Manager and the entry for "Google APIs level 10" had a broken instead of a green tick - so I just clicked the entry and clicked the "repair" button and problem was fixed
(It was probably only 3 above..)
I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.
[src=''] {
visibility: hidden;
}
The following solution is:
getElementById
is called once at the outset. This may or may not suit your purposes.mydiv = document.getElementById("showmehideme");_x000D_
_x000D_
function showhide(d) {_x000D_
d.style.display = (d.style.display !== "none") ? "none" : "block";_x000D_
}
_x000D_
#mydiv { background-color: #ddd; }
_x000D_
<button id="button" onclick="showhide(mydiv)">Show/Hide</button>_x000D_
<div id="showmehideme">_x000D_
This div will show and hide on button click._x000D_
</div>
_x000D_
You can also type "top" and look at the list of running processes.
Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)
This maybe too late but No one provided a clear explanation of how the algorithm works
The idea of Dijkstra is simple, let me show this with the following pseudocode.
Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.
At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.
The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.
If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.
Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.
Credits to Lars Vogel
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
Found a solution from the comments I got.
Sub TestIsEmpty()
If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
MsgBox "Empty"
Else
MsgBox "Not Empty"
End If
End Sub
var people =
[{"name": 'a75',"item1": "false","item2":"false"},
{"name": 'z32',"item1": "true","item2": "false"},
{"name": 'e77',"item1": "false","item2": "false"}];
function mycomparator(a,b) { return parseInt(a.name) - parseInt(b.name); }
people.sort(mycomparator);
something along the lines of this maybe (or as we used to say, this should work).
All of the answers is true.This is another way. And I like this One
SqlCommand cmd = conn.CreateCommand()
you must notice that strings concat have a sql injection problem. Use the Parameters http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Use doubleval()
. But be very careful about using decimals in financial transactions, and validate that user input very carefully.
This is an issue with the 64 bit version of Kepler and windows7 in my case. I downloaded the 32 bit and it worked immediately.
I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...
This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.
There are a couple of fixes for this.
First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:
ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;
However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.
If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:
#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode=NO_ENGINE_SUBSTITUTION
Save the file and restart Mysql.
Source: https://www.euperia.com/development/mysql-fix-field-doesnt-default-value/1509
I worked on this issue for a few days. Installed all packages, modified web.config and still had the same problem. I finally removed
<assemblies>
<add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</assemblies>
from the web.config and it worked. No exactly sure why it didn't work with the tags in the web.config file. My guess there is a conflict with the GAC and the BIN folder.
Here is my web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpHandlers>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</handlers>
</system.webServer>
</configuration>
Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper
public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));
// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}
Once you’ve decided to change vim color scheme that you like, you’ll need to configure vim configuration file ~/.vimrc
.
For e.g. to use the elflord
color scheme just add these lines to your ~/.vimrc
file:
colo elflord
For other names of color schemes you can look in /usr/share/vim/vimNN/colors
where NN - version of VIM.
map.at("key") throws exception if missing key
If k does not match the key of any element in the container, the function throws an out_of_range exception.
//----------App.js---------------------//_x000D_
$(document).ready(function() {_x000D_
var holder = document.getElementById('holder');_x000D_
holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
holder.ondrop = function (e) {_x000D_
this.className = 'hidden';_x000D_
e.preventDefault();_x000D_
var file = e.dataTransfer.files[0];_x000D_
var reader = new FileReader();_x000D_
reader.onload = function (event) {_x000D_
document.getElementById('image_droped').className='visible'_x000D_
$('#image_droped').attr('src', event.target.result);_x000D_
}_x000D_
reader.readAsDataURL(file);_x000D_
};_x000D_
});
_x000D_
.holder_default {_x000D_
width:500px; _x000D_
height:150px; _x000D_
border: 3px dashed #ccc;_x000D_
}_x000D_
_x000D_
#holder.hover { _x000D_
width:400px; _x000D_
height:150px; _x000D_
border: 3px dashed #0c0 !important; _x000D_
}_x000D_
_x000D_
.hidden {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.visible {_x000D_
visibility: visible;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title> HTML 5 </title>_x000D_
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="http://example.com/">_x000D_
<div id="holder" style="" id="holder" class="holder_default">_x000D_
<img src="" id="image_droped" width="200" style="border: 3px dashed #7A97FC;" class=" hidden"/>_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
In case anyone comes to this post and has a similar issue. I just experienced a similar problem, but the solution was quite simple.
A developer had mistakenly dropped a copy of the web.config into the CSS directory. Once deleted, all errors were resolved and the page properly displayed.
Proxies can make this a little tricky, make sure to check out ProxyFix (Flask docs) if you are using one. Take a look at request.environ
in your particular environment. With nginx I will sometimes do something like this:
from flask import request
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
When proxies, such as nginx, forward addresses, they typically include the original IP somewhere in the request headers.
Update See the flask-security implementation. Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.
Here's another way to be compatible with an IHttpActionResult return type. In this case I am asking it to use the XML Serializer(optional) instead of Data Contract serializer, I'm using return ResponseMessage(
so that I get a return compatible with IHttpActionResult:
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<SomeType>(objectToSerialize,
new System.Net.Http.Formatting.XmlMediaTypeFormatter {
UseXmlSerializer = true
})
});
The solution below has a "SEO friendlier" version:
function hyphenize($string) {
$dict = array(
"I'm" => "I am",
"thier" => "their",
// Add your own replacements here
);
return strtolower(
preg_replace(
array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
array( '-', '' ),
// the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
cleanString(
str_replace( // preg_replace can be used to support more complicated replacements
array_keys($dict),
array_values($dict),
urldecode($string)
)
)
)
);
}
function cleanString($text) {
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[éèêë]/u' => 'e',
'/[ÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
'/–/' => '-', // UTF-8 hyphen to "normal" hyphen
'/[’‘‹›‚]/u' => ' ', // Literally a single quote
'/[“”«»„]/u' => ' ', // Double quote
'/ /' => ' ', // nonbreaking space (equiv. to 0x160)
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.
After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru
"behaved better" than viaggi-economy-per
(the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).
There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.
In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict
needs to be hand tailored, of course.
A simple approach:
// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped
$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);
// Replace sequences of spaces with hyphen
$str = preg_replace('/ */', '-', $str);
// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)
// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);
// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything
Note that you might have to first urldecode()
the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.
So the finished function along with test cases:
function hyphenize($string) {
return
## strtolower(
preg_replace(
array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
array('-', ''),
## cleanString(
urldecode($string)
## )
)
## )
;
}
print implode("\n", array_map(
function($s) {
return $s . ' becomes ' . hyphenize($s);
},
array(
'Never%20gonna%20give%20you%20up',
"I'm not the man I was",
"'Légeresse', dit sa majesté",
)));
Never%20gonna%20give%20you%20up becomes never-gonna-give-you-up
I'm not the man I was becomes im-not-the-man-I-was
'Légeresse', dit sa majesté becomes legeresse-dit-sa-majeste
To handle UTF-8 I used a cleanString
implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.
The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.
node.js, recursive simple function:
var path = require('path'), fs=require('fs');
function fromDir(startPath,filter){
//console.log('Starting from dir '+startPath+'/');
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
fromDir(filename,filter); //recurse
}
else if (filename.indexOf(filter)>=0) {
console.log('-- found: ',filename);
};
};
};
fromDir('../LiteScript','.html');
add RegExp if you want to get fancy, and a callback to make it generic.
var path = require('path'), fs=require('fs');
function fromDir(startPath,filter,callback){
//console.log('Starting from dir '+startPath+'/');
if (!fs.existsSync(startPath)){
console.log("no dir ",startPath);
return;
}
var files=fs.readdirSync(startPath);
for(var i=0;i<files.length;i++){
var filename=path.join(startPath,files[i]);
var stat = fs.lstatSync(filename);
if (stat.isDirectory()){
fromDir(filename,filter,callback); //recurse
}
else if (filter.test(filename)) callback(filename);
};
};
fromDir('../LiteScript',/\.html$/,function(filename){
console.log('-- found: ',filename);
});
This is an example, which shows that by converting an int to char, one can determine the corresponding character to an ASCII code.
public class sample6
{
public static void main(String... asf)
{
for(int i =0; i<256; i++)
{
System.out.println( i + ". " + (char)i);
}
}
}
It is also possible to load scripts and links into the header. I'll be adding it one of the examples above...
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:[email protected]'>Contact Us</a> / "
+ "<a href='mailto:[email protected]'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
I had a similar problem. I was attempting to have a file written every time a user visits a website.
The problem ended up being twofold.
1: the permissions were not set correctly
2: I attempted to use
f = open(r"newfile.txt","w+")
(Wrong)
After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+")
(Right)