first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
This way you can create Observable from data, in my case I need to maintain shopping cart:
service.ts
export class OrderService {
cartItems: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
cartItems$ = this.cartItems.asObservable();
// I need to maintain cart, so add items in cart
addCartData(data) {
const currentValue = this.cartItems.value; // get current items in cart
const updatedValue = [...currentValue, data]; // push new item in cart
if(updatedValue.length) {
this.cartItems.next(updatedValue); // notify to all subscribers
}
}
}
Component.ts
export class CartViewComponent implements OnInit {
cartProductList: any = [];
constructor(
private order: OrderService
) { }
ngOnInit() {
this.order.cartItems$.subscribe(items => {
this.cartProductList = items;
});
}
}
Anyone over here who wants his image to fit in full screen without any crop (in both portrait and landscape mode), use this:
image: {
flex: 1,
width: '100%',
height: '100%',
resizeMode: 'contain',
},
Not the best way but If you are using mac or linux even in windows you can set alias for different registries.
##############NPM ALIASES######################
alias npm-default='npm config set registry https://registry.npmjs.org'
alias npm-sinopia='npm config set registry http://localhost:4873/'
You can assign an iterable to side_effect
, and the mock will return the next value in the sequence each time it is called:
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'
Quoting the Mock()
documentation:
If side_effect is an iterable then each call to the mock will return the next value from the iterable.
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#grad1 {
height: 400px;
width: 600px;
background-image: url(t1.jpg);/* Select Image Hare */
}
#gradup {
height: 100%;
width: 100%;
background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */
}
</style>
</head>
<body>
<h1>Fade Image Edge With Radial Gradient</h1>
<div id="grad1"><div id="gradup"></div></div>
</body>
</html>
We just switched our site to bootstrap 3 and we have a bunch of forms...wasn't fun but once you get the hang it's not too bad.
Is this what you are looking for? Demo Here
<div class="form-group">
<label class="control-label col-sm-offset-2 col-sm-2" for="company">Company</label>
<div class="col-sm-6 col-md-4">
<select id="company" class="form-control">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
</div>
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
Hi Guys if u are using angular plugin in eclipse that time is plugin is limited periods after that if u want to used this plugin then u pay it so i suggest to you used webstrome and visual code ide that are very easy and comfort to used so take care if u start and developed a angular app using eclipse
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
You need to add a 640x1136 pixels PNG image ([email protected]
) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).
I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:
enum {
UIDeviceResolution_Unknown = 0,
UIDeviceResolution_iPhoneStandard = 1, // iPhone 1,3,3GS Standard Display (320x480px)
UIDeviceResolution_iPhoneRetina4 = 2, // iPhone 4,4S Retina Display 3.5" (640x960px)
UIDeviceResolution_iPhoneRetina5 = 3, // iPhone 5 Retina Display 4" (640x1136px)
UIDeviceResolution_iPadStandard = 4, // iPad 1,2,mini Standard Display (1024x768px)
UIDeviceResolution_iPadRetina = 5 // iPad 3 Retina Display (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;
@interface UIDevice (Resolutions)
- (UIDeviceResolution)resolution;
NSString *NSStringFromResolution(UIDeviceResolution resolution);
@end
#import "UIDevice+Resolutions.h"
@implementation UIDevice (Resolutions)
- (UIDeviceResolution)resolution
{
UIDeviceResolution resolution = UIDeviceResolution_Unknown;
UIScreen *mainScreen = [UIScreen mainScreen];
CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
if (scale == 2.0f) {
if (pixelHeight == 960.0f)
resolution = UIDeviceResolution_iPhoneRetina4;
else if (pixelHeight == 1136.0f)
resolution = UIDeviceResolution_iPhoneRetina5;
} else if (scale == 1.0f && pixelHeight == 480.0f)
resolution = UIDeviceResolution_iPhoneStandard;
} else {
if (scale == 2.0f && pixelHeight == 2048.0f) {
resolution = UIDeviceResolution_iPadRetina;
} else if (scale == 1.0f && pixelHeight == 1024.0f) {
resolution = UIDeviceResolution_iPadStandard;
}
}
return resolution;
}
@end
This is how you need to use this code.
1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project
2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m
3) Add this code to check what versions of device you are dealing with
int valueDevice = [[UIDevice currentDevice] resolution];
NSLog(@"valueDevice: %d ...", valueDevice);
if (valueDevice == 0)
{
//unknow device - you got me!
}
else if (valueDevice == 1)
{
//standard iphone 3GS and lower
}
else if (valueDevice == 2)
{
//iphone 4 & 4S
}
else if (valueDevice == 3)
{
//iphone 5
}
else if (valueDevice == 4)
{
//ipad 2
}
else if (valueDevice == 5)
{
//ipad 3 - retina display
}
I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.
Add this in your css to hide just the horizontal scroll bar
iframe{
overflow-x:hidden;
}
webView.setDownloadListener(new DownloadListener()
{
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
To make it simple, you can think of it like that;
break
command in the for
loop, the else
part will not be called.break
command in the for
loop, the else
part will be called.In other words, if for loop iteration is not "broken" with break
, the else
part will be called.
It's been 4 months since asking this question, and I still haven't found a good solution.
However, I did find a decent workaround, which I will share in case others have the same issue.
I will try to update this answer, too, if I make further progress.
First of all, my research has shown that there are several possible combinations of user-settings and site settings that cause a variety of PDF display issues. These include:
I spent some time researching PDF display options at pdfobject.com, which is an EXCELLENT resource and I learned a lot.
The workaround I came up with is to embed the PDF file inside an empty HTML page. It is very simple: See some similar examples at pdfobject.com.
<html>
<head>...</head>
<body>
<object data="/pdf/sample.pdf" type="application/pdf" height="100%" width="100%"></object>
</body>
</html>
However, here's a list of caveats:
<object />
tag, ... but ...z-index
to show it ... but ...This is a huge list of caveats. I believe it covers all the bases, but I am definitely not comfortable applying this to EVERY user (most of whom do not have an issue).
Therefore, we decided to ONLY do this embedded
option if the user opts-in for it. On our PDF page, we have a section that says "Having trouble viewing PDFs?", which lets you change your setting to "embedded", and we store that setting in a cookie.
In our GetPDF
Action, we look for the embed=true
cookie. This determines whether we return the PDF file, or if we return a View of HTML with the embedded PDF.
Ugh. This was even less fun than writing IE6-compatible JavaScript.
I hope that others with the same problem can find comfort knowing that they're not alone!
Use .prop instead:
$('#deliveryNext').prop('disabled')
Add the driver class to the bootstrapclasspath. The problem is in java.sql.DriverManager that doesn't see the drivers loaded by ClassLoaders other than bootstrap ClassLoader.
Try the Content-Disposition
header
Content-Disposition: attachment; filename=<file name.ext>
According to the latest W3C HTML5 recommendation (which is likely to be the final HTML5 standard) published today, there is no seamless attribute in the iframe element anymore. It seems to have been removed somewhere in the standardization process.
According to caniuse.com no major browser does support this attribute (anymore), so you probably shouldn't use it.
You can create an ExpandoObject like this:
IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;
And after casting it to dynamic, those values will look like properties:
dynamic d = expando;
Console.WriteLine(d.Name);
However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:
d.GetType().GetProperty("Name")
You can just read from stdin unless the user supply a filename ?
If not, treat the special "filename" -
as meaning "read from stdin". The user would have to start the program like cat file | myprogram -
if he wants to pipe data to it, and myprogam file
if he wants it to read from a file.
int main(int argc,char *argv[] ) {
FILE *input;
if(argc != 2) {
usage();
return 1;
}
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"rb");
//check for errors
}
If you're on *nix, you can check whether stdin is a fifo:
struct stat st_info;
if(fstat(0,&st_info) != 0)
//error
}
if(S_ISFIFO(st_info.st_mode)) {
//stdin is a pipe
}
Though that won't handle the user doing myprogram <file
You can also check if stdin is a terminal/console
if(isatty(0)) {
//stdin is a terminal
}
The most important part is to get the focus working for the list cell. Especially for list on Google TV this is essential:
setItemsCanFocus method of the list view does the trick:
...
mPuzzleList = (ListView) mGameprogressView.findViewById(R.id.gameprogress_puzzlelist);
mPuzzleList.setItemsCanFocus(true);
mPuzzleList.setAdapter(new PuzzleListAdapter(ctx,PuzzleGenerator.getPuzzles(ctx, getResources(), version_lite)));
...
My list cell xml starts like follows:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/puzzleDetailFrame"
android:focusable="true"
android:nextFocusLeft="@+id/gameprogress_lessDetails"
android:nextFocusRight="@+id/gameprogress_reset"
...
nextFocusLeft/Right are also important for D-Pad navigation.
For more details check out the great other answers.
I kind of fail to see the point, for jqGrid you can use the virtual scrolling functionality:
http://www.trirand.net/aspnetmvc/grid/performancevirtualscrolling
but then again, millions of rows with filtering can be done:
http://www.trirand.net/aspnetmvc/grid/performancelinq
I really fail to see the point of "as if there are no pages" though, I mean... there is no way to display 1,000,000 rows at once in the browser - this is 10MB of HTML raw, I kind of fail to see why users would not want to see the pages.
Anyway...
What if - the Bot does not find any form
at all?
3 examples:
<noscript> <p class="error"> ERROR: The form could not be loaded. Please enable JavaScript in your browser to fully enjoy our services. </p> </noscript>
Create a form.html
and place your form
inside a <div id="formContainer">
element.
Inside the page where you need to call that form use an empty <div id="dynamicForm"></div>
and this jQuery: $("#dynamicForm").load("form.html #formContainer");
// THE FORM
var $form = $("<form/>", {
appendTo : $("#formContainer"),
class : "myForm",
submit : AJAXSubmitForm
});
// EMAIL INPUT
$("<input/>",{
name : "Email", // Needed for serialization
placeholder : "Your Email",
appendTo : $form,
on : { // Yes, the jQuery's on() Method
input : function() {
console.log( this.value );
}
}
});
// MESSAGE TEXTAREA
$("<textarea/>",{
name : "Message", // Needed for serialization
placeholder : "Your message",
appendTo : $form
});
// SUBMIT BUTTON
$("<input/>",{
type : "submit",
value : "Send",
name : "submit",
appendTo : $form
});
function AJAXSubmitForm(event) {
event.preventDefault(); // Prevent Default Form Submission
// do AJAX instead:
var serializedData = $(this).serialize();
alert( serializedData );
$.ajax({
url: '/mail.php',
type: "POST",
data: serializedData,
success: function (data) {
// log the data sent back from PHP
console.log( data );
}
});
}
_x000D_
.myForm input,
.myForm textarea{
font: 14px/1 sans-serif;
box-sizing: border-box;
display:block;
width:100%;
padding: 8px;
margin-bottom:12px;
}
.myForm textarea{
resize: vertical;
min-height: 120px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formContainer"></div>
_x000D_
<input type="text" name="email" id="email" placeholder="Your email" autocomplete="nope" tabindex="-1"
They wll be happy to enter some value such as
`[email protected]`
input[name=email]{ /* bait input */ /* do not use display:none or visibility:hidden that will not fool the bot*/ position:absolute; left:-2000px; }
$_POST["email"]
should be empty (without any value)! Otherwise don't submit the form.<input name="sender" type="text" placeholder="Your email">
after (!) the "bot-bait" input for the actual user Email address.Acknowledgments:
Developer.Mozilla - Turning off form autocompletition
StackOverflow - Ignore Tabindex
It's probably easier to create your keys under linux and use PuTTYgen to convert the keys to PuTTY format.
The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.
Updating is quite straightforward:
glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update
Add the following code to the top of your Markdown files to get MathJax rendering support
<style TYPE="text/css">
code.has-jax {font: inherit; font-size: 100%; background: inherit; border: inherit;}
</style>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'] // removed 'code' entry
}
});
MathJax.Hub.Queue(function() {
var all = MathJax.Hub.getAllJax(), i;
for(i = 0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML-full"></script>
and then `$x^2$` or `$$x^2$$` will render as expected :-)
You can always install a local version of MathJax if you don't want to use the online distribution, but you might need to host it through a local webserver.
UPDATE: these days I just use pandoc instead of canonical markdown, but the above is still useful.
Ruby has the concepts of blocks, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a yield
statement.
For example, a simple definition of an each
method on Array
might be something like:
class Array
def each
for i in self
yield(i) # If a block has been passed, control will be passed here.
end
end
end
Then you can invoke this like so:
# Add five to each element.
[1, 2, 3, 4].each{ |e| puts e + 5 }
> [6, 7, 8, 9]
Python has anonymous functions/closures/lambdas, but it doesn't quite have blocks since it's missing some of the useful syntactic sugar. However, there's at least one way to get it in an ad-hoc fashion. See, for example, here.
In your viewDidLoad
:
self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
{
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
You'll need a script to loop through them. Git doesn't a provide a "push all." You could theoretically do a push in multiple threads, but a native method is not available.
Fetch is even more complicated, and I'd recommend doing that linearly.
I think your best answer is to have once machine that everybody does a push / pull to, if that's at all possible.
From what i understand, you can just manage windows using microsoft. hold control and select multiple windows in the taskbar, then right click it and tile whatever way you want. what i've been looking for is a way to actually split a physical monitor into two. so you can run not just windowed prgrams (explorer, firefox, whatever) but full screen programs like games or movies or whatever else you want. this is super useful to fix bugs in full screen programs. im tired of these "windows mangagers" its easier just to click and drag it where you want. and im not OCD about it lining up just right. i just want to split a monitor into two. is that so hard to ask?
You can also do it with JavaScript this way. It will find any iframe elements and remove their borders in IE and other browsers (though you can just set a style of "border : none;" in non-IE browsers instead of using JavaScript). AND it will work even if used AFTER the iframe is generated and in place in the document (e.g. iframes that are added in plain HTML and not JavaScript)!
This appears to work because IE creates the border, not on the iframe element as you'd expect, but on the CONTENT of the iframe--after the iframe is created in the BOM. ($@&*#@!!! IE!!!)
Note: The IE part will only work (of course) if the parent window and iframe are from the SAME origin (same domain, port, protocol etc.). Otherwise the script will get "access denied" errors in the IE error console. If that happens, your only option is to set it before it is generated, as others have noted, or use the non-standard frameBorder="0" attribute. (or just let IE look fugly--my current favorite option ;) )
Took me MANY hours of working to the point of despair to figure this out...
Enjoy. :)
// =========================================================================
// Remove borders on iFrames
if (window.document.getElementsByTagName("iframe"))
{
var iFrameElements = window.document.getElementsByTagName("iframe");
for (var i = 0; i < iFrameElements.length; i++)
{
iFrameElements[i].frameBorder="0"; // For other browsers.
iFrameElements[i].setAttribute("frameBorder", "0"); // For other browsers (just a backup for the above).
iFrameElements[i].contentWindow.document.body.style.border="none"; // For IE.
}
}
Use android:backgroundTint=""
in your EditText
xml layout.
For api<21 you can use AppCompatEditText
from support library thenapp:backgroundTint=""
I use this function for dd/mm/yyyy format :
// (new Date()).fromString("3/9/2013") : 3 of september
// (new Date()).fromString("3/9/2013", false) : 9 of march
Date.prototype.fromString = function(str, ddmmyyyy) {
var m = str.match(/(\d+)(-|\/)(\d+)(?:-|\/)(?:(\d+)\s+(\d+):(\d+)(?::(\d+))?(?:\.(\d+))?)?/);
if(m[2] == "/"){
if(ddmmyyyy === false)
return new Date(+m[4], +m[1] - 1, +m[3], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
return new Date(+m[4], +m[3] - 1, +m[1], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}
return new Date(+m[1], +m[3] - 1, +m[4], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}
UPDATE ed
SET ed.kWh = ted.kWh
FROM energydata ed
INNER JOIN temp_energydata ted ON ted.webmeterID = ed.webmeterID
You can also convert to datetime
without string concatenation, by combining datetime
and timedelta
objects. Combined with pd.DataFrame.pop
, you can remove the source series simultaneously:
df['DateTime'] = pd.to_datetime(df.pop('Date')) + pd.to_timedelta(df.pop('Time'))
print(df)
DateTime
0 2013-01-06 23:00:00
1 2013-02-06 01:00:00
2 2013-02-06 21:00:00
3 2013-02-06 22:00:00
4 2013-02-06 23:00:00
5 2013-03-06 01:00:00
6 2013-03-06 21:00:00
7 2013-03-06 22:00:00
8 2013-03-06 23:00:00
9 2013-04-06 01:00:00
print(df.dtypes)
DateTime datetime64[ns]
dtype: object
Python 3.8 added functools.singledispatchmethod
Transform a method into a single-dispatch generic function.
To define a generic method, decorate it with the @singledispatchmethod decorator. Note that the dispatch happens on the type of the first non-self or non-cls argument, create your function accordingly:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
def neg(self, arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(self, arg: int):
return -arg
@neg.register
def _(self, arg: bool):
return not arg
negator = Negator()
for v in [42, True, "Overloading"]:
neg = negator.neg(v)
print(f"{v=}, {neg=}")
Output
v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
@singledispatchmethod supports nesting with other decorators such as @classmethod. Note that to allow for dispatcher.register, singledispatchmethod must be the outer most decorator. Here is the Negator class with the neg methods being class bound:
from functools import singledispatchmethod
class Negator:
@singledispatchmethod
@staticmethod
def neg(arg):
raise NotImplementedError("Cannot negate a")
@neg.register
def _(arg: int) -> int:
return -arg
@neg.register
def _(arg: bool) -> bool:
return not arg
for v in [42, True, "Overloading"]:
neg = Negator.neg(v)
print(f"{v=}, {neg=}")
Output:
v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
The same pattern can be used for other similar decorators: staticmethod, abstractmethod, and others.
You can use the forEach
method to execute a provided function once for each element in the array. In this provided function you can add the Active
property to the element.
Results.forEach(function (element) {
element.Active = "false";
});
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.
If interested to serialize you can use:
json.dumps -> serialize
json.loads -> deserialize
If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)
String to Set
set('abca')
Set to String
''.join(some_var_set)
example:
def test():
some_var_set=set('abca')
print("here is the set:",some_var_set,type(some_var_set))
some_var_string=''.join(some_var_set)
print("here is the string:",some_var_string,type(some_var_string))
test()
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
I think you need quotes around your {$row['null_field']}
, so '{$row['null_field']}'
If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',)
which is a syntax error.
If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..
You could try a for loop
for func,args,kwargs in zip([a,b,c,d],
[args_a,args_b,args_c,args_d],
[kw_a,kw_b,kw_c,kw_d]):
try:
func(*args, **kwargs)
break
except:
pass
This way you can loop as many functions as you want without making the code look ugly
This can be done by using a pointer, and allocating memory on the heap using malloc
.
Note that there is no way to later ask how big that memory block is. You have to keep track of the array size yourself.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
/* declare a pointer do an integer */
int *data;
/* we also have to keep track of how big our array is - I use 50 as an example*/
const int datacount = 50;
data = malloc(sizeof(int) * datacount); /* allocate memory for 50 int's */
if (!data) { /* If data == 0 after the call to malloc, allocation failed for some reason */
perror("Error allocating memory");
abort();
}
/* at this point, we know that data points to a valid block of memory.
Remember, however, that this memory is not initialized in any way -- it contains garbage.
Let's start by clearing it. */
memset(data, 0, sizeof(int)*datacount);
/* now our array contains all zeroes. */
data[0] = 1;
data[2] = 15;
data[49] = 66; /* the last element in our array, since we start counting from 0 */
/* Loop through the array, printing out the values (mostly zeroes, but even so) */
for(int i = 0; i < datacount; ++i) {
printf("Element %d: %d\n", i, data[i]);
}
}
That's it. What follows is a more involved explanation of why this works :)
I don't know how well you know C pointers, but array access in C (like array[2]
) is actually a shorthand for accessing memory via a pointer. To access the memory pointed to by data
, you write *data
. This is known as dereferencing the pointer. Since data
is of type int *
, then *data
is of type int
. Now to an important piece of information: (data + 2)
means "add the byte size of 2 ints to the adress pointed to by data
".
An array in C is just a sequence of values in adjacent memory. array[1]
is just next to array[0]
. So when we allocate a big block of memory and want to use it as an array, we need an easy way of getting the direct adress to every element inside. Luckily, C lets us use the array notation on pointers as well. data[0]
means the same thing as *(data+0)
, namely "access the memory pointed to by data
". data[2]
means *(data+2)
, and accesses the third int
in the memory block.
Use summarise
in the dplyr
package:
library(dplyr)
summarise(df, Average = mean(col_name, na.rm = T))
note: dplyr
supports both summarise
and summarize
.
case when isdate(inputdate) = 1
then convert(datetime, cast(inputdate,datetime2), 103)
else
case when isdate(inputdate) = 0
then convert(datetime, cast(inputdate,datetime2), 103)
The default port of Postgres is commonly configured in:
sudo vi /<path to your installation>/data/postgresql.conf
On Ubuntu this might be:
sudo vi /<path to your installation>/main/postgresql.conf
Search for port
in this file.
The way I think about it is that you use flatMap
when the function you wanted to put inside of map()
returns an Observable
. In which case you might still try to use map()
but it would be unpractical. Let me try to explain why.
If in such case you decided to stick with map
, you would get an Observable<Observable<Something>>
. For example in your case, if we used an imaginary RxGson library, that returned an Observable<String>
from it's toJson()
method (instead of simply returning a String
) it would look like this:
Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
@Override public Observable<String>> call(File file) {
return new RxGson().toJson(new FileReader(file), Object.class);
}
}); // you get Observable<Observable<String>> here
At this point it would be pretty tricky to subscribe()
to such an observable. Inside of it you would get an Observable<String>
to which you would again need to subscribe()
to get the value. Which is not practical or nice to look at.
So to make it useful one idea is to "flatten" this observable of observables (you might start to see where the name _flat_Map comes from). RxJava provides a few ways to flatten observables and for sake of simplicity lets assume merge is what we want. Merge basically takes a bunch of observables and emits whenever any of them emits. (Lots of people would argue switch would be a better default. But if you're emitting just one value, it doesn't matter anyway.)
So amending our previous snippet we would get:
Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
@Override public Observable<String>> call(File file) {
return new RxGson().toJson(new FileReader(file), Object.class);
}
}).merge(); // you get Observable<String> here
This is a lot more useful, because subscribing to that (or mapping, or filtering, or...) you just get the String
value. (Also, mind you, such variant of merge()
does not exist in RxJava, but if you understand the idea of merge then I hope you also understand how that would work.)
So basically because such merge()
should probably only ever be useful when it succeeds a map()
returning an observable and so you don't have to type this over and over again, flatMap()
was created as a shorthand. It applies the mapping function just as a normal map()
would, but later instead of emitting the returned values it also "flattens" (or merges) them.
That's the general use case. It is most useful in a codebase that uses Rx allover the place and you've got many methods returning observables, which you want to chain with other methods returning observables.
In your use case it happens to be useful as well, because map()
can only transform one value emitted in onNext()
into another value emitted in onNext()
. But it cannot transform it into multiple values, no value at all or an error. And as akarnokd wrote in his answer (and mind you he's much smarter than me, probably in general, but at least when it comes to RxJava) you shouldn't throw exceptions from your map()
. So instead you can use flatMap()
and
return Observable.just(value);
when all goes well, but
return Observable.error(exception);
when something fails.
See his answer for a complete snippet: https://stackoverflow.com/a/30330772/1402641
What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?
And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.
I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.
With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:
$factors = array();
for($i = 0; $i < $target; $i++){
if($target % $i == 0){
$temp = array()
$a = $i;
$b = $target / $i;
$temp["a"] = $a;
$temp["b"] = $b;
$temp["index"] = $i;
array_push($factors, $temp);
}
}
This would leave you with an array of factors of the target number.
If you programatically set the tableHeaderView
, then just set it inside viewDidLayoutSubviews
.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setupTableViewHeader()
}
private func setupTableViewHeader() {
// Something you do to set it up programatically...
tableView.tableHeaderView = MyHeaderView.instanceFromNib()
}
If you didn't set it programatically, you need to do similar to what @Kris answered based on this link
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
sizeHeaderToFit()
}
private func sizeHeaderToFit() {
if let headerView = tableView.tableHeaderView {
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableView.tableHeaderView = headerView
}
}
View > Quick Switch Scheme > Keymap > Eclipse
use this option for eclipse keymap or if u want to go with AndroidStudio keymap then follow below link
Click here for Official Android Studio Keymap Refference guide
you may find default keymap referrence in
AndroidStudio --> Help-->Default keymap refrence
In general, this is probably not a great idea, since your html file should only be loading JS files that they actually make use of. Regardless, this would be trivial to do with any server-side scripting language. Just insert the script tags before serving the pages to the client.
If you want to do it without using server-side scripting, you could drop your JS files into a directory that allows listing the directory contents, and then use XMLHttpRequest to read the contents of the directory, and parse out the file names and load them.
Option #3 is to have a "loader" JS file that uses getScript() to load all of the other files. Put that in a script tag in all of your html files, and then you just need to update the loader file whenever you upload a new script.
I know it's late but hope it will help someone else...
This is my code: It takes two by two hex representations contained in String and add those into byte array. It works perfectly for me.
public byte[] stringToByteArray (String s) {
byte[] byteArray = new byte[s.length()/2];
String[] strBytes = new String[s.length()/2];
int k = 0;
for (int i = 0; i < s.length(); i=i+2) {
int j = i+2;
strBytes[k] = s.substring(i,j);
byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
k++;
}
return byteArray;
}
My tested version
Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)
Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)
End Sub
This code work for me:
fetch('http://localhost:8080')
.then(response => response.json())
.then(json => {
this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
})
Based on the warning message, the component ReactTooltip renders an HTML that might look like this:
<p>
<div>...</div>
</p>
According to this document, a <p></p>
tag can only contain inline elements. That means putting a <div></div>
tag inside it should be improper, since the div
tag is a block element. Improper nesting might cause glitches like rendering extra tags, which can affect your javascript and css.
If you want to get rid of this warning, you might want to customize the ReactTooltip component, or wait for the creator to fix this warning.
Tested in JSFiddle and does what you're asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked.
Updated Answer:
$(document).ready(function() {
//set initial state.
$('#textbox1').val(this.checked);
$('#checkbox1').change(function() {
if(this.checked) {
var returnVal = confirm("Are you sure?");
$(this).prop("checked", returnVal);
}
$('#textbox1').val(this.checked);
});
});
Original Answer:
$(document).ready(function() {
//set initial state.
$('#textbox1').val($(this).is(':checked'));
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
var returnVal = confirm("Are you sure?");
$(this).attr("checked", returnVal);
}
$('#textbox1').val($(this).is(':checked'));
});
});
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
fline=open("myfile").readline().rstrip()
you can intersect types:
type TypeA = {
nameA: string;
};
type TypeB = {
nameB: string;
};
export type TypeC = TypeA & TypeB;
somewhere in you code you can now do:
const some: TypeC = {
nameB: 'B',
nameA: 'A',
};
ViewGroup class provides API for child views management in run-time, allowing to add/remove views as well.
Some other links on the subject:
Android, add new view without XML Layout
Android Runtime Layout Tutorial
http://developer.android.com/reference/android/view/View.html
http://developer.android.com/reference/android/widget/LinearLayout.html
You can use reduce
>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'
Here is the method that I finally came up with after struggling:
Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*
To make the output cleaner (only path), use:
(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname
To get only the first result, use:
(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname | Select -First 1
Now for the important stuff:
To search only for files/directories do not use -File
or -Directory
(see below why). Instead use this for files:
Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
and remove the -eq $false
for directories. Do not leave a trailing wildcard like bin/*
.
Why not use the built in switches? They are terrible and remove features randomly. For example, in order to use -Include
with a file, you must end the path with a wildcard. However, this disables the -Recurse
switch without telling you:
Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib
You'd think that would give you all *.lib
s in all subdirectories, but it only will search top level of bin
.
In order to search for directories, you can use -Directory
, but then you must remove the trailing wildcard. For whatever reason, this will not deactivate -Recurse
. It is for these reasons that I recommend not using the builtin flags.
You can shorten this command considerably:
Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
becomes
gci './path*/' -s -Include 'name*' | where {$_.PSIsContainer -eq $false}
Get-ChildItem
is aliased to gci
-Path
is default to position 0, so you can just make first argument path-Recurse
is aliased to -s
-Include
does not have a shorthandIf you're using ES6 or higher, the cleanest way is to construct an array of the items and use Array.includes
:
['a', 'b', 'c'].includes('b')
This has some inherent benefits over indexOf
because it can properly test for the presence of NaN
in the list, and can match missing array elements such as the middle one in [1, , 2]
to undefined
. includes
also works on JavaScript typed arrays such as Uint8Array
.
If you're concerned about browser support (such as for IE or Edge), you can check Array.includes
at CanIUse.Com, and if you want to target a browser or browser version that's missing includes
, I recommend polyfill.io for polyfilling.
You could add a new isInList
property to strings as follows:
if (!String.prototype.isInList) {
Object.defineProperty(String.prototype, 'isInList', {
get: () => function(...args) {
let value = this.valueOf();
for (let i = 0, l = args.length; i < l; i += 1) {
if (arguments[i] === value) return true;
}
return false;
}
});
}
Then use it like so:
'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false
You can do the same thing for Number.prototype
.
Note that Object.defineProperty
cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... }
because using simple assignment like that will create an enumerable property on String.prototype
, which is more likely to break code.
If you are using a modern browser, indexOf
always works. However, for IE8 and earlier you'll need a polyfill.
If indexOf
returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN
, and while it can match an explicit undefined
, it can’t match a missing element to undefined
as in the array [1, , 2]
.
indexOf
or includes
in IE, or any other browser/version lacking supportIf you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf
.
In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf()
function that is not standards-compliant:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item) {
var i = this.length;
while (i--) {
if (this[i] === item) return i;
}
return -1;
}
}
However, I don't think modifying Array.prototype
is the best answer in the long term. Modifying Object
and Array
prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in
will return the new function name as one of the keys:
Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!
Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.
The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x))
and only then work with that x
.
The new ES6 ways to avoid this extra-key problem are:
Use of
instead of in
, for (let x of arr)
. However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes
as stated above.
Define your new properties on the prototype using Object.defineProperty()
, as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this.
I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.
On Centos 7.8 and PHP 7.3
yum install php-soap
service httpd restart
It will only push the new commits. It won't push the whole "master" branch. That is part of the benefit of working with a Distributed Version Control System. Git figures out what is actually needed and only pushes those pieces. If the branch you are on has been changed and pushed by someone else you'll need to pull first. Then push your commits.
To get the file extension, I would do this:
var ext = file.split('.').pop();
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
Look at the Doctrine API source-code :
class EntityRepository{
...
public function findAll(){
return $this->findBy(array());
}
...
}
<div class="d-flex justify-content-center align-items-center container ">
<div class="row ">
<form action="">
<div class="form-group">
<label for="inputUserName" class="control-label">Enter UserName</label>
<input type="email" class="form-control" id="inputUserName" aria-labelledby="emailnotification">
<small id="emailnotification" class="form-text text-muted">Enter Valid Email Id</small>
</div>
<div class="form-group">
<label for="inputPassword" class="control-label">Enter Password</label>
<input type="password" class="form-control" id="inputPassword" aria-labelledby="passwordnotification">
</div>
</form>
</div>
</div>
I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:
\includegraphics[height=60mm, width=100mm]{number2.png}
works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.
Incidentally, you can change this in TexShop from the "Typeset" menu.
Hope this helps.
Strongly simplified version of max
:
def max(items, key=lambda x: x):
current = item[0]
for item in items:
if key(item) > key(current):
current = item
return current
Regarding lambda:
>>> ident = lambda x: x
>>> ident(3)
3
>>> ident(5)
5
>>> times_two = lambda x: 2*x
>>> times_two(2)
4
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
the following code is for making the same y axis limit on two subplots
f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})
df.plot(ax = ax[0], linewidth = 2.5)
ylim = [lower_limit,upper_limit]
ax[0].set_ylim(ylim)
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1)
ax[1].set_ylim(ylim)
just a reminder, plt.hist(range=[low, high])
the histogram auto crops the range if the specified range is larger than the max&min of the data points. So if you want to specify the y-axis range number, i prefer to use set_ylim
I've also experienced such issues as R.java
being missing, and also eclipse complaining there are errors in my code (displaying red X icon against class files) when there were no errors.
The only method I've found for solving this is to clean the project by selecting Project > Clean
This seems to solve the issue for myself, running Eclipse 3.5.2
Swift 2 :
this is what is did to do every thing !
close keyboard with Done
button or Touch outSide
,Next
for go to next input.
First Change TextFiled Return Key
To Next
in StoryBoard.
override func viewDidLoad() {
txtBillIdentifier.delegate = self
txtBillIdentifier.tag = 1
txtPayIdentifier.delegate = self
txtPayIdentifier.tag = 2
let tap = UITapGestureRecognizer(target: self, action: "onTouchGesture")
self.view.addGestureRecognizer(tap)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if(textField.returnKeyType == UIReturnKeyType.Default) {
if let next = textField.superview?.viewWithTag(textField.tag+1) as? UITextField {
next.becomeFirstResponder()
return false
}
}
textField.resignFirstResponder()
return false
}
func onTouchGesture(){
self.view.endEditing(true)
}
This is useful:
sudo passwd root
for anyone who's been caught out by the need to set a root password in vagrant first
You can use git reflog to find the SHA1 of the last commit of the branch. From that point, you can recreate a branch using
git branch branchName <sha1>
Edit: As @seagullJS says, the branch -D
command tells you the sha1, so if you haven't closed the terminal yet it becomes real easy. For example this deletes and then immediately restores a branch named master2
:
user@MY-PC /C/MyRepo (master)
$ git branch -D master2
Deleted branch master2 (was 130d7ba). <-- This is the SHA1 we need to restore it!
user@MY-PC /C/MyRepo (master)
$ git branch master2 130d7ba
It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe
. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.
I ended up creating the ODBC connection directly under HKLM\Software\ODBC
. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.
After creating the entry (by hand), I fired up my windows service and everything was happy.
Colspan:
<table>
<tr>
<td> Row 1 Col 1</td>
<td> Row 1 Col 2</td>
</tr>
<tr>
<td colspan=2> Row 2 Long Col</td>
</tr>
</table>
Internet Explorer (IE8 and lower) doesn't support addEventListener(...)
. It has its own event model using the attachEvent
method. You could use some code like this:
var element = document.getElementById('container');
if (document.addEventListener){
element .addEventListener('copy', beforeCopy, false);
} else if (el.attachEvent){
element .attachEvent('oncopy', beforeCopy);
}
Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.
By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.
Use DateTime::createFromFormat
$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();
brew reinstall php56-mcrypt --build-from-source
Do this—pass the --build-from-source
flag—for each module which needs to be compiled with the same version.
It may also require PHP options depending on your plugins. If so, brew reinstall php56 --with-thread-safety
To see all of the options for php[version] run brew options php56
(replacing 56 with your version)
Regular expressions are built to parse. While the syntax can take a while to pick up on this approach is very efficient, and is very flexible for handling more complex string extractions/replacements
Sub Tester()
MsgBox CleanString("3d1fgd4g1dg5d9gdg")
End Sub
Function CleanString(strIn As String) As String
Dim objRegex
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "[^\d]+"
CleanString = .Replace(strIn, vbNullString)
End With
End Function
Update 2013-01-07: If you want to see a good mix of component-based game engine with the (in my opinion) superior approach of reactive programming take a look at the V-Play engine. It very well integrates QTs QML property binding functionality.
We did some research on CBSE in games at our university and I collected some material over the years:
CBSE in games literature:
A very good and clean example of a component-based game-engine in C# is the Elephant game framework.
If you really want to know what components are read: Component-based Software Engineering! They define a component as:
A software component is a software element that conforms to a component model and can be independently deployed and composed without modification according to a composition standard.
A component model defines specific interaction and composition standards. A component model implementation is the dedicated set of executable software elements required to support the execution of components that conform to the model.
A software component infrastructure is a set of interacting software components designed to ensure that a software system or subsystem constructed using those components and interfaces will satisfy clearly defined performance specifications.
My opinions after 2 years of experience with CBSE in games thought are that object-oriented programming is simply a dead-end. Remember my warning as you watch your components become smaller and smaller, and more like functions packed in components with a lot of useless overhead. Use functional-reactive programming instead. Also take a look at my fresh blog post (which lead me to this question while writing it :)) about Why I switched from component-based game engine architecture to FRP.
CBSE in games papers:
CBSE in games web-links (sorted by relevancy):
Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.
Here's what worked for me:
import java.lang.System.getProperty;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
frame = JFrame("Test")
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png')
frame.setIconImage(icon.getImage());
frame.setVisible(True)
Anytime you're tempted to pass a collection (or pointer or reference to one) to a function, ask yourself whether you couldn't pass a couple of iterators instead. Chances are that by doing so, you'll make your function more versatile (e.g., make it trivial to work with data in another type of container when/if needed).
In this case, of course, there's not much point since the standard library already has perfectly good binary searching, but when/if you write something that's not already there, being able to use it on different types of containers is often quite handy.
In your comment on @Kenneth's answer you're saying that ReadAsStringAsync()
is returning empty string.
That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.
What you can do is this:
public static string GetRequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
When I added module: 'jsr305'
as an additional exclude statement, it all worked out fine for me.
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude module: 'jsr305'
})
Inspired by Radek and Spencer... On Rails 4(.0.2 - Ruby 2.1.0 ), I was able to append this to config/boot.rb:
# config/boot.rb
# ...existing code
require 'rails/commands/server'
module Rails
# Override default development
# Server port
class Server
def default_options
super.merge(Port: 3100)
end
end
end
All other configuration in default_options are still set, and command-line switches still override defaults.
Try this one from Codeproject (credit to Nitron):
I think it's the same dialog you're talking about - maybe it would help if you add a screenshot?
bool GetFolder(std::string& folderpath, const char* szCaption=NULL, HWND hOwner=NULL)
{
bool retVal = false;
// The BROWSEINFO struct tells the shell how it should display the dialog.
BROWSEINFO bi;
memset(&bi, 0, sizeof(bi));
bi.ulFlags = BIF_USENEWUI;
bi.hwndOwner = hOwner;
bi.lpszTitle = szCaption;
// must call this if using BIF_USENEWUI
::OleInitialize(NULL);
// Show the dialog and get the itemIDList for the selected folder.
LPITEMIDLIST pIDL = ::SHBrowseForFolder(&bi);
if(pIDL != NULL)
{
// Create a buffer to store the path, then get the path.
char buffer[_MAX_PATH] = {'\0'};
if(::SHGetPathFromIDList(pIDL, buffer) != 0)
{
// Set the string value.
folderpath = buffer;
retVal = true;
}
// free the item id list
CoTaskMemFree(pIDL);
}
::OleUninitialize();
return retVal;
}
For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration
has a make_svn_version_py()
method that embeds the revision number inside package.__svn_version__
in the variable version
.
Make an jInternalFrame into main frame and make it invisible. Then you can use it for further events.
jInternalFrame.setSize(300,150);
jInternalFrame.setVisible(true);
Use as follows
[profilename]
region=us-east-1
output=text
Example cmd
aws --profile myname CMD opts
Your case: HTTP 400
is the right status code for your case from REST perspective as its syntactically incorrect to send sales_tax
instead of tax
, though its a valid JSON. This is normally enforced by most of the server side frameworks when mapping the JSON to objects. However, there are some REST implementations that ignore new key
in JSON object. In that case, a custom content-type
specification to accept only valid fields can be enforced by server-side.
Ideal Scenario for 422:
In an ideal world, 422 is preferred and generally acceptable to send as response if the server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the data because its semantically erroneous.
Situations of 400 over 422:
Remember, the response code 422 is an extended HTTP (WebDAV) status code. There are still some HTTP clients / front-end libraries that aren't prepared to handle 422. For them, its as simple as "HTTP 422 is wrong, because it's not HTTP". From the service perspective, 400 isn't quite specific.
In enterprise architecture, the services are deployed mostly on service layers like SOA, IDM, etc. They typically serve multiple clients ranging from a very old native client to a latest HTTP clients. If one of the clients doesn't handle HTTP 422, the options are that asking the client to upgrade or change your response code to HTTP 400 for everyone. In my experience, this is very rare these days but still a possibility. So, a careful study of your architecture is always required before deciding on the HTTP response codes.
To handle situation like these, the service layers normally use versioning
or setup configuration
flag for strict HTTP conformance clients to send 400, and send 422 for the rest of them. That way they provide backwards compatibility support for existing consumers but at the same time provide the ability for the new clients to consume HTTP 422.
The latest update to RFC7321 says:
The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).
This confirms that servers can send HTTP 400 for invalid request. 400 doesn't refer only to syntax error anymore, however, 422 is still a genuine response provided the clients can handle it.
I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:
1) just need to reset the workspace file status
2) select all unstage files (command +a), right click and select remove
It's that simple :D
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to
Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
Please use udid.io in your device browser Or Please install iTools and conncet the device to get the correct UDID.
Adarsh E M
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());
It is undefined behaviour to attempt to modify string literals, which is what something like:
strcat ("Hello, ", name);
will attempt to do. It will try to tack on the name
string to the end of the string literal "Hello, "
, which is not well defined.
Try something this. It achieves what you appear to be trying to do:
char message[1000];
strcpy (message, "TEXT ");
strcat (message, var);
This creates a buffer area that is allowed to be modified and then copies both the string literal and other text to it. Just be careful with buffer overflows. If you control the input data (or check it before-hand), it's fine to use fixed length buffers like I have.
Otherwise, you should use mitigation strategies such as allocating enough memory from the heap to ensure you can handle it. In other words, something like:
const static char TEXT[] = "TEXT ";
// Make *sure* you have enough space.
char *message = malloc (sizeof(TEXT) + strlen(var) + 1);
if (message == NULL)
handleOutOfMemoryIntelligently();
strcpy (message, TEXT);
strcat (message, var);
// Need to free message at some point after you're done with it.
Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.
import numpy as np
import matplotlib.pyplot as plt
def set_shared_ylabel(a, ylabel, labelpad = 0.01):
"""Set a y label shared by multiple axes
Parameters
----------
a: list of axes
ylabel: string
labelpad: float
Sets the padding between ticklabels and axis label"""
f = a[0].get_figure()
f.canvas.draw() #sets f.canvas.renderer needed below
# get the center position for all plots
top = a[0].get_position().y1
bottom = a[-1].get_position().y0
# get the coordinates of the left side of the tick labels
x0 = 1
for at in a:
at.set_ylabel('') # just to make sure we don't and up with multiple labels
bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
bboxes = bboxes.inverse_transformed(f.transFigure)
xt = bboxes.x0
if xt < x0:
x0 = xt
tick_label_left = x0
# set position of label
a[-1].set_ylabel(ylabel)
a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)
length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)
f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')
You can use this function if you want to add the data into database, with a button. I hope it will help.
// dgvBill is name of DataGridView
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnectingString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dgvBill.Rows.Count; i++)
{
StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price, total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message , "Error !");
}
you are looking for this:
a:visited{
color:blue;
}
Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)
Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)
a:link{
color:blue;
}
a:visited{
color:purple;
}
a:hover{
color:orange;
}
a:focus{
color:green;
}
a:active{
color:red;
}
If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)
If you have different types of links that you want to all have the same color when clicked, add a class to the links.
a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
color:orange;
}
It should be noted that not all browsers respect each of these options ;-)
Use File.mkdirs()
:
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
I didn't need to set up remote debugging in order to get this working, I used Maven.
spring-boot::run
.NB. If your IDE has problems finding your project's source code when doing line-by-line debugging, take a look at this SO answer to find out how to manually attach your source code to the debug application.
Hope this helps someone!
Following is an adaptation of @wisbucky's answer for Windows users:
for /f "tokens=1" %i in ('git branch -vv ^| findstr ": gone]"') DO git branch %i -d
I use posh-git and unfortunately PS doesn't like the naked for
, so I created a plain 'ol command script named PruneOrphanBranches.cmd:
@ECHO OFF
for /f "tokens=1" %%i in ('git branch -vv ^| findstr ": gone]"') DO CALL :ProcessBranch %%i %1
GOTO :EOF
:ProcessBranch
IF /I "%2%"=="-d" (
git branch %1 %2
) ELSE (
CALL :OutputMessage %1
)
GOTO :EOF
:OutputMessage
ECHO Will delete branch [%1]
GOTO :EOF
:EOF
Call it with no parameters to see a list, and then call it with "-d" to perform the actual deletion or "-D" for any branches that are not fully merged but which you want to delete anyway.
psql
's inline help:
\h ALTER TABLE
Also documented in the postgres docs (an excellent resource, plus easy to read, too).
ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);
The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as
If NOT (value1 = value2)
which just makes the use of the NOT keyword pointless.
I become frustrated trying to implement something that looked consistent in all browsers and went with an svg button which can be styled with css.
html
<svg>
<circle cx="12" cy="12" r="11" stroke="black" stroke-width="2" fill="white" />
<path stroke="black" stroke-width="4" fill="none" d="M6.25,6.25,17.75,17.75" />
<path stroke="black" stroke-width="4" fill="none" d="M6.25,17.75,17.75,6.25" />
</svg>
css
svg {
cursor: pointer;
height: 24px;
width: 24px;
}
svg > circle {
stroke: black;
fill: white;
}
svg > path {
stroke: black;
}
svg:hover > circle {
fill: red;
}
svg:hover > path {
stroke: white;
}
Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.
Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable
Or simply use
ng-show="v.hasOwnProperty('secId')"
See updated solution here:
After installation you need to connect to Server Name : localhost to start using the local instance of SQL Server.
Once you are connected to the local instance, right click on Databases and create a new database.
If you want to send exactly post request with verify=False option, fastest way is to use this code:
import requests
requests.api.request('post', url, data={'bar':'baz'}, json=None, verify=False)
Some tab completions to show the contents of the packages in Python 2 vs Python 3.
In Python 2:
In [1]: import urllib
In [2]: urllib.
urllib.ContentTooShortError urllib.ftpwrapper urllib.socket urllib.test1
urllib.FancyURLopener urllib.getproxies urllib.splitattr urllib.thishost
urllib.MAXFTPCACHE urllib.getproxies_environment urllib.splithost urllib.time
urllib.URLopener urllib.i urllib.splitnport urllib.toBytes
urllib.addbase urllib.localhost urllib.splitpasswd urllib.unquote
urllib.addclosehook urllib.noheaders urllib.splitport urllib.unquote_plus
urllib.addinfo urllib.os urllib.splitquery urllib.unwrap
urllib.addinfourl urllib.pathname2url urllib.splittag urllib.url2pathname
urllib.always_safe urllib.proxy_bypass urllib.splittype urllib.urlcleanup
urllib.base64 urllib.proxy_bypass_environment urllib.splituser urllib.urlencode
urllib.basejoin urllib.quote urllib.splitvalue urllib.urlopen
urllib.c urllib.quote_plus urllib.ssl urllib.urlretrieve
urllib.ftpcache urllib.re urllib.string
urllib.ftperrors urllib.reporthook urllib.sys
In Python 3:
In [2]: import urllib.
urllib.error urllib.parse urllib.request urllib.response urllib.robotparser
In [2]: import urllib.error.
urllib.error.ContentTooShortError urllib.error.HTTPError urllib.error.URLError
In [2]: import urllib.parse.
urllib.parse.parse_qs urllib.parse.quote_plus urllib.parse.urldefrag urllib.parse.urlsplit
urllib.parse.parse_qsl urllib.parse.unquote urllib.parse.urlencode urllib.parse.urlunparse
urllib.parse.quote urllib.parse.unquote_plus urllib.parse.urljoin urllib.parse.urlunsplit
urllib.parse.quote_from_bytes urllib.parse.unquote_to_bytes urllib.parse.urlparse
In [2]: import urllib.request.
urllib.request.AbstractBasicAuthHandler urllib.request.HTTPSHandler
urllib.request.AbstractDigestAuthHandler urllib.request.OpenerDirector
urllib.request.BaseHandler urllib.request.ProxyBasicAuthHandler
urllib.request.CacheFTPHandler urllib.request.ProxyDigestAuthHandler
urllib.request.DataHandler urllib.request.ProxyHandler
urllib.request.FTPHandler urllib.request.Request
urllib.request.FancyURLopener urllib.request.URLopener
urllib.request.FileHandler urllib.request.UnknownHandler
urllib.request.HTTPBasicAuthHandler urllib.request.build_opener
urllib.request.HTTPCookieProcessor urllib.request.getproxies
urllib.request.HTTPDefaultErrorHandler urllib.request.install_opener
urllib.request.HTTPDigestAuthHandler urllib.request.pathname2url
urllib.request.HTTPErrorProcessor urllib.request.url2pathname
urllib.request.HTTPHandler urllib.request.urlcleanup
urllib.request.HTTPPasswordMgr urllib.request.urlopen
urllib.request.HTTPPasswordMgrWithDefaultRealm urllib.request.urlretrieve
urllib.request.HTTPRedirectHandler
In [2]: import urllib.response.
urllib.response.addbase urllib.response.addclosehook urllib.response.addinfo urllib.response.addinfourl
#!/bin/bash
num=0
metab=0
for ((i=1; i<=2; i++)); do
for j in `ls output-$i-*`; do
echo "$j"
metab=$(cat $j|grep EndBuffer|awk '{sum+=$2} END { print sum/120}') (line15)
let num=num+metab (line 16)
done
echo "$num"
done
I had the same problem even use
<uses-permission android:name="android.permission.INTERNET" />
If you want connect web api using http
not https
. Maybe you use android device using Android 9 (Pie) or API level 28 or higher . android:usesCleartextTraffic
default value is false
. You have to set be
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true" <!-- this line -->
...>
...
</application>
</manifest>
Finally, should be https
https://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic
@adeneo answer works for Firefox and chrome... For IE the below can be used.
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'FileName.csv');_x000D_
}
_x000D_
http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword says:
Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.
This is relevant if some http/https requests don't go through the proxy (which is quite possible depending on configuration). In that case, you would send your credentials directly to some http server, not to your proxy.
He suggests the following fix.
// Java ignores http.proxyUser. Here come's the workaround.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
String prot = getRequestingProtocol().toLowerCase();
String host = System.getProperty(prot + ".proxyHost", "");
String port = System.getProperty(prot + ".proxyPort", "80");
String user = System.getProperty(prot + ".proxyUser", "");
String password = System.getProperty(prot + ".proxyPassword", "");
if (getRequestingHost().equalsIgnoreCase(host)) {
if (Integer.parseInt(port) == getRequestingPort()) {
// Seems to be OK.
return new PasswordAuthentication(user, password.toCharArray());
}
}
}
return null;
}
});
I haven't tried it yet, but it looks good to me.
I modified the original version slightly to use equalsIgnoreCase() instead of equals(host.toLowerCase()) because of this: http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug and I added "80" as the default value for port to avoid NumberFormatException in Integer.parseInt(port).
Here is the limit of most popular web server
A more elegant solution
echo "Enter the file name"
read x
if [ -f $x ]
then
echo "This is a regular file"
else
echo "This is a directory"
fi
Inspired by Martijn Pieters' response.
In case you only need to delete the header from the csv
file, you can work more efficiently if you write using the standard Python file I/O library, avoiding writing with the CSV Python library:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
next(infile) # skip the headers
outfile.write(infile.read())
Not directly relevant, but often it's required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I've read this post and did not find the solution, so I am posting my own here for the sake of completeness.
def get_domain_suffixes():
import requests
res=requests.get('https://publicsuffix.org/list/public_suffix_list.dat')
lst=set()
for line in res.text.split('\n'):
if not line.startswith('//'):
domains=line.split('.')
cand=domains[-1]
if cand:
lst.add('.'+cand)
return tuple(sorted(lst))
domain_suffixes=get_domain_suffixes()
def reminds_url(txt:str):
"""
>>> reminds_url('yandex.ru.com/somepath')
True
"""
ltext=txt.lower().split('/')[0]
return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)
Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.
I know this is an old thread, but hope it helps some one.
public static void SetRequest(string mXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Decide your encoding here
//webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentType = "text/xml; charset=utf-8";
// You should setContentLength
byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var res = await httpRequest(webRequest);
}
split_part()
does what you want in one step:
SELECT split_part(col, ',', 1) AS col1
, split_part(col, ',', 2) AS col2
, split_part(col, ',', 3) AS col3
, split_part(col, ',', 4) AS col4
FROM tbl;
Add as many lines as you have items in col
(the possible maximum). Columns exceeding data items will be empty strings (''
).
It's Hebrew for "double colon".
Declaring a variable final
or not declaring it final
, but keeping it effectively final may result (depends on compiler) in different bytecode.
Let's have a look on a small example:
public static void main(String[] args) {
final boolean i = true; // 6 // final by declaration
boolean j = true; // 7 // effectively final
if (i) { // 9
System.out.println(i);// 10
}
if (!i) { // 12
System.out.println(i);// 13
}
if (j) { // 15
System.out.println(j);// 16
}
if (!j) { // 18
System.out.println(j);// 19
}
}
The corresponding bytecode of the main
method (Java 8u161 on Windows 64 Bit):
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iconst_1
3: istore_2
4: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
7: iconst_1
8: invokevirtual #22 // Method java/io/PrintStream.println:(Z)V
11: iload_2
12: ifeq 22
15: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
18: iload_2
19: invokevirtual #22 // Method java/io/PrintStream.println:(Z)V
22: iload_2
23: ifne 33
26: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
29: iload_2
30: invokevirtual #22 // Method java/io/PrintStream.println:(Z)V
33: return
The corresponding line number table:
LineNumberTable:
line 6: 0
line 7: 2
line 10: 4
line 15: 11
line 16: 15
line 18: 22
line 19: 26
line 21: 33
As we see the source code at lines 12
, 13
, 14
doesn't appear in the byte code. That's because i
is true
and will not change it's state. Thus this code is unreachable (more in this answer). For the same reason the code at line 9
misses too. The state of i
doesn't have to be evaluated since it is true
for sure.
On the other hand though the variable j
is effectively final it's not processed in the same way. There are no such optimizations applied. The state of j
is evaluated two times. The bytecode is the same regardless of j
being effectively final.
The whole lot is encrypted† - all the headers. That's why SSL on vhosts doesn't work too well - you need a dedicated IP address because the Host header is encrypted.
†The Server Name Identification (SNI) standard means that the hostname may not be encrypted if you're using TLS. Also, whether you're using SNI or not, the TCP and IP headers are never encrypted. (If they were, your packets would not be routable.)
There is a function called append for ediitext which appends the string value to current edittext value and places the cursor at the end of the value. You can have the string value as the current ediitext value itself and call append();
myedittext.append("current_this_edittext_string");
30 2 * * * wget https://www.yoursite.com/your_function_name
The first part is for setting cron job and the next part to call your function.
Another option - to convert to C++ besides Shed Skin - is Pythran.
To quote High Performance Python by Micha Gorelick and Ian Ozsvald:
Pythran is a Python-to-C++ compiler for a subset of Python that includes partial
numpy
support. It acts a little like Numba and Cython—you annotate a function’s arguments, and then it takes over with further type annotation and code specialization. It takes advantage of vectorization possibilities and of OpenMP-based parallelization possibilities. It runs using Python 2.7 only.One very interesting feature of Pythran is that it will attempt to automatically spot parallelization opportunities (e.g., if you’re using a
map
), and turn this into parallel code without requiring extra effort from you. You can also specify parallel sections usingpragma omp
> directives; in this respect, it feels very similar to Cython’s OpenMP support.Behind the scenes, Pythran will take both normal Python and numpy code and attempt to aggressively compile them into very fast C++—even faster than the results of Cython.
You should note that this project is young, and you may encounter bugs; you should also note that the development team are very friendly and tend to fix bugs in a matter of hours.
In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.
This may help... use the following code and browse the folder you want to set as the working folder
setwd(choose.dir())
I have some problems with jquery mobile 1.4.5. For example it seems accepting format change only passing from "option". And there are some refresh problem with the calendar using "option". For all that have the same problems I can suggest this code:
$( "#mydatepicker" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
$( "#mydatepicker" ).datepicker( "setDate", new Date());
$('.ui-datepicker-calendar').hide();
Look here, the operator used is !!
.
I.e. [1,2,3]!!1
gives you 2
, since lists are 0-indexed.
If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before
//HTML
<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
<div class="morph-button morph-button-overlay morph-button-fixed">
<button id="user-interface" type="button">MORE INFO</button>
<!--a id="user-interface" href="javascript:void(0)">popup</a-->
<div class="morph-content">
<div>
<div class="content-style-overlay">
<span class="icon icon-close">Close the overlay</span>
<h2>About Parsley</h2>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
</div>
</div>
</div>
</div>
</div>
//CSS
/* Blur - doesn't work on IE */
.blur-on, .blur-element {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
-webkit-transition: all 5s linear;
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
.blur-off {
-webkit-filter: blur(0px) !important;
-moz-filter : blur(0px) !important;
-o-filter : blur(0px) !important;
-ms-filter : blur(0px) !important;
filter : blur(0px) !important;
}
.blur-bgimage:before {
content: "";
position: absolute;
height: 20%; width: 20%;
background-size: cover;
background: inherit;
z-index: -1;
transform: scale(5);
transform-origin: top left;
filter: blur(2px);
-moz-transform: scale(5);
-moz-transform-origin: top left;
-moz-filter: blur(2px);
-webkit-transform: scale(5);
-webkit-transform-origin: top left;
-webkit-filter: blur(2px);
-o-transform: scale(5);
-o-transform-origin: top left;
-o-filter: blur(2px);
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
//Javascript
function blurBehindPopup() {
if(blurredElements.length == 0) {
for(var i=0; i < document.body.children.length; i++) {
var element = document.body.children[i];
if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
classie.addClass( element, 'blur-element' );
blurredElements.push(element);
}
}
} else {
for(var i=0; i < blurredElements.length; i++) {
classie.addClass( blurredElements[i], 'blur-element' );
}
}
}
function unblurBehindPopup() {
for(var i=0; i < blurredElements.length; i++) {
classie.removeClass( blurredElements[i], 'blur-element' );
}
}
I solved this problem by adding a variable in the token data:
softexp - I set this to 5 mins (300 seconds)
I set expiresIn
option to my desired time before the user will be forced to login again. Mine is set to 30 minutes. This must be greater than the value of softexp
.
When my client side app sends request to the server API (where token is required, eg. customer list page), the server checks whether the token submitted is still valid or not based on its original expiration (expiresIn
) value. If it's not valid, server will respond with a status particular for this error, eg. INVALID_TOKEN
.
If the token is still valid based on expiredIn
value, but it already exceeded the softexp
value, the server will respond with a separate status for this error, eg. EXPIRED_TOKEN
:
(Math.floor(Date.now() / 1000) > decoded.softexp)
On the client side, if it received EXPIRED_TOKEN
response, it should renew the token automatically by sending a renewal request to the server. This is transparent to the user and automatically being taken care of the client app.
The renewal method in the server must check if the token is still valid:
jwt.verify(token, secret, (err, decoded) => {})
The server will refuse to renew tokens if it failed the above method.
$header3 = @("Field_1","Field_2","Field_3","Field_4","Field_5")
Import-Csv $fileName -Header $header3 -Delimiter "`t" | select -skip 3 | Foreach-Object {
$record = $indexName
foreach ($property in $_.PSObject.Properties){
#doSomething $property.Name, $property.Value
if($property.Name -like '*TextWrittenAsNumber*'){
$record = $record + "," + '"' + $property.Value + '"'
}
else{
$record = $record + "," + $property.Value
}
}
$array.add($record) | out-null
#write-host $record
}
If you have a typical table structure with an auto-incrementing primary key column in which rows are never deleted, the following will be the fastest way to determine the record count and should work similarly across most ANSI compliant databases:
SELECT TOP(1) <primarykeyfield> FROM <table> ORDER BY <primarykeyfield> DESC;
I work with MS SQL tables containing billions of rows that require sub-second response times for data, including record counts. A similar SELECT COUNT(*) would take minutes to process by comparison.
regarding the recommended answer's code,
For my bot the recommended answer did not work. This is because I'm using Chrome which is requiring me to use KEYEVENTF_SCANCODE in my dwFlags.
To get his code to work I had to modify these code blocks:
class KEYBDINPUT(ctypes.Structure):
_fields_ = (("wVk", wintypes.WORD),
("wScan", wintypes.WORD),
("dwFlags", wintypes.DWORD),
("time", wintypes.DWORD),
("dwExtraInfo", wintypes.ULONG_PTR))
def __init__(self, *args, **kwds):
super(KEYBDINPUT, self).__init__(*args, **kwds)
# some programs use the scan code even if KEYEVENTF_SCANCODE
# isn't set in dwFflags, so attempt to map the correct code.
#if not self.dwFlags & KEYEVENTF_UNICODE:l
#self.wScan = user32.MapVirtualKeyExW(self.wVk,
#MAPVK_VK_TO_VSC, 0)
# ^MAKE SURE YOU COMMENT/REMOVE THIS CODE^
def PressKey(keyCode):
input = INPUT(type=INPUT_KEYBOARD,
ki=KEYBDINPUT(wScan=keyCode,
dwFlags=KEYEVENTF_SCANCODE))
user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(input))
def ReleaseKey(keyCode):
input = INPUT(type=INPUT_KEYBOARD,
ki=KEYBDINPUT(wScan=keyCode,
dwFlags=KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP))
user32.SendInput(1, ctypes.byref(input), ctypes.sizeof(input))
time.sleep(5) # sleep to open browser tab
PressKey(0x26) # press right arrow key
time.sleep(2) # hold for 2 seconds
ReleaseKey(0x26) # release right arrow key
I hope this helps someone's headache!
This is using ms-Dropdown : https://github.com/marghoobsuleman/ms-Dropdown
Data resource is json. But you dont need to use json. If you want you can use with css.
Css example : https://github.com/marghoobsuleman/ms-Dropdown/tree/master/examples
Json Example : http://jsfiddle.net/tcibikci/w3rdhj4s/6
HTML
<div id="byjson"></div>
Script
<script>
var jsonData = [
{description:'Choos your payment gateway', value:'', text:'Payment Gateway'},
{image:'https://via.placeholder.com/50', description:'My life. My card...', value:'amex', text:'Amex'},
{image:'https://via.placeholder.com/50', description:'It pays to Discover...', value:'Discover', text:'Discover'},
{image:'https://via.placeholder.com/50', title:'For everything else...', description:'For everything else...', value:'Mastercard', text:'Mastercard'},
{image:'https://via.placeholder.com/50', description:'Sorry not available...', value:'cash', text:'Cash on devlivery', disabled:true},
{image:'https://via.placeholder.com/50', description:'All you need...', value:'Visa', text:'Visa'},
{image:'https://via.placeholder.com/50', description:'Pay and get paid...', value:'Paypal', text:'Paypal'}
];
$("#byjson").msDropDown({byJson:{data:jsonData, name:'payments2'}}).data("dd");
}
</script>
Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position. Example 1:
loop1:
for(int i= 0; i<6; i++){
for(int j=0; j<5; j++){
if(i==3)
break loop1;
}
}
suppose there are 3 loops and you want to terminate the loop3: Example 2:
loop3:
for(int i= 0; i<6; i++){
loop2:
for(int k= 0; k<6; k++){
loop1:
for(int j=0; j<5; j++){
if(i==3)
break loop3;
}
}
}
To be able to call notify() you need to synchronize on the same object.
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
Search for [ ]{2,}
. This will find two or more adjacent spaces anywhere within the line. It will also match leading and trailing spaces as well as lines that consist entirely of spaces. If you don't want that, check out Alexander's answer.
Actually, you can leave out the brackets, they are just for clarity (otherwise the space character that is being repeated isn't that well visible :)).
The problem with \s{2,}
is that it will also match newlines on Windows files (where newlines are denoted by CRLF
or \r\n
which is matched by \s{2}
.
If you also want to find multiple tabs and spaces, use [ \t]{2,}
.
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
Use $#
to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:
if [ $# -ne 2 ]; then
usage;
fi
Next, check if $1
equals -t
, otherwise an unknown flag was used:
if [ "$1" != "-t" ]; then
usage;
fi
Finally store $2
in FLAG
:
FLAG=$2
Note: usage()
is some function showing the syntax. For example:
function usage {
cat << EOF
Usage: script.sh -t <application>
Performs some activity
EOF
exit 1
}
Just convert it to timestamp
datetime.datetime.fromtimestamp(ms/1000.0)
I found this solution to work for me. Just call a javascript function like this:
action="javascript:myFunction();"
Then you have the html5 validation... really simple :-)
An example with a little less stringified html:
var container = $('#my-container'),
table = $('<table>');
users.forEach(function(user) {
var tr = $('<tr>');
['ID', 'Name', 'Address'].forEach(function(attr) {
tr.append('<td>' + user[attr] + '</td>');
});
table.append(tr);
});
container.append(table);
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
just add different .gitignore files to mini project 1 and mini project 2. Each of the .gitignore files should /node_modules and you're good to go.
You should find all HTTP headers in the $_SERVER
global variable prefixed with HTTP_
uppercased and with dashes (-) replaced by underscores (_).
For instance your X-Requested-With
can be found in:
$_SERVER['HTTP_X_REQUESTED_WITH']
It might be convenient to create an associative array from the $_SERVER
variable. This can be done in several styles, but here's a function that outputs camelcased keys:
$headers = array();
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
$headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
Now just use $headers['XRequestedWith']
to retrieve the desired header.
PHP manual on $_SERVER
: http://php.net/manual/en/reserved.variables.server.php
In ksh
,bash
,sh
:
$ count7=0
$ count1=5
$
$ (( count7 += count1 ))
$ echo $count7
$ 5
by using Listbuffer we can save data into single file:
import java.io.FileWriter
import org.apache.spark.sql.SparkSession
import scala.collection.mutable.ListBuffer
val text = spark.read.textFile("filepath")
var data = ListBuffer[String]()
for(line:String <- text.collect()){
data += line
}
val writer = new FileWriter("filepath")
data.foreach(line => writer.write(line.toString+"\n"))
writer.close()
In my case i found better to use "string.search".
var str = "Some very very very long string";
var n = str.search("very");
In case it would be helpful for someone.
its too simple, you can just type "cache:" before the URL of the page. for example
if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page
this will show you the last webcache of the page.see here:
But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.
The slowdown is not necessarily the same with any compiler.
I haven't used Delphi or Kylix but back in the MS-DOS days, a Turbo Pascal program would compile almost instantaneously, while the equivalent Turbo C++ program would just crawl.
The two main differences were a very strong module system and a syntax that allowed single-pass compilation.
It's certainly possible that compilation speed just hasn't been a priority for C++ compiler developers, but there are also some inherent complications in the C/C++ syntax that make it more difficult to process. (I'm not an expert on C, but Walter Bright is, and after building various commercial C/C++ compilers, he created the D language. One of his changes was to enforce a context-free grammar to make the language easier to parse.)
Also, you'll notice that generally Makefiles are set up so that every file is compiled separately in C, so if 10 source files all use the same include file, that include file is processed 10 times.
Thre are 2 ways to run Action Query in MS Access VBA:
DoCmd.OpenQuery
statement. This allows you to control these warnings:BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs
Function RunActionQuery(QueryName As String)
On Error GoTo Hell 'Set Error Hanlder
DoCmd.SetWarnings True 'Turn On Warnings
DoCmd.OpenQuery QueryName 'Execute Action Query
DoCmd.SetWarnings False 'Turn On Warnings
Exit Function
Hell:
If Err.Number = 2501 Then 'If Query Was Canceled
MsgBox Err.Description, vbInformation
Else 'Everything else
MsgBox Err.Description, vbCritical
End If
End Function
CurrentDb.Execute
method. This alows you to keep Action Query failures
under control. The SetWarnings flag does not affect it. Query is executed always without warnings.Function RunActionQuery()
'To Catch the Query Error use dbFailOnError option
On Error GoTo Hell
CurrentDb.Execute "Query1", dbFailOnError
Exit Function
Hell:
Debug.Print Err.Description
End Function
It is worth noting that the dbFailOnError
option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified
In addition, you can use DoCmd.Hourglass True
and DoCmd.Hourglass False
to control the mouse pointer if your Query takes longer
You can use .change
for what you want
$("input[@name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '@'. Correct way to select is:
$("input[name='lom']")
The find
command may help
find $PWD -name ex*
find $PWD -name example.log
Lists all the files in or below the current directory with names matching the pattern. You can simplify it if you will only get a few results (e.g. directory near bottom of tree containing few files), just
find $PWD
I use this on Solaris 10, which doesn't have the other utilities mentioned.
AND (both classes)
var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");
OR (at least one class)
var list = document.querySelectorAll(".class1,.class2");
XOR (one class but not the other)
var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");
NAND (not both classes)
var list = document.querySelectorAll(":not(.class1),:not(.class2)");
NOR (not any of the two classes)
var list = document.querySelectorAll(":not(.class1):not(.class2)");
You can try some positioning tricks. You can put the input in a div with position: relative
and a fixed height, then on the input have position: absolute; left: 0; right: 0;
, and any padding you like.
A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use. -- Extract from book Design Patterns in C#.
Ned Batchelder has posted a short script that will unmarshal a .pyc file and disassemble any code objects within, so you'll be able to see the Python bytecode.
It looks like with newer versions of Python, you'll need to comment out the lines that set modtime
and print it (but don't comment the line that sets moddate
).
Turning that back into Python source would be somewhat more difficult, although theoretically possible. I assume all these programs that work for older versions of Python do that.
If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file
I've done this with nock, like so:
import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'
axios.defaults.adapter = httpAdapter
describe('foo', () => {
it('bar', () => {
nock('https://example.com:443')
.get('/example')
.reply(200, 'some payload')
// test...
})
})
I have found a new workaround, different from any other that I have seen, by disabling the native iOS zoom, and instead implementing zoom functionality in JavaScript.
An excellent background on the various other solutions to the zoom/orientation problem is by Sérgio Lopes: A fix to the famous iOS zoom bug on orientation change to portrait.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" id="viewport" content="user-scalable=no,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0" />
<title>Robocat mobile Safari zoom fix</title>
<style>
body {
padding: 0;
margin: 0;
}
#container {
-webkit-transform-origin: 0px 0px;
-webkit-transform: scale3d(1,1,1);
/* shrink-to-fit needed so can measure width of container http://stackoverflow.com/questions/450903/make-css-div-width-equal-to-contents */
display: inline-block;
*display: inline;
*zoom: 1;
}
#zoomfix {
opacity: 0;
position: absolute;
z-index: -1;
top: 0;
left: 0;
}
</style>
</head>
<body>
<input id="zoomfix" disabled="1" tabIndex="-1">
<div id="container">
<style>
table {
counter-reset: row cell;
background-image: url(http://upload.wikimedia.org/wikipedia/commons/3/38/JPEG_example_JPG_RIP_010.jpg);
}
tr {
counter-increment: row;
}
td:before {
counter-increment: cell;
color: white;
font-weight: bold;
content: "row" counter(row) ".cell" counter(cell);
}
</style>
<table cellspacing="10">
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
<tr><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td><td>
</table>
</div>
<script>
(function() {
var viewportScale = 1;
var container = document.getElementById('container');
var scale, originX, originY, relativeOriginX, relativeOriginY, windowW, windowH, containerW, containerH, resizeTimer, activeElement;
document.addEventListener('gesturestart', function(event) {
scale = null;
originX = event.pageX;
originY = event.pageY;
relativeOriginX = (originX - window.pageXOffset) / window.innerWidth;
relativeOriginY = (originY - window.pageYOffset) / window.innerHeight;
windowW = window.innerWidth;
windowH = window.innerHeight;
containerW = container.offsetWidth;
containerH = container.offsetHeight;
});
document.addEventListener('gesturechange', function(event) {
event.preventDefault();
if (originX && originY && event.scale && event.pageX && event.pageY) {
scale = event.scale;
var newWindowW = windowW / scale;
if (newWindowW > containerW) {
scale = windowW / containerW;
}
var newWindowH = windowH / scale;
if (newWindowH > containerH) {
scale = windowH / containerH;
}
if (viewportScale * scale < 0.1) {
scale = 0.1/viewportScale;
}
if (viewportScale * scale > 10) {
scale = 10/viewportScale;
}
container.style.WebkitTransformOrigin = originX + 'px ' + originY + 'px';
container.style.WebkitTransform = 'scale3d(' + scale + ',' + scale + ',1)';
}
});
document.addEventListener('gestureend', function() {
if (scale && (scale < 0.95 || scale > 1.05)) {
viewportScale *= scale;
scale = null;
container.style.WebkitTransform = '';
container.style.WebkitTransformOrigin = '';
document.getElementById('viewport').setAttribute('content', 'user-scalable=no,initial-scale=' + viewportScale + ',minimum-scale=' + viewportScale + ',maximum-scale=' + viewportScale);
document.body.style.WebkitTransform = 'scale3d(1,1,1)';
// Without zoomfix focus, after changing orientation and zoom a few times, the iOS viewport scale functionality sometimes locks up (and completely stops working).
// The reason I thought this hack would work is because showing the keyboard is the only way to affect the viewport sizing, which forces the viewport to resize (even though the keyboard doesn't actually get time to open!).
// Also discovered another amazing side effect: if you have no meta viewport element, and focus()/blur() in gestureend, zoom is disabled!! Wow!
var zoomfix = document.getElementById('zoomfix');
zoomfix.disabled = false;
zoomfix.focus();
zoomfix.blur();
setTimeout(function() {
zoomfix.disabled = true;
window.scrollTo(originX - relativeOriginX * window.innerWidth, originY - relativeOriginY * window.innerHeight);
// This forces a repaint. repaint *intermittently* fails to redraw correctly, and this fixes the problem.
document.body.style.WebkitTransform = '';
}, 0);
}
});
})();
</script>
</body>
</html>
It could be improved, but for my needs it avoids the major drawbacks that occur with all the other solutions I have seen. So far I have only tested it using mobile Safari on an iPad 2 with iOS4.
The focus()/blur() is a workaround to prevent the occasional lockup of the zoom functionality which can occur after changing orientation and zooming a few times.
Setting the document.body.style forces a full screen repaint, which avoids an occasional intermittent problems where the repaint badly fails after zoom.
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
Here is one more example based on Intl.NumberFormat native api.
var number = 123456.789;_x000D_
_x000D_
// India uses thousands/lakh/crore separators_x000D_
console.log(new Intl.NumberFormat('en-IN', {_x000D_
style: 'currency',_x000D_
currency: 'INR',_x000D_
// limit to six significant digits (Possible values are from 1 to 21)._x000D_
maximumSignificantDigits: 6_x000D_
}).format(number));
_x000D_
I had this issue recently and I resolved it by simply rolling IE8 back to IE7.
My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.
I've got the same error on a fully updated Windows Vista Family 64bit with a .NET application that I've compiled to 32 bit only - the program is installed in the programx86 folder on 64 bit machines. It fails with this error message even with 2007 access database provider installed, with/wiothout the SP2 of the same installed, IIS installed and app pool set for 32bit app support... yes I've tried every solution everywhere and still no success.
I switched my app to ACE OLE DB.12.0 because JET4.0 was failing on 64bit machines - and it's no better :-/ The most promising thread I've found was this:
http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/
but when you try to install the 64 bit "2010 Office System Driver Beta: Data Connectivity Components" it tells you that you can't install the 64 bit version without uninstalling all 32bit office applications... and installing the 32 bit version of 2010 Office System Driver Beta: Data Connectivity Components doesn't solve the initial problem, even with "Microsoft.ACE.OLEDB.12.0" as provider instead of "Microsoft.ACE.OLEDB.14.0" which that page (and others) recommend.
My next attempt will be to follow this post:
The issue is due to the wrong flavor of OLEDB32.DLL and OLEDB32r.DLL being registered on the server. If the 64 bit versions are registered, they need to be unregistered, and then the 32 bit versions registered instead. To fix this, unregister the versions located in %Program Files%/Common Files/System/OLE DB. Then register the versions at the same path but in the %Program Files (x86)% directory.
Has anyone else had so much trouble with both JET4.0 and OLEDB ACE providers on 64 bit machines? Has anyone found a solution if none of the others work?
I had to do following:
2.Go to App releases -> Manage production -> Create release
3.Click continue on Google Play App Signing
4.Create upload certificate by running "keytool -genkey -v -keystore c:\path\to\cert.keystore -alias uploadKey -keyalg RSA -keysize 2048 -validity 10000"
5.Sign your apk with generated certificate (c:\path\to\cert.keystore)
6.Upload signed apk in App releases -> Manage production -> Edit release
7.By uploading apk, certificate generated in step 4 has been added to App Signing certificates and became your signing cert for all future builds.
select ROUND(CASE
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0) from Tablename where ID="123"
There looks to be an issue with the latest version of the pip module pytesseract=0.3.7. I have downgraded it to pytesseract=0.3.6 and don't see the error.
You can do it by using the td's index:
var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
This is what I did.
$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, newValue, oldValue) {
var selected = $(e.currentTarget).val();
});
Assuming that call_me is a global function, so you don't expect this to be set.
var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);
it's not true the clear()
function clear the Arraylist and start from index 0
The std::string object returned by ss.str() is a temporary object that will have a life time limited to the expression. So you cannot assign a pointer to a temporary object without getting trash.
Now, there is one exception: if you use a const reference to get the temporary object, it is legal to use it for a wider life time. For example you should do:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const std::string& resultstr = ss.str();
const char* cstr2 = resultstr.c_str();
cout << cstr1 // Prints correctly
<< cstr2; // No more error : cstr2 points to resultstr memory that is still alive as we used the const reference to keep it for a time.
system("PAUSE");
return 0;
}
That way you get the string for a longer time.
Now, you have to know that there is a kind of optimisation called RVO that say that if the compiler see an initialization via a function call and that function return a temporary, it will not do the copy but just make the assigned value be the temporary. That way you don't need to actually use a reference, it's only if you want to be sure that it will not copy that it's necessary. So doing:
std::string resultstr = ss.str();
const char* cstr2 = resultstr.c_str();
would be better and simpler.
If you want to recursively convert the entire array into an Object type (stdClass) then , below is the best method and it's not time-consuming or memory deficient especially when you want to do a recursive (multi-level) conversion compared to writing your own function.
$array_object = json_decode(json_encode($array));
All answers here - hacks. I've found better way to scroll collection view somewhere after relaodData:
Subclass collection view layout what ever layout you use, override method prepareLayout, after super call set what ever offset you need.
ex: https://stackoverflow.com/a/34192787/1400119
You can try out this code. Since you cannot override valueOf
method you have to define a custom method (getEnum
in the sample code below) which returns the value that you need and change your client to use this method instead.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private String value;
RandomEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return this.getValue();
}
public static RandomEnum getEnum(String value) {
for(RandomEnum v : values())
if(v.getValue().equalsIgnoreCase(value)) return v;
throw new IllegalArgumentException();
}
}
SimpleDateFormat has a constructor which takes the locale, have you tried that?
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Something like
new SimpleDateFormat("your-pattern-here", Locale.getDefault());
On a modern GNU/Linux system you can see the available network interfaces listing the content of /sys/class/net/
, for example:
$ ls /sys/class/net/
enp0s25 lo virbr0 virbr0-nic wlp2s0
You can check if an interface is up
looking at operstate
in the device directory. For example, here's how you can see if enp0s25
is up:
$ cat /sys/class/net/enp0s25/operstate
up
You can then get the MAC address of that interface with:
$ cat /sys/class/net/enp0s25/address
ff:00:ff:e9:84:a5
For example, here's a simple bash script that prints MAC addresses for active interfaces:
#!/bin/bash
# getmacifup.sh: Print active NICs MAC addresses
D='/sys/class/net'
for nic in $( ls $D )
do
echo $nic
if grep -q up $D/$nic/operstate
then
echo -n ' '
cat $D/$nic/address
fi
done
And here's its output on a system with an ethernet and a wifi interface:
$ ./getmacifup.sh
enp0s25
ff:00:ff:e9:84:a5
lo
wlp2s0
For details see the Kernel documentation
Remember also that from 2015 most GNU/Linux distributions switched to systemd
, and don't use ethX
interface naming scheme any more - now they use a more robust naming convention based on the hardware topology, see:
The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely
To achieve what you want, I'd either
CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:
td {
height: 200px;
}
td div {
/* div will now take up full 200px of parent's height */
height: 100%;
}
Since it seems like your <td>
is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:
.thatSetsABackgroundWithAnIcon {
/* Makes the <div> a coordinate map for the icon */
position: relative;
/* Takes the full height of its parent <td>. For this to work, the <td>
must have an explicit height set. */
height: 100%;
}
.thatSetsABackgroundWithAnIcon .theIcon {
position: absolute;
bottom: 0;
right: 0;
}
With the table cell markup like so:
<td class="thatSetsABackground">
<div class="thatSetsABackgroundWithAnIcon">
<dl>
<dt>yada
</dt>
<dd>yada
</dd>
</dl>
<img class="theIcon" src="foo-icon.png" alt="foo!"/>
</div>
</td>
Edit: using jQuery to set div's height
If you keep the <div>
as a child of the <td>
, this snippet of jQuery will properly set its height:
// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
var $div = $(this);
// Set the div's height to its parent td's height
$div.height($div.closest('td').height());
});
This works fine on 2005 (if the plan is in the cache)
USE YourDb;
SELECT qt.[text] AS [SP Name],
qs.last_execution_time,
qs.execution_count AS [Execution Count]
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE qt.dbid = DB_ID()
AND objectid = OBJECT_ID('YourProc')
It's rather interesting to see how .NET get this internally to say the least... It's as "simple" as below:
namespace System.Threading
{
using System;
using System.Runtime.CompilerServices;
internal static class PlatformHelper
{
private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 0x7530;
private static volatile int s_lastProcessorCountRefreshTicks;
private static volatile int s_processorCount;
internal static bool IsSingleProcessor
{
get
{
return (ProcessorCount == 1);
}
}
internal static int ProcessorCount
{
get
{
int tickCount = Environment.TickCount;
int num2 = s_processorCount;
if ((num2 == 0) || ((tickCount - s_lastProcessorCountRefreshTicks) >= 0x7530))
{
s_processorCount = num2 = Environment.ProcessorCount;
s_lastProcessorCountRefreshTicks = tickCount;
}
return num2;
}
}
}
}
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});
To achieve this you can try below steps:
You need to use a hashbang. Add it to the first line of your python script.
#! <full path of python interpreter>
Then change the file permissions, and add the executing permission.
chmod +x <filename>
And finally execute it using
./<filename>
If its in the current directory,
You could use the IndexOf
method to get a location of the string, and split it using that position, and the length of the search string.
You can also use regular expression. A simple google search turned out with this
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string value = "cat\r\ndog\r\nanimal\r\nperson";
// Split the string on line breaks.
// ... The return value from Split is a string[] array.
string[] lines = Regex.Split(value, "\r\n");
foreach (string line in lines) {
Console.WriteLine(line);
}
}
}
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse
method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
To Post Rest/JSON Request
We can simply use request package and save the values we have to send in Json variable.
First install the require package in your console by npm install request --save
var request = require('request');
var options={
'key':'28',
'key1':'value',
'key2':'value'
}
request({
url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?
minorRev="+options.key+
"&cid="+options.key1+
"&apiKey="+options.key2,
method:"POST",
json:true},function(error,response,body){
console.log(body)
}
);
Use regex:
result = result.replaceAll("\n.*", "");
replaceAll()
uses regex to find its target, which I have replaced with "nothing" - effectively deleting the target.
The target I've specified by the regex \n.*
means "the newline char and everything after"
Another approach might be to have the top and bottom labels have constraints relative to the view top and bottom, respectively, and have the middle view have top and bottom constraints relative to the first and third view, respectively.
Note that you have more control over constraints than it might seem by dragging views close to one another until guiding dashed lines appear - these indicate constraints between the two objects that will be formed instead of between the object and the superview.
In this case you would then want to alter the constraints to be "Greater than or equal to" the desired value, instead of "equal to" to allow them to resize. Not sure if this will do exactly what you want.
You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:
sudo chmod 777 markers.xml
You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.
The first answer you posted (System is a built-in class...) is pretty spot on.
You can add that the System
class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out
printstream to the native output stream associated with the "standard out" (console).
I got this error in chrome when I had an unterminated string after the line that the error pointed to. After closing the string the error went away.
Example with error:
var file = files[i]; // SyntaxError: Unexpected token ILLEGAL
jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
+ "<a href=\"javascript: something('"+file.id+');\">Error is here</a>";
Example without error:
var file = files[i]; // No error
jQuery('#someDiv').innerHTML = file.name + " (" + formatSize(file.size) + ") "
+ "<a href=\"javascript: something('"+file.id+"');\">Error was here</a>";
As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema
namespace.
1) Yes, a select with NOLOCK
will complete faster than a normal select.
2) Yes, a select with NOLOCK
will allow other queries against the effected table to complete faster than a normal select.
Why would this be?
NOLOCK
typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.
You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a NOLOCK
read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.
You really have no way to know what the state of the data is.
If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then NOLOCK
is a good way to boost performance for these queries and avoid having them negatively impact database performance.
Always use the NOLOCK
hint with great caution and treat any data it returns suspiciously.
I just want to clarify that, in jQuery,
Elements can be considered hidden for several reasons:
- They have a CSS display value of none.
- They are form elements with type="hidden".
- Their width and height are explicitly set to 0.
- An ancestor element is hidden, so the element is not shown on the page.
Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation.
if($('.element').is(':hidden')) {
// Do something
}
ENGINE=MEMORY
is not supported when table contains BLOB
/TEXT
columns
first of all,
be sure that there is a post
if(isset($_POST['username'])) {
// check if the username has been set
}
second, and most importantly, sanitize the data, meaning that
$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";
is deadly dangerous, instead use
$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";
and please research the subject sql injection
okkk you have take id INTEGER PRIMARY KEY AUTOINCREMENT and still u r passing value... that is the problem :) for more detail see this still getting problem then post code and logcat
Both are fine, but only the first one will allow you to inspect the Exception itself.
Both swallow the Exception, and you should only catch exceptions to do something meaningfull. Hiding a problem is not meaningful!
$(document).ready(function () {
setTimeout(function () {
$(".imgthumbnew").click(function () {
$("#divVideo video").attr({
"src": $(this).data("item"),
"autoplay": "autoplay",
})
})
}, 2000);
}
});
here ".imgthumbnew" is the class of images which are thumbs of videos, an extra attribute is given to them which have video url. u can change according to your convenient.
i would suggest you to give an ID to ur Video tag it would be easy to handle.
Try with this link: http://download.eclipse.org/egit/github/updates
1)Go to Help-> Install new Software
2)Click on Add...
3)Name: eGit Location:http://download.eclipse.org/egit/github/updates
4)Click on OK
5)Accept the licence.
You are good to go
I know this is 3 years old, but for everyone reading this now: Don't stick to VST, AU or any vendor's format. Steinberg has stopped supporting VST2, and people are in trouble porting their code to newer formats, because it's too tied to VST2.
These tutorials cover creating plugins that run on Win/Mac, 32/64, all plugin formats from the same code base.
It happened with me as well and fixed in following way:
Created expression based connection string and saved password in a variable and used it.
The difference between Response.Write()
and Response.Output.Write()
in ASP.NET. The short answer is that the latter gives you String.Format-style
output and the former doesn't. The long answer follows.
In ASP.NET the Response
object is of type HttpResponse
and when you say Response.Write
you're really saying (basically) HttpContext.Current.Response.Write
and calling one of the many overloaded Write
methods of HttpResponse
.
Response.Write
then calls .Write()
on it's internal TextWriter
object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse
also has a Property called Output
that is of type, yes, TextWriter
, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can do the Response
whatever a TextWriter
will let you. Now, TextWriters support a Write()
method aka String.Format
, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this is happening:
public virtual void Write(string format, params object[] arg)
{
this.Write(string.Format(format, arg));
}
There's a much easier way than recompiling PHP. Just yum install the required mbstring library:
Example: How to install PHP mbstring on CentOS 6.2
yum --enablerepo=remi install php-mbstring
Oh, and don't forget to restart apache afterward.
I met this problem because I use request.js which writen base on axios
And I already set a defaults.headers in request.js
import axios from 'axios'
const request = axios.create({
baseURL: '',
timeout: 15000
})
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
here is how I solve this
instead of
request.post('/manage/product/upload.do',
param,config
)
I use axios directly send request,and didn't add config
axios.post('/manage/product/upload.do',
param
)
hope this can solve your problem
Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length
instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.
if (!str.trim().length) {
console.log('str is empty!');
}
You can read more about trim here.
If still not working you can call garbage collector to close the file and free up memory
System.gc();
if(new File("./__tmp.txt").delete()){
System.out.println("OK");
}
Don't forget to close that file, if any previous opening using code snippet fio.close()
I tested in Java 1.8, works well.
How about using colors to differentiate between "apples" and "oranges" and spacing to separate "A", "B" and "C"?
Something like this:
from pylab import plot, show, savefig, xlim, figure, \
hold, ylim, legend, boxplot, setp, axes
# function for setting the colors of the box plots pairs
def setBoxColors(bp):
setp(bp['boxes'][0], color='blue')
setp(bp['caps'][0], color='blue')
setp(bp['caps'][1], color='blue')
setp(bp['whiskers'][0], color='blue')
setp(bp['whiskers'][1], color='blue')
setp(bp['fliers'][0], color='blue')
setp(bp['fliers'][1], color='blue')
setp(bp['medians'][0], color='blue')
setp(bp['boxes'][1], color='red')
setp(bp['caps'][2], color='red')
setp(bp['caps'][3], color='red')
setp(bp['whiskers'][2], color='red')
setp(bp['whiskers'][3], color='red')
setp(bp['fliers'][2], color='red')
setp(bp['fliers'][3], color='red')
setp(bp['medians'][1], color='red')
# Some fake data to plot
A= [[1, 2, 5,], [7, 2]]
B = [[5, 7, 2, 2, 5], [7, 2, 5]]
C = [[3,2,5,7], [6, 7, 3]]
fig = figure()
ax = axes()
hold(True)
# first boxplot pair
bp = boxplot(A, positions = [1, 2], widths = 0.6)
setBoxColors(bp)
# second boxplot pair
bp = boxplot(B, positions = [4, 5], widths = 0.6)
setBoxColors(bp)
# thrid boxplot pair
bp = boxplot(C, positions = [7, 8], widths = 0.6)
setBoxColors(bp)
# set axes limits and labels
xlim(0,9)
ylim(0,9)
ax.set_xticklabels(['A', 'B', 'C'])
ax.set_xticks([1.5, 4.5, 7.5])
# draw temporary red and blue lines and use them to create a legend
hB, = plot([1,1],'b-')
hR, = plot([1,1],'r-')
legend((hB, hR),('Apples', 'Oranges'))
hB.set_visible(False)
hR.set_visible(False)
savefig('boxcompare.png')
show()
I have had a similar problem before where it turned out to be the web brower (chrome in my case) that was the issue.
If you are using chrome, try launching it so:
For Windows:
1) Create a shortcut to Chrome on your desktop. Right-click on the shortcut and choose Properties, then switch to “Shortcut” tab.
2) In the “Target” field, append the following: –args –disable-web-security
For Mac, Open a terminal window and run this from command-line: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security
Above info from:
I will throw in what worked for me in the end. I needed to remove the initial commit on a repository as quarantined data had been misplaced, the commit had already been pushed.
Make sure you are are currently on the right branch.
git checkout master
git update-ref -d HEAD
git commit -m "Initial commit
git push -u origin master
This was able to resolve the problem.
Important
This was on an internal repository which was not publicly accessible, if your repository was publicly accessible please assume anything you need to revert has already been pulled down by someone else.
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
If youtube-dl
is a terminal program, you can use the subprocess
module to access the data you want.
Check out this link for more details: Calling an external command in Python
Why is $observe different than $watch?
The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.
$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}"
, the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.
See $observe & $set in compile.js
Use merge()
:
$request->merge([
'user_id' => $modified_user_id_here,
]);
Simple! No need to transfer the entire $request->all()
to another variable.
git checkout
modifies your working tree,git reset
modifies which reference the branch you're on points to,git revert
adds a commit undoing changes.I normally use another way to do the same
using System.Xml;
using System.Net;
using System.IO;
public static void CallWebService()
{
var _url = "http://xxxxxxxxx/Service1.asmx";
var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(
@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">
<SOAP-ENV:Body>
<HelloWorld xmlns=""http://tempuri.org/""
SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<int1 xsi:type=""xsd:integer"">12</int1>
<int2 xsi:type=""xsd:integer"">32</int2>
</HelloWorld>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>");
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
I know this is an old question, but I was struggling to do this with a time period over 2 hours, so this might help someone. Also, several of the answers don't actually plot against time, giving equal space whatever the duration.
Firstly, as @jameswarren says, use a scatter graph. Then right-click the horizontal axis and choose Format Axis.
Under Number, select Time, and at this point you may find your scale goes a bit crazy, because it chooses to scale the axis by days. So go back to Axis Options and select Fixed for the Minimum, Maximum and Major unit scales.
To set the unit to hours, type in 1/24 = 0.0416667 (I used half that to get half-hourly increments). To make this start at a round number, multiply it by your preferred number of hours and type that into the Minimum box. In my case 08:00 = 0.333333
Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.
moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm
I found simple solution to get current date without any parsing error.
Calendar calendar;
calendar = Calendar.getInstance();
String customDate = "" + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
You can execute 'tree' command of Linux shell.
Installation:
~$sudo apt install tree
Using in python
>>> import os
>>> os.system('tree <desired path>')
Example:
>>> os.system('tree ~/Desktop/myproject')
This gives you a cleaner structure and is visually more comprehensive and easy to type.